1 /* 2 * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 // no precompiled headers 26 #include "jvm.h" 27 #include "classfile/classLoader.hpp" 28 #include "classfile/systemDictionary.hpp" 29 #include "classfile/vmSymbols.hpp" 30 #include "code/icBuffer.hpp" 31 #include "code/vtableStubs.hpp" 32 #include "compiler/compileBroker.hpp" 33 #include "compiler/disassembler.hpp" 34 #include "interpreter/interpreter.hpp" 35 #include "logging/log.hpp" 36 #include "logging/logStream.hpp" 37 #include "memory/allocation.inline.hpp" 38 #include "memory/filemap.hpp" 39 #include "memory/universe.hpp" 40 #include "oops/oop.inline.hpp" 41 #include "os_share_solaris.hpp" 42 #include "os_solaris.inline.hpp" 43 #include "prims/jniFastGetField.hpp" 44 #include "prims/jvm_misc.hpp" 45 #include "runtime/arguments.hpp" 46 #include "runtime/atomic.hpp" 47 #include "runtime/extendedPC.hpp" 48 #include "runtime/globals.hpp" 49 #include "runtime/interfaceSupport.inline.hpp" 50 #include "runtime/java.hpp" 51 #include "runtime/javaCalls.hpp" 52 #include "runtime/mutexLocker.hpp" 53 #include "runtime/objectMonitor.hpp" 54 #include "runtime/orderAccess.hpp" 55 #include "runtime/osThread.hpp" 56 #include "runtime/perfMemory.hpp" 57 #include "runtime/sharedRuntime.hpp" 58 #include "runtime/statSampler.hpp" 59 #include "runtime/stubRoutines.hpp" 60 #include "runtime/thread.inline.hpp" 61 #include "runtime/threadCritical.hpp" 62 #include "runtime/timer.hpp" 63 #include "runtime/vm_version.hpp" 64 #include "semaphore_posix.hpp" 65 #include "services/attachListener.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/growableArray.hpp" 73 #include "utilities/macros.hpp" 74 #include "utilities/vmError.hpp" 75 76 // put OS-includes here 77 # include <dlfcn.h> 78 # include <errno.h> 79 # include <exception> 80 # include <link.h> 81 # include <poll.h> 82 # include <pthread.h> 83 # include <setjmp.h> 84 # include <signal.h> 85 # include <stdio.h> 86 # include <alloca.h> 87 # include <sys/filio.h> 88 # include <sys/ipc.h> 89 # include <sys/lwp.h> 90 # include <sys/machelf.h> // for elf Sym structure used by dladdr1 91 # include <sys/mman.h> 92 # include <sys/processor.h> 93 # include <sys/procset.h> 94 # include <sys/pset.h> 95 # include <sys/resource.h> 96 # include <sys/shm.h> 97 # include <sys/socket.h> 98 # include <sys/stat.h> 99 # include <sys/systeminfo.h> 100 # include <sys/time.h> 101 # include <sys/times.h> 102 # include <sys/types.h> 103 # include <sys/wait.h> 104 # include <sys/utsname.h> 105 # include <thread.h> 106 # include <unistd.h> 107 # include <sys/priocntl.h> 108 # include <sys/rtpriocntl.h> 109 # include <sys/tspriocntl.h> 110 # include <sys/iapriocntl.h> 111 # include <sys/fxpriocntl.h> 112 # include <sys/loadavg.h> 113 # include <string.h> 114 # include <stdio.h> 115 116 # define _STRUCTURED_PROC 1 // this gets us the new structured proc interfaces of 5.6 & later 117 # include <sys/procfs.h> // see comment in <sys/procfs.h> 118 119 #define MAX_PATH (2 * K) 120 121 // for timer info max values which include all bits 122 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 123 124 125 // Here are some liblgrp types from sys/lgrp_user.h to be able to 126 // compile on older systems without this header file. 127 128 #ifndef MADV_ACCESS_LWP 129 #define MADV_ACCESS_LWP 7 /* next LWP to access heavily */ 130 #endif 131 #ifndef MADV_ACCESS_MANY 132 #define MADV_ACCESS_MANY 8 /* many processes to access heavily */ 133 #endif 134 135 #ifndef LGRP_RSRC_CPU 136 #define LGRP_RSRC_CPU 0 /* CPU resources */ 137 #endif 138 #ifndef LGRP_RSRC_MEM 139 #define LGRP_RSRC_MEM 1 /* memory resources */ 140 #endif 141 142 // Values for ThreadPriorityPolicy == 1 143 int prio_policy1[CriticalPriority+1] = { 144 -99999, 0, 16, 32, 48, 64, 145 80, 96, 112, 124, 127, 127 }; 146 147 // System parameters used internally 148 static clock_t clock_tics_per_sec = 100; 149 150 // Track if we have called enable_extended_FILE_stdio (on Solaris 10u4+) 151 static bool enabled_extended_FILE_stdio = false; 152 153 // For diagnostics to print a message once. see run_periodic_checks 154 static bool check_addr0_done = false; 155 static sigset_t check_signal_done; 156 static bool check_signals = true; 157 158 address os::Solaris::handler_start; // start pc of thr_sighndlrinfo 159 address os::Solaris::handler_end; // end pc of thr_sighndlrinfo 160 161 address os::Solaris::_main_stack_base = NULL; // 4352906 workaround 162 163 os::Solaris::pthread_setname_np_func_t os::Solaris::_pthread_setname_np = NULL; 164 165 // "default" initializers for missing libc APIs 166 extern "C" { 167 static int lwp_mutex_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; } 168 static int lwp_mutex_destroy(mutex_t *mx) { return 0; } 169 170 static int lwp_cond_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; } 171 static int lwp_cond_destroy(cond_t *cv) { return 0; } 172 } 173 174 // "default" initializers for pthread-based synchronization 175 extern "C" { 176 static int pthread_mutex_default_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; } 177 static int pthread_cond_default_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; } 178 } 179 180 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time); 181 182 static inline size_t adjust_stack_size(address base, size_t size) { 183 if ((ssize_t)size < 0) { 184 // 4759953: Compensate for ridiculous stack size. 185 size = max_intx; 186 } 187 if (size > (size_t)base) { 188 // 4812466: Make sure size doesn't allow the stack to wrap the address space. 189 size = (size_t)base; 190 } 191 return size; 192 } 193 194 static inline stack_t get_stack_info() { 195 stack_t st; 196 int retval = thr_stksegment(&st); 197 st.ss_size = adjust_stack_size((address)st.ss_sp, st.ss_size); 198 assert(retval == 0, "incorrect return value from thr_stksegment"); 199 assert((address)&st < (address)st.ss_sp, "Invalid stack base returned"); 200 assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned"); 201 return st; 202 } 203 204 static void _handle_uncaught_cxx_exception() { 205 VMError::report_and_die("An uncaught C++ exception"); 206 } 207 208 bool os::is_primordial_thread(void) { 209 int r = thr_main(); 210 guarantee(r == 0 || r == 1, "CR6501650 or CR6493689"); 211 return r == 1; 212 } 213 214 address os::current_stack_base() { 215 bool _is_primordial_thread = is_primordial_thread(); 216 217 // Workaround 4352906, avoid calls to thr_stksegment by 218 // thr_main after the first one (it looks like we trash 219 // some data, causing the value for ss_sp to be incorrect). 220 if (!_is_primordial_thread || os::Solaris::_main_stack_base == NULL) { 221 stack_t st = get_stack_info(); 222 if (_is_primordial_thread) { 223 // cache initial value of stack base 224 os::Solaris::_main_stack_base = (address)st.ss_sp; 225 } 226 return (address)st.ss_sp; 227 } else { 228 guarantee(os::Solaris::_main_stack_base != NULL, "Attempt to use null cached stack base"); 229 return os::Solaris::_main_stack_base; 230 } 231 } 232 233 size_t os::current_stack_size() { 234 size_t size; 235 236 if (!is_primordial_thread()) { 237 size = get_stack_info().ss_size; 238 } else { 239 struct rlimit limits; 240 getrlimit(RLIMIT_STACK, &limits); 241 size = adjust_stack_size(os::Solaris::_main_stack_base, (size_t)limits.rlim_cur); 242 } 243 // base may not be page aligned 244 address base = current_stack_base(); 245 address bottom = align_up(base - size, os::vm_page_size());; 246 return (size_t)(base - bottom); 247 } 248 249 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 250 return localtime_r(clock, res); 251 } 252 253 void os::Solaris::try_enable_extended_io() { 254 typedef int (*enable_extended_FILE_stdio_t)(int, int); 255 256 if (!UseExtendedFileIO) { 257 return; 258 } 259 260 enable_extended_FILE_stdio_t enabler = 261 (enable_extended_FILE_stdio_t) dlsym(RTLD_DEFAULT, 262 "enable_extended_FILE_stdio"); 263 if (enabler) { 264 enabler(-1, -1); 265 } 266 } 267 268 static int _processors_online = 0; 269 270 jint os::Solaris::_os_thread_limit = 0; 271 volatile jint os::Solaris::_os_thread_count = 0; 272 273 julong os::available_memory() { 274 return Solaris::available_memory(); 275 } 276 277 julong os::Solaris::available_memory() { 278 return (julong)sysconf(_SC_AVPHYS_PAGES) * os::vm_page_size(); 279 } 280 281 julong os::Solaris::_physical_memory = 0; 282 283 julong os::physical_memory() { 284 return Solaris::physical_memory(); 285 } 286 287 static hrtime_t first_hrtime = 0; 288 static const hrtime_t hrtime_hz = 1000*1000*1000; 289 static volatile hrtime_t max_hrtime = 0; 290 291 292 void os::Solaris::initialize_system_info() { 293 set_processor_count(sysconf(_SC_NPROCESSORS_CONF)); 294 _processors_online = sysconf(_SC_NPROCESSORS_ONLN); 295 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * 296 (julong)sysconf(_SC_PAGESIZE); 297 } 298 299 uint os::processor_id() { 300 const processorid_t id = ::getcpuid(); 301 assert(id >= 0 && id < _processor_count, "Invalid processor id"); 302 return (uint)id; 303 } 304 305 int os::active_processor_count() { 306 // User has overridden the number of active processors 307 if (ActiveProcessorCount > 0) { 308 log_trace(os)("active_processor_count: " 309 "active processor count set by user : %d", 310 ActiveProcessorCount); 311 return ActiveProcessorCount; 312 } 313 314 int online_cpus = sysconf(_SC_NPROCESSORS_ONLN); 315 pid_t pid = getpid(); 316 psetid_t pset = PS_NONE; 317 // Are we running in a processor set or is there any processor set around? 318 if (pset_bind(PS_QUERY, P_PID, pid, &pset) == 0) { 319 uint_t pset_cpus; 320 // Query the number of cpus available to us. 321 if (pset_info(pset, NULL, &pset_cpus, NULL) == 0) { 322 assert(pset_cpus > 0 && pset_cpus <= online_cpus, "sanity check"); 323 _processors_online = pset_cpus; 324 return pset_cpus; 325 } 326 } 327 // Otherwise return number of online cpus 328 return online_cpus; 329 } 330 331 static bool find_processors_in_pset(psetid_t pset, 332 processorid_t** id_array, 333 uint_t* id_length) { 334 bool result = false; 335 // Find the number of processors in the processor set. 336 if (pset_info(pset, NULL, id_length, NULL) == 0) { 337 // Make up an array to hold their ids. 338 *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal); 339 // Fill in the array with their processor ids. 340 if (pset_info(pset, NULL, id_length, *id_array) == 0) { 341 result = true; 342 } 343 } 344 return result; 345 } 346 347 // Callers of find_processors_online() must tolerate imprecise results -- 348 // the system configuration can change asynchronously because of DR 349 // or explicit psradm operations. 350 // 351 // We also need to take care that the loop (below) terminates as the 352 // number of processors online can change between the _SC_NPROCESSORS_ONLN 353 // request and the loop that builds the list of processor ids. Unfortunately 354 // there's no reliable way to determine the maximum valid processor id, 355 // so we use a manifest constant, MAX_PROCESSOR_ID, instead. See p_online 356 // man pages, which claim the processor id set is "sparse, but 357 // not too sparse". MAX_PROCESSOR_ID is used to ensure that we eventually 358 // exit the loop. 359 // 360 // In the future we'll be able to use sysconf(_SC_CPUID_MAX), but that's 361 // not available on S8.0. 362 363 static bool find_processors_online(processorid_t** id_array, 364 uint* id_length) { 365 const processorid_t MAX_PROCESSOR_ID = 100000; 366 // Find the number of processors online. 367 *id_length = sysconf(_SC_NPROCESSORS_ONLN); 368 // Make up an array to hold their ids. 369 *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal); 370 // Processors need not be numbered consecutively. 371 long found = 0; 372 processorid_t next = 0; 373 while (found < *id_length && next < MAX_PROCESSOR_ID) { 374 processor_info_t info; 375 if (processor_info(next, &info) == 0) { 376 // NB, PI_NOINTR processors are effectively online ... 377 if (info.pi_state == P_ONLINE || info.pi_state == P_NOINTR) { 378 (*id_array)[found] = next; 379 found += 1; 380 } 381 } 382 next += 1; 383 } 384 if (found < *id_length) { 385 // The loop above didn't identify the expected number of processors. 386 // We could always retry the operation, calling sysconf(_SC_NPROCESSORS_ONLN) 387 // and re-running the loop, above, but there's no guarantee of progress 388 // if the system configuration is in flux. Instead, we just return what 389 // we've got. Note that in the worst case find_processors_online() could 390 // return an empty set. (As a fall-back in the case of the empty set we 391 // could just return the ID of the current processor). 392 *id_length = found; 393 } 394 395 return true; 396 } 397 398 static bool assign_distribution(processorid_t* id_array, 399 uint id_length, 400 uint* distribution, 401 uint distribution_length) { 402 // We assume we can assign processorid_t's to uint's. 403 assert(sizeof(processorid_t) == sizeof(uint), 404 "can't convert processorid_t to uint"); 405 // Quick check to see if we won't succeed. 406 if (id_length < distribution_length) { 407 return false; 408 } 409 // Assign processor ids to the distribution. 410 // Try to shuffle processors to distribute work across boards, 411 // assuming 4 processors per board. 412 const uint processors_per_board = ProcessDistributionStride; 413 // Find the maximum processor id. 414 processorid_t max_id = 0; 415 for (uint m = 0; m < id_length; m += 1) { 416 max_id = MAX2(max_id, id_array[m]); 417 } 418 // The next id, to limit loops. 419 const processorid_t limit_id = max_id + 1; 420 // Make up markers for available processors. 421 bool* available_id = NEW_C_HEAP_ARRAY(bool, limit_id, mtInternal); 422 for (uint c = 0; c < limit_id; c += 1) { 423 available_id[c] = false; 424 } 425 for (uint a = 0; a < id_length; a += 1) { 426 available_id[id_array[a]] = true; 427 } 428 // Step by "boards", then by "slot", copying to "assigned". 429 // NEEDS_CLEANUP: The assignment of processors should be stateful, 430 // remembering which processors have been assigned by 431 // previous calls, etc., so as to distribute several 432 // independent calls of this method. What we'd like is 433 // It would be nice to have an API that let us ask 434 // how many processes are bound to a processor, 435 // but we don't have that, either. 436 // In the short term, "board" is static so that 437 // subsequent distributions don't all start at board 0. 438 static uint board = 0; 439 uint assigned = 0; 440 // Until we've found enough processors .... 441 while (assigned < distribution_length) { 442 // ... find the next available processor in the board. 443 for (uint slot = 0; slot < processors_per_board; slot += 1) { 444 uint try_id = board * processors_per_board + slot; 445 if ((try_id < limit_id) && (available_id[try_id] == true)) { 446 distribution[assigned] = try_id; 447 available_id[try_id] = false; 448 assigned += 1; 449 break; 450 } 451 } 452 board += 1; 453 if (board * processors_per_board + 0 >= limit_id) { 454 board = 0; 455 } 456 } 457 FREE_C_HEAP_ARRAY(bool, available_id); 458 return true; 459 } 460 461 void os::set_native_thread_name(const char *name) { 462 if (Solaris::_pthread_setname_np != NULL) { 463 // Only the first 31 bytes of 'name' are processed by pthread_setname_np 464 // but we explicitly copy into a size-limited buffer to avoid any 465 // possible overflow. 466 char buf[32]; 467 snprintf(buf, sizeof(buf), "%s", name); 468 buf[sizeof(buf) - 1] = '\0'; 469 Solaris::_pthread_setname_np(pthread_self(), buf); 470 } 471 } 472 473 bool os::distribute_processes(uint length, uint* distribution) { 474 bool result = false; 475 // Find the processor id's of all the available CPUs. 476 processorid_t* id_array = NULL; 477 uint id_length = 0; 478 // There are some races between querying information and using it, 479 // since processor sets can change dynamically. 480 psetid_t pset = PS_NONE; 481 // Are we running in a processor set? 482 if ((pset_bind(PS_QUERY, P_PID, P_MYID, &pset) == 0) && pset != PS_NONE) { 483 result = find_processors_in_pset(pset, &id_array, &id_length); 484 } else { 485 result = find_processors_online(&id_array, &id_length); 486 } 487 if (result == true) { 488 if (id_length >= length) { 489 result = assign_distribution(id_array, id_length, distribution, length); 490 } else { 491 result = false; 492 } 493 } 494 FREE_C_HEAP_ARRAY(processorid_t, id_array); 495 return result; 496 } 497 498 bool os::bind_to_processor(uint processor_id) { 499 // We assume that a processorid_t can be stored in a uint. 500 assert(sizeof(uint) == sizeof(processorid_t), 501 "can't convert uint to processorid_t"); 502 int bind_result = 503 processor_bind(P_LWPID, // bind LWP. 504 P_MYID, // bind current LWP. 505 (processorid_t) processor_id, // id. 506 NULL); // don't return old binding. 507 return (bind_result == 0); 508 } 509 510 // Return true if user is running as root. 511 512 bool os::have_special_privileges() { 513 static bool init = false; 514 static bool privileges = false; 515 if (!init) { 516 privileges = (getuid() != geteuid()) || (getgid() != getegid()); 517 init = true; 518 } 519 return privileges; 520 } 521 522 523 void os::init_system_properties_values() { 524 // The next steps are taken in the product version: 525 // 526 // Obtain the JAVA_HOME value from the location of libjvm.so. 527 // This library should be located at: 528 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so. 529 // 530 // If "/jre/lib/" appears at the right place in the path, then we 531 // assume libjvm.so is installed in a JDK and we use this path. 532 // 533 // Otherwise exit with message: "Could not create the Java virtual machine." 534 // 535 // The following extra steps are taken in the debugging version: 536 // 537 // If "/jre/lib/" does NOT appear at the right place in the path 538 // instead of exit check for $JAVA_HOME environment variable. 539 // 540 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, 541 // then we append a fake suffix "hotspot/libjvm.so" to this path so 542 // it looks like libjvm.so is installed there 543 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so. 544 // 545 // Otherwise exit. 546 // 547 // Important note: if the location of libjvm.so changes this 548 // code needs to be changed accordingly. 549 550 // Base path of extensions installed on the system. 551 #define SYS_EXT_DIR "/usr/jdk/packages" 552 #define EXTENSIONS_DIR "/lib/ext" 553 554 // Buffer that fits several sprintfs. 555 // Note that the space for the colon and the trailing null are provided 556 // by the nulls included by the sizeof operator. 557 const size_t bufsize = 558 MAX3((size_t)MAXPATHLEN, // For dll_dir & friends. 559 sizeof(SYS_EXT_DIR) + sizeof("/lib/"), // invariant ld_library_path 560 (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir 561 char *buf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 562 563 // sysclasspath, java_home, dll_dir 564 { 565 char *pslash; 566 os::jvm_path(buf, bufsize); 567 568 // Found the full path to libjvm.so. 569 // Now cut the path to <java_home>/jre if we can. 570 *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so. 571 pslash = strrchr(buf, '/'); 572 if (pslash != NULL) { 573 *pslash = '\0'; // Get rid of /{client|server|hotspot}. 574 } 575 Arguments::set_dll_dir(buf); 576 577 if (pslash != NULL) { 578 pslash = strrchr(buf, '/'); 579 if (pslash != NULL) { 580 *pslash = '\0'; // Get rid of /lib. 581 } 582 } 583 Arguments::set_java_home(buf); 584 if (!set_boot_path('/', ':')) { 585 vm_exit_during_initialization("Failed setting boot class path.", NULL); 586 } 587 } 588 589 // Where to look for native libraries. 590 { 591 // Use dlinfo() to determine the correct java.library.path. 592 // 593 // If we're launched by the Java launcher, and the user 594 // does not set java.library.path explicitly on the commandline, 595 // the Java launcher sets LD_LIBRARY_PATH for us and unsets 596 // LD_LIBRARY_PATH_32 and LD_LIBRARY_PATH_64. In this case 597 // dlinfo returns LD_LIBRARY_PATH + crle settings (including 598 // /usr/lib), which is exactly what we want. 599 // 600 // If the user does set java.library.path, it completely 601 // overwrites this setting, and always has. 602 // 603 // If we're not launched by the Java launcher, we may 604 // get here with any/all of the LD_LIBRARY_PATH[_32|64] 605 // settings. Again, dlinfo does exactly what we want. 606 607 Dl_serinfo info_sz, *info = &info_sz; 608 Dl_serpath *path; 609 char *library_path; 610 char *common_path = buf; 611 612 // Determine search path count and required buffer size. 613 if (dlinfo(RTLD_SELF, RTLD_DI_SERINFOSIZE, (void *)info) == -1) { 614 FREE_C_HEAP_ARRAY(char, buf); 615 vm_exit_during_initialization("dlinfo SERINFOSIZE request", dlerror()); 616 } 617 618 // Allocate new buffer and initialize. 619 info = (Dl_serinfo*)NEW_C_HEAP_ARRAY(char, info_sz.dls_size, mtInternal); 620 info->dls_size = info_sz.dls_size; 621 info->dls_cnt = info_sz.dls_cnt; 622 623 // Obtain search path information. 624 if (dlinfo(RTLD_SELF, RTLD_DI_SERINFO, (void *)info) == -1) { 625 FREE_C_HEAP_ARRAY(char, buf); 626 FREE_C_HEAP_ARRAY(char, info); 627 vm_exit_during_initialization("dlinfo SERINFO request", dlerror()); 628 } 629 630 path = &info->dls_serpath[0]; 631 632 // Note: Due to a legacy implementation, most of the library path 633 // is set in the launcher. This was to accomodate linking restrictions 634 // on legacy Solaris implementations (which are no longer supported). 635 // Eventually, all the library path setting will be done here. 636 // 637 // However, to prevent the proliferation of improperly built native 638 // libraries, the new path component /usr/jdk/packages is added here. 639 640 // Construct the invariant part of ld_library_path. 641 sprintf(common_path, SYS_EXT_DIR "/lib"); 642 643 // Struct size is more than sufficient for the path components obtained 644 // through the dlinfo() call, so only add additional space for the path 645 // components explicitly added here. 646 size_t library_path_size = info->dls_size + strlen(common_path); 647 library_path = NEW_C_HEAP_ARRAY(char, library_path_size, mtInternal); 648 library_path[0] = '\0'; 649 650 // Construct the desired Java library path from the linker's library 651 // search path. 652 // 653 // For compatibility, it is optimal that we insert the additional path 654 // components specific to the Java VM after those components specified 655 // in LD_LIBRARY_PATH (if any) but before those added by the ld.so 656 // infrastructure. 657 if (info->dls_cnt == 0) { // Not sure this can happen, but allow for it. 658 strcpy(library_path, common_path); 659 } else { 660 int inserted = 0; 661 int i; 662 for (i = 0; i < info->dls_cnt; i++, path++) { 663 uint_t flags = path->dls_flags & LA_SER_MASK; 664 if (((flags & LA_SER_LIBPATH) == 0) && !inserted) { 665 strcat(library_path, common_path); 666 strcat(library_path, os::path_separator()); 667 inserted = 1; 668 } 669 strcat(library_path, path->dls_name); 670 strcat(library_path, os::path_separator()); 671 } 672 // Eliminate trailing path separator. 673 library_path[strlen(library_path)-1] = '\0'; 674 } 675 676 // happens before argument parsing - can't use a trace flag 677 // tty->print_raw("init_system_properties_values: native lib path: "); 678 // tty->print_raw_cr(library_path); 679 680 // Callee copies into its own buffer. 681 Arguments::set_library_path(library_path); 682 683 FREE_C_HEAP_ARRAY(char, library_path); 684 FREE_C_HEAP_ARRAY(char, info); 685 } 686 687 // Extensions directories. 688 sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home()); 689 Arguments::set_ext_dirs(buf); 690 691 FREE_C_HEAP_ARRAY(char, buf); 692 693 #undef SYS_EXT_DIR 694 #undef EXTENSIONS_DIR 695 } 696 697 void os::breakpoint() { 698 BREAKPOINT; 699 } 700 701 bool os::Solaris::valid_stack_address(Thread* thread, address sp) { 702 address stackStart = (address)thread->stack_base(); 703 address stackEnd = (address)(stackStart - (address)thread->stack_size()); 704 if (sp < stackStart && sp >= stackEnd) return true; 705 return false; 706 } 707 708 extern "C" void breakpoint() { 709 // use debugger to set breakpoint here 710 } 711 712 static thread_t main_thread; 713 714 // Thread start routine for all newly created threads 715 extern "C" void* thread_native_entry(void* thread_addr) { 716 717 Thread* thread = (Thread*)thread_addr; 718 719 thread->record_stack_base_and_size(); 720 721 // Try to randomize the cache line index of hot stack frames. 722 // This helps when threads of the same stack traces evict each other's 723 // cache lines. The threads can be either from the same JVM instance, or 724 // from different JVM instances. The benefit is especially true for 725 // processors with hyperthreading technology. 726 static int counter = 0; 727 int pid = os::current_process_id(); 728 alloca(((pid ^ counter++) & 7) * 128); 729 730 int prio; 731 732 thread->initialize_thread_current(); 733 734 OSThread* osthr = thread->osthread(); 735 736 osthr->set_lwp_id(_lwp_self()); // Store lwp in case we are bound 737 738 log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ").", 739 os::current_thread_id()); 740 741 if (UseNUMA) { 742 int lgrp_id = os::numa_get_group_id(); 743 if (lgrp_id != -1) { 744 thread->set_lgrp_id(lgrp_id); 745 } 746 } 747 748 // Our priority was set when we were created, and stored in the 749 // osthread, but couldn't be passed through to our LWP until now. 750 // So read back the priority and set it again. 751 752 if (osthr->thread_id() != -1) { 753 if (UseThreadPriorities) { 754 int prio = osthr->native_priority(); 755 if (ThreadPriorityVerbose) { 756 tty->print_cr("Starting Thread " INTPTR_FORMAT ", LWP is " 757 INTPTR_FORMAT ", setting priority: %d\n", 758 osthr->thread_id(), osthr->lwp_id(), prio); 759 } 760 os::set_native_priority(thread, prio); 761 } 762 } else if (ThreadPriorityVerbose) { 763 warning("Can't set priority in _start routine, thread id hasn't been set\n"); 764 } 765 766 assert(osthr->get_state() == RUNNABLE, "invalid os thread state"); 767 768 // initialize signal mask for this thread 769 os::Solaris::hotspot_sigmask(thread); 770 771 os::Solaris::init_thread_fpu_state(); 772 std::set_terminate(_handle_uncaught_cxx_exception); 773 774 thread->call_run(); 775 776 // Note: at this point the thread object may already have deleted itself. 777 // Do not dereference it from here on out. 778 779 // One less thread is executing 780 // When the VMThread gets here, the main thread may have already exited 781 // which frees the CodeHeap containing the Atomic::dec code 782 if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) { 783 Atomic::dec(&os::Solaris::_os_thread_count); 784 } 785 786 log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ").", os::current_thread_id()); 787 788 if (UseDetachedThreads) { 789 thr_exit(NULL); 790 ShouldNotReachHere(); 791 } 792 return NULL; 793 } 794 795 static OSThread* create_os_thread(Thread* thread, thread_t thread_id) { 796 // Allocate the OSThread object 797 OSThread* osthread = new OSThread(NULL, NULL); 798 if (osthread == NULL) return NULL; 799 800 // Store info on the Solaris thread into the OSThread 801 osthread->set_thread_id(thread_id); 802 osthread->set_lwp_id(_lwp_self()); 803 804 if (UseNUMA) { 805 int lgrp_id = os::numa_get_group_id(); 806 if (lgrp_id != -1) { 807 thread->set_lgrp_id(lgrp_id); 808 } 809 } 810 811 if (ThreadPriorityVerbose) { 812 tty->print_cr("In create_os_thread, Thread " INTPTR_FORMAT ", LWP is " INTPTR_FORMAT "\n", 813 osthread->thread_id(), osthread->lwp_id()); 814 } 815 816 // Initial thread state is INITIALIZED, not SUSPENDED 817 osthread->set_state(INITIALIZED); 818 819 return osthread; 820 } 821 822 void os::Solaris::hotspot_sigmask(Thread* thread) { 823 //Save caller's signal mask 824 sigset_t sigmask; 825 pthread_sigmask(SIG_SETMASK, NULL, &sigmask); 826 OSThread *osthread = thread->osthread(); 827 osthread->set_caller_sigmask(sigmask); 828 829 pthread_sigmask(SIG_UNBLOCK, os::Solaris::unblocked_signals(), NULL); 830 if (!ReduceSignalUsage) { 831 if (thread->is_VM_thread()) { 832 // Only the VM thread handles BREAK_SIGNAL ... 833 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); 834 } else { 835 // ... all other threads block BREAK_SIGNAL 836 assert(!sigismember(vm_signals(), SIGINT), "SIGINT should not be blocked"); 837 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); 838 } 839 } 840 } 841 842 bool os::create_attached_thread(JavaThread* thread) { 843 #ifdef ASSERT 844 thread->verify_not_published(); 845 #endif 846 OSThread* osthread = create_os_thread(thread, thr_self()); 847 if (osthread == NULL) { 848 return false; 849 } 850 851 // Initial thread state is RUNNABLE 852 osthread->set_state(RUNNABLE); 853 thread->set_osthread(osthread); 854 855 // initialize signal mask for this thread 856 // and save the caller's signal mask 857 os::Solaris::hotspot_sigmask(thread); 858 859 log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ").", 860 os::current_thread_id()); 861 862 return true; 863 } 864 865 bool os::create_main_thread(JavaThread* thread) { 866 #ifdef ASSERT 867 thread->verify_not_published(); 868 #endif 869 if (_starting_thread == NULL) { 870 _starting_thread = create_os_thread(thread, main_thread); 871 if (_starting_thread == NULL) { 872 return false; 873 } 874 } 875 876 // The primodial thread is runnable from the start 877 _starting_thread->set_state(RUNNABLE); 878 879 thread->set_osthread(_starting_thread); 880 881 // initialize signal mask for this thread 882 // and save the caller's signal mask 883 os::Solaris::hotspot_sigmask(thread); 884 885 return true; 886 } 887 888 // Helper function to trace thread attributes, similar to os::Posix::describe_pthread_attr() 889 static char* describe_thr_create_attributes(char* buf, size_t buflen, 890 size_t stacksize, long flags) { 891 stringStream ss(buf, buflen); 892 ss.print("stacksize: " SIZE_FORMAT "k, ", stacksize / 1024); 893 ss.print("flags: "); 894 #define PRINT_FLAG(f) if (flags & f) ss.print( #f " "); 895 #define ALL(X) \ 896 X(THR_SUSPENDED) \ 897 X(THR_DETACHED) \ 898 X(THR_BOUND) \ 899 X(THR_NEW_LWP) \ 900 X(THR_DAEMON) 901 ALL(PRINT_FLAG) 902 #undef ALL 903 #undef PRINT_FLAG 904 return buf; 905 } 906 907 // return default stack size for thr_type 908 size_t os::Posix::default_stack_size(os::ThreadType thr_type) { 909 // default stack size when not specified by caller is 1M (2M for LP64) 910 size_t s = (BytesPerWord >> 2) * K * K; 911 return s; 912 } 913 914 bool os::create_thread(Thread* thread, ThreadType thr_type, 915 size_t req_stack_size) { 916 // Allocate the OSThread object 917 OSThread* osthread = new OSThread(NULL, NULL); 918 if (osthread == NULL) { 919 return false; 920 } 921 922 if (ThreadPriorityVerbose) { 923 char *thrtyp; 924 switch (thr_type) { 925 case vm_thread: 926 thrtyp = (char *)"vm"; 927 break; 928 case cgc_thread: 929 thrtyp = (char *)"cgc"; 930 break; 931 case pgc_thread: 932 thrtyp = (char *)"pgc"; 933 break; 934 case java_thread: 935 thrtyp = (char *)"java"; 936 break; 937 case compiler_thread: 938 thrtyp = (char *)"compiler"; 939 break; 940 case watcher_thread: 941 thrtyp = (char *)"watcher"; 942 break; 943 default: 944 thrtyp = (char *)"unknown"; 945 break; 946 } 947 tty->print_cr("In create_thread, creating a %s thread\n", thrtyp); 948 } 949 950 // calculate stack size if it's not specified by caller 951 size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size); 952 953 // Initial state is ALLOCATED but not INITIALIZED 954 osthread->set_state(ALLOCATED); 955 956 if (os::Solaris::_os_thread_count > os::Solaris::_os_thread_limit) { 957 // We got lots of threads. Check if we still have some address space left. 958 // Need to be at least 5Mb of unreserved address space. We do check by 959 // trying to reserve some. 960 const size_t VirtualMemoryBangSize = 20*K*K; 961 char* mem = os::reserve_memory(VirtualMemoryBangSize); 962 if (mem == NULL) { 963 delete osthread; 964 return false; 965 } else { 966 // Release the memory again 967 os::release_memory(mem, VirtualMemoryBangSize); 968 } 969 } 970 971 // Setup osthread because the child thread may need it. 972 thread->set_osthread(osthread); 973 974 // Create the Solaris thread 975 thread_t tid = 0; 976 long flags = (UseDetachedThreads ? THR_DETACHED : 0) | THR_SUSPENDED; 977 int status; 978 979 // Mark that we don't have an lwp or thread id yet. 980 // In case we attempt to set the priority before the thread starts. 981 osthread->set_lwp_id(-1); 982 osthread->set_thread_id(-1); 983 984 status = thr_create(NULL, stack_size, thread_native_entry, thread, flags, &tid); 985 986 char buf[64]; 987 if (status == 0) { 988 log_info(os, thread)("Thread started (tid: " UINTX_FORMAT ", attributes: %s). ", 989 (uintx) tid, describe_thr_create_attributes(buf, sizeof(buf), stack_size, flags)); 990 } else { 991 log_warning(os, thread)("Failed to start thread - thr_create failed (%s) for attributes: %s.", 992 os::errno_name(status), describe_thr_create_attributes(buf, sizeof(buf), stack_size, flags)); 993 // Log some OS information which might explain why creating the thread failed. 994 log_info(os, thread)("Number of threads approx. running in the VM: %d", Threads::number_of_threads()); 995 LogStream st(Log(os, thread)::info()); 996 os::Posix::print_rlimit_info(&st); 997 os::print_memory_info(&st); 998 } 999 1000 if (status != 0) { 1001 thread->set_osthread(NULL); 1002 // Need to clean up stuff we've allocated so far 1003 delete osthread; 1004 return false; 1005 } 1006 1007 Atomic::inc(&os::Solaris::_os_thread_count); 1008 1009 // Store info on the Solaris thread into the OSThread 1010 osthread->set_thread_id(tid); 1011 1012 // Remember that we created this thread so we can set priority on it 1013 osthread->set_vm_created(); 1014 1015 // Most thread types will set an explicit priority before starting the thread, 1016 // but for those that don't we need a valid value to read back in thread_native_entry. 1017 osthread->set_native_priority(NormPriority); 1018 1019 // Initial thread state is INITIALIZED, not SUSPENDED 1020 osthread->set_state(INITIALIZED); 1021 1022 // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain 1023 return true; 1024 } 1025 1026 debug_only(static bool signal_sets_initialized = false); 1027 static sigset_t unblocked_sigs, vm_sigs; 1028 1029 void os::Solaris::signal_sets_init() { 1030 // Should also have an assertion stating we are still single-threaded. 1031 assert(!signal_sets_initialized, "Already initialized"); 1032 // Fill in signals that are necessarily unblocked for all threads in 1033 // the VM. Currently, we unblock the following signals: 1034 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden 1035 // by -Xrs (=ReduceSignalUsage)); 1036 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all 1037 // other threads. The "ReduceSignalUsage" boolean tells us not to alter 1038 // the dispositions or masks wrt these signals. 1039 // Programs embedding the VM that want to use the above signals for their 1040 // own purposes must, at this time, use the "-Xrs" option to prevent 1041 // interference with shutdown hooks and BREAK_SIGNAL thread dumping. 1042 // (See bug 4345157, and other related bugs). 1043 // In reality, though, unblocking these signals is really a nop, since 1044 // these signals are not blocked by default. 1045 sigemptyset(&unblocked_sigs); 1046 sigaddset(&unblocked_sigs, SIGILL); 1047 sigaddset(&unblocked_sigs, SIGSEGV); 1048 sigaddset(&unblocked_sigs, SIGBUS); 1049 sigaddset(&unblocked_sigs, SIGFPE); 1050 sigaddset(&unblocked_sigs, ASYNC_SIGNAL); 1051 1052 if (!ReduceSignalUsage) { 1053 if (!os::Posix::is_sig_ignored(SHUTDOWN1_SIGNAL)) { 1054 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); 1055 } 1056 if (!os::Posix::is_sig_ignored(SHUTDOWN2_SIGNAL)) { 1057 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); 1058 } 1059 if (!os::Posix::is_sig_ignored(SHUTDOWN3_SIGNAL)) { 1060 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); 1061 } 1062 } 1063 // Fill in signals that are blocked by all but the VM thread. 1064 sigemptyset(&vm_sigs); 1065 if (!ReduceSignalUsage) { 1066 sigaddset(&vm_sigs, BREAK_SIGNAL); 1067 } 1068 debug_only(signal_sets_initialized = true); 1069 1070 // For diagnostics only used in run_periodic_checks 1071 sigemptyset(&check_signal_done); 1072 } 1073 1074 // These are signals that are unblocked while a thread is running Java. 1075 // (For some reason, they get blocked by default.) 1076 sigset_t* os::Solaris::unblocked_signals() { 1077 assert(signal_sets_initialized, "Not initialized"); 1078 return &unblocked_sigs; 1079 } 1080 1081 // These are the signals that are blocked while a (non-VM) thread is 1082 // running Java. Only the VM thread handles these signals. 1083 sigset_t* os::Solaris::vm_signals() { 1084 assert(signal_sets_initialized, "Not initialized"); 1085 return &vm_sigs; 1086 } 1087 1088 // CR 7190089: on Solaris, primordial thread's stack needs adjusting. 1089 // Without the adjustment, stack size is incorrect if stack is set to unlimited (ulimit -s unlimited). 1090 void os::Solaris::correct_stack_boundaries_for_primordial_thread(Thread* thr) { 1091 assert(is_primordial_thread(), "Call only for primordial thread"); 1092 1093 JavaThread* jt = (JavaThread *)thr; 1094 assert(jt != NULL, "Sanity check"); 1095 size_t stack_size; 1096 address base = jt->stack_base(); 1097 if (Arguments::created_by_java_launcher()) { 1098 // Use 2MB to allow for Solaris 7 64 bit mode. 1099 stack_size = JavaThread::stack_size_at_create() == 0 1100 ? 2048*K : JavaThread::stack_size_at_create(); 1101 1102 // There are rare cases when we may have already used more than 1103 // the basic stack size allotment before this method is invoked. 1104 // Attempt to allow for a normally sized java_stack. 1105 size_t current_stack_offset = (size_t)(base - (address)&stack_size); 1106 stack_size += ReservedSpace::page_align_size_down(current_stack_offset); 1107 } else { 1108 // 6269555: If we were not created by a Java launcher, i.e. if we are 1109 // running embedded in a native application, treat the primordial thread 1110 // as much like a native attached thread as possible. This means using 1111 // the current stack size from thr_stksegment(), unless it is too large 1112 // to reliably setup guard pages. A reasonable max size is 8MB. 1113 size_t current_size = os::current_stack_size(); 1114 // This should never happen, but just in case.... 1115 if (current_size == 0) current_size = 2 * K * K; 1116 stack_size = current_size > (8 * K * K) ? (8 * K * K) : current_size; 1117 } 1118 address bottom = align_up(base - stack_size, os::vm_page_size());; 1119 stack_size = (size_t)(base - bottom); 1120 1121 assert(stack_size > 0, "Stack size calculation problem"); 1122 1123 if (stack_size > jt->stack_size()) { 1124 #ifndef PRODUCT 1125 struct rlimit limits; 1126 getrlimit(RLIMIT_STACK, &limits); 1127 size_t size = adjust_stack_size(base, (size_t)limits.rlim_cur); 1128 assert(size >= jt->stack_size(), "Stack size problem in main thread"); 1129 #endif 1130 tty->print_cr("Stack size of %d Kb exceeds current limit of %d Kb.\n" 1131 "(Stack sizes are rounded up to a multiple of the system page size.)\n" 1132 "See limit(1) to increase the stack size limit.", 1133 stack_size / K, jt->stack_size() / K); 1134 vm_exit(1); 1135 } 1136 assert(jt->stack_size() >= stack_size, 1137 "Attempt to map more stack than was allocated"); 1138 jt->set_stack_size(stack_size); 1139 1140 } 1141 1142 1143 1144 // Free Solaris resources related to the OSThread 1145 void os::free_thread(OSThread* osthread) { 1146 assert(osthread != NULL, "os::free_thread but osthread not set"); 1147 1148 // We are told to free resources of the argument thread, 1149 // but we can only really operate on the current thread. 1150 assert(Thread::current()->osthread() == osthread, 1151 "os::free_thread but not current thread"); 1152 1153 // Restore caller's signal mask 1154 sigset_t sigmask = osthread->caller_sigmask(); 1155 pthread_sigmask(SIG_SETMASK, &sigmask, NULL); 1156 1157 delete osthread; 1158 } 1159 1160 void os::pd_start_thread(Thread* thread) { 1161 int status = thr_continue(thread->osthread()->thread_id()); 1162 assert_status(status == 0, status, "thr_continue failed"); 1163 } 1164 1165 1166 intx os::current_thread_id() { 1167 return (intx)thr_self(); 1168 } 1169 1170 static pid_t _initial_pid = 0; 1171 1172 int os::current_process_id() { 1173 return (int)(_initial_pid ? _initial_pid : getpid()); 1174 } 1175 1176 // gethrtime() should be monotonic according to the documentation, 1177 // but some virtualized platforms are known to break this guarantee. 1178 // getTimeNanos() must be guaranteed not to move backwards, so we 1179 // are forced to add a check here. 1180 inline hrtime_t getTimeNanos() { 1181 const hrtime_t now = gethrtime(); 1182 const hrtime_t prev = max_hrtime; 1183 if (now <= prev) { 1184 return prev; // same or retrograde time; 1185 } 1186 const hrtime_t obsv = Atomic::cmpxchg(now, &max_hrtime, prev); 1187 assert(obsv >= prev, "invariant"); // Monotonicity 1188 // If the CAS succeeded then we're done and return "now". 1189 // If the CAS failed and the observed value "obsv" is >= now then 1190 // we should return "obsv". If the CAS failed and now > obsv > prv then 1191 // some other thread raced this thread and installed a new value, in which case 1192 // we could either (a) retry the entire operation, (b) retry trying to install now 1193 // or (c) just return obsv. We use (c). No loop is required although in some cases 1194 // we might discard a higher "now" value in deference to a slightly lower but freshly 1195 // installed obsv value. That's entirely benign -- it admits no new orderings compared 1196 // to (a) or (b) -- and greatly reduces coherence traffic. 1197 // We might also condition (c) on the magnitude of the delta between obsv and now. 1198 // Avoiding excessive CAS operations to hot RW locations is critical. 1199 // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate 1200 return (prev == obsv) ? now : obsv; 1201 } 1202 1203 // Time since start-up in seconds to a fine granularity. 1204 // Used by VMSelfDestructTimer and the MemProfiler. 1205 double os::elapsedTime() { 1206 return (double)(getTimeNanos() - first_hrtime) / (double)hrtime_hz; 1207 } 1208 1209 jlong os::elapsed_counter() { 1210 return (jlong)(getTimeNanos() - first_hrtime); 1211 } 1212 1213 jlong os::elapsed_frequency() { 1214 return hrtime_hz; 1215 } 1216 1217 // Return the real, user, and system times in seconds from an 1218 // arbitrary fixed point in the past. 1219 bool os::getTimesSecs(double* process_real_time, 1220 double* process_user_time, 1221 double* process_system_time) { 1222 struct tms ticks; 1223 clock_t real_ticks = times(&ticks); 1224 1225 if (real_ticks == (clock_t) (-1)) { 1226 return false; 1227 } else { 1228 double ticks_per_second = (double) clock_tics_per_sec; 1229 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; 1230 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; 1231 // For consistency return the real time from getTimeNanos() 1232 // converted to seconds. 1233 *process_real_time = ((double) getTimeNanos()) / ((double) NANOUNITS); 1234 1235 return true; 1236 } 1237 } 1238 1239 bool os::supports_vtime() { return true; } 1240 bool os::enable_vtime() { return false; } 1241 bool os::vtime_enabled() { return false; } 1242 1243 double os::elapsedVTime() { 1244 return (double)gethrvtime() / (double)hrtime_hz; 1245 } 1246 1247 // Must return millis since Jan 1 1970 for JVM_CurrentTimeMillis 1248 jlong os::javaTimeMillis() { 1249 timeval t; 1250 if (gettimeofday(&t, NULL) == -1) { 1251 fatal("os::javaTimeMillis: gettimeofday (%s)", os::strerror(errno)); 1252 } 1253 return jlong(t.tv_sec) * 1000 + jlong(t.tv_usec) / 1000; 1254 } 1255 1256 // Must return seconds+nanos since Jan 1 1970. This must use the same 1257 // time source as javaTimeMillis and can't use get_nsec_fromepoch as 1258 // we need better than 1ms accuracy 1259 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { 1260 timeval t; 1261 if (gettimeofday(&t, NULL) == -1) { 1262 fatal("os::javaTimeSystemUTC: gettimeofday (%s)", os::strerror(errno)); 1263 } 1264 seconds = jlong(t.tv_sec); 1265 nanos = jlong(t.tv_usec) * 1000; 1266 } 1267 1268 1269 jlong os::javaTimeNanos() { 1270 return (jlong)getTimeNanos(); 1271 } 1272 1273 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 1274 info_ptr->max_value = ALL_64_BITS; // gethrtime() uses all 64 bits 1275 info_ptr->may_skip_backward = false; // not subject to resetting or drifting 1276 info_ptr->may_skip_forward = false; // not subject to resetting or drifting 1277 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 1278 } 1279 1280 char * os::local_time_string(char *buf, size_t buflen) { 1281 struct tm t; 1282 time_t long_time; 1283 time(&long_time); 1284 localtime_r(&long_time, &t); 1285 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 1286 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, 1287 t.tm_hour, t.tm_min, t.tm_sec); 1288 return buf; 1289 } 1290 1291 // Note: os::shutdown() might be called very early during initialization, or 1292 // called from signal handler. Before adding something to os::shutdown(), make 1293 // sure it is async-safe and can handle partially initialized VM. 1294 void os::shutdown() { 1295 1296 // allow PerfMemory to attempt cleanup of any persistent resources 1297 perfMemory_exit(); 1298 1299 // needs to remove object in file system 1300 AttachListener::abort(); 1301 1302 // flush buffered output, finish log files 1303 ostream_abort(); 1304 1305 // Check for abort hook 1306 abort_hook_t abort_hook = Arguments::abort_hook(); 1307 if (abort_hook != NULL) { 1308 abort_hook(); 1309 } 1310 } 1311 1312 // Note: os::abort() might be called very early during initialization, or 1313 // called from signal handler. Before adding something to os::abort(), make 1314 // sure it is async-safe and can handle partially initialized VM. 1315 void os::abort(bool dump_core, void* siginfo, const void* context) { 1316 os::shutdown(); 1317 if (dump_core) { 1318 #ifndef PRODUCT 1319 fdStream out(defaultStream::output_fd()); 1320 out.print_raw("Current thread is "); 1321 char buf[16]; 1322 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); 1323 out.print_raw_cr(buf); 1324 out.print_raw_cr("Dumping core ..."); 1325 #endif 1326 ::abort(); // dump core (for debugging) 1327 } 1328 1329 ::exit(1); 1330 } 1331 1332 // Die immediately, no exit hook, no abort hook, no cleanup. 1333 // Dump a core file, if possible, for debugging. 1334 void os::die() { 1335 if (TestUnresponsiveErrorHandler && !CreateCoredumpOnCrash) { 1336 // For TimeoutInErrorHandlingTest.java, we just kill the VM 1337 // and don't take the time to generate a core file. 1338 os::signal_raise(SIGKILL); 1339 } else { 1340 ::abort(); 1341 } 1342 } 1343 1344 // DLL functions 1345 1346 const char* os::dll_file_extension() { return ".so"; } 1347 1348 // This must be hard coded because it's the system's temporary 1349 // directory not the java application's temp directory, ala java.io.tmpdir. 1350 const char* os::get_temp_directory() { return "/tmp"; } 1351 1352 // check if addr is inside libjvm.so 1353 bool os::address_is_in_vm(address addr) { 1354 static address libjvm_base_addr; 1355 Dl_info dlinfo; 1356 1357 if (libjvm_base_addr == NULL) { 1358 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { 1359 libjvm_base_addr = (address)dlinfo.dli_fbase; 1360 } 1361 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); 1362 } 1363 1364 if (dladdr((void *)addr, &dlinfo) != 0) { 1365 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; 1366 } 1367 1368 return false; 1369 } 1370 1371 typedef int (*dladdr1_func_type)(void *, Dl_info *, void **, int); 1372 static dladdr1_func_type dladdr1_func = NULL; 1373 1374 bool os::dll_address_to_function_name(address addr, char *buf, 1375 int buflen, int * offset, 1376 bool demangle) { 1377 // buf is not optional, but offset is optional 1378 assert(buf != NULL, "sanity check"); 1379 1380 Dl_info dlinfo; 1381 1382 // dladdr1_func was initialized in os::init() 1383 if (dladdr1_func != NULL) { 1384 // yes, we have dladdr1 1385 1386 // Support for dladdr1 is checked at runtime; it may be 1387 // available even if the vm is built on a machine that does 1388 // not have dladdr1 support. Make sure there is a value for 1389 // RTLD_DL_SYMENT. 1390 #ifndef RTLD_DL_SYMENT 1391 #define RTLD_DL_SYMENT 1 1392 #endif 1393 #ifdef _LP64 1394 Elf64_Sym * info; 1395 #else 1396 Elf32_Sym * info; 1397 #endif 1398 if (dladdr1_func((void *)addr, &dlinfo, (void **)&info, 1399 RTLD_DL_SYMENT) != 0) { 1400 // see if we have a matching symbol that covers our address 1401 if (dlinfo.dli_saddr != NULL && 1402 (char *)dlinfo.dli_saddr + info->st_size > (char *)addr) { 1403 if (dlinfo.dli_sname != NULL) { 1404 if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) { 1405 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); 1406 } 1407 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1408 return true; 1409 } 1410 } 1411 // no matching symbol so try for just file info 1412 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { 1413 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1414 buf, buflen, offset, dlinfo.dli_fname, demangle)) { 1415 return true; 1416 } 1417 } 1418 } 1419 buf[0] = '\0'; 1420 if (offset != NULL) *offset = -1; 1421 return false; 1422 } 1423 1424 // no, only dladdr is available 1425 if (dladdr((void *)addr, &dlinfo) != 0) { 1426 // see if we have a matching symbol 1427 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { 1428 if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) { 1429 jio_snprintf(buf, buflen, dlinfo.dli_sname); 1430 } 1431 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1432 return true; 1433 } 1434 // no matching symbol so try for just file info 1435 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { 1436 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1437 buf, buflen, offset, dlinfo.dli_fname, demangle)) { 1438 return true; 1439 } 1440 } 1441 } 1442 buf[0] = '\0'; 1443 if (offset != NULL) *offset = -1; 1444 return false; 1445 } 1446 1447 bool os::dll_address_to_library_name(address addr, char* buf, 1448 int buflen, int* offset) { 1449 // buf is not optional, but offset is optional 1450 assert(buf != NULL, "sanity check"); 1451 1452 Dl_info dlinfo; 1453 1454 if (dladdr((void*)addr, &dlinfo) != 0) { 1455 if (dlinfo.dli_fname != NULL) { 1456 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 1457 } 1458 if (dlinfo.dli_fbase != NULL && offset != NULL) { 1459 *offset = addr - (address)dlinfo.dli_fbase; 1460 } 1461 return true; 1462 } 1463 1464 buf[0] = '\0'; 1465 if (offset) *offset = -1; 1466 return false; 1467 } 1468 1469 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) { 1470 Dl_info dli; 1471 // Sanity check? 1472 if (dladdr(CAST_FROM_FN_PTR(void *, os::get_loaded_modules_info), &dli) == 0 || 1473 dli.dli_fname == NULL) { 1474 return 1; 1475 } 1476 1477 void * handle = dlopen(dli.dli_fname, RTLD_LAZY); 1478 if (handle == NULL) { 1479 return 1; 1480 } 1481 1482 Link_map *map; 1483 dlinfo(handle, RTLD_DI_LINKMAP, &map); 1484 if (map == NULL) { 1485 dlclose(handle); 1486 return 1; 1487 } 1488 1489 while (map->l_prev != NULL) { 1490 map = map->l_prev; 1491 } 1492 1493 while (map != NULL) { 1494 // Iterate through all map entries and call callback with fields of interest 1495 if(callback(map->l_name, (address)map->l_addr, (address)0, param)) { 1496 dlclose(handle); 1497 return 1; 1498 } 1499 map = map->l_next; 1500 } 1501 1502 dlclose(handle); 1503 return 0; 1504 } 1505 1506 int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) { 1507 outputStream * out = (outputStream *) param; 1508 out->print_cr(PTR_FORMAT " \t%s", base_address, name); 1509 return 0; 1510 } 1511 1512 void os::print_dll_info(outputStream * st) { 1513 st->print_cr("Dynamic libraries:"); st->flush(); 1514 if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) { 1515 st->print_cr("Error: Cannot print dynamic libraries."); 1516 } 1517 } 1518 1519 static void change_endianness(Elf32_Half& val) { 1520 unsigned char *ptr = (unsigned char *)&val; 1521 unsigned char swp = ptr[0]; 1522 ptr[0] = ptr[1]; 1523 ptr[1] = swp; 1524 } 1525 1526 // Loads .dll/.so and 1527 // in case of error it checks if .dll/.so was built for the 1528 // same architecture as Hotspot is running on 1529 1530 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { 1531 log_info(os)("attempting shared library load of %s", filename); 1532 1533 void * result= ::dlopen(filename, RTLD_LAZY); 1534 if (result != NULL) { 1535 // Successful loading 1536 Events::log(NULL, "Loaded shared library %s", filename); 1537 log_info(os)("shared library load of %s was successful", filename); 1538 return result; 1539 } 1540 1541 Elf32_Ehdr elf_head; 1542 const char* error_report = ::dlerror(); 1543 if (error_report == NULL) { 1544 error_report = "dlerror returned no error description"; 1545 } 1546 if (ebuf != NULL && ebuflen > 0) { 1547 ::strncpy(ebuf, error_report, ebuflen-1); 1548 ebuf[ebuflen-1]='\0'; 1549 } 1550 1551 Events::log(NULL, "Loading shared library %s failed, %s", filename, error_report); 1552 log_info(os)("shared library load of %s failed, %s", filename, error_report); 1553 1554 int diag_msg_max_length=ebuflen-strlen(ebuf); 1555 char* diag_msg_buf=ebuf+strlen(ebuf); 1556 1557 if (diag_msg_max_length==0) { 1558 // No more space in ebuf for additional diagnostics message 1559 return NULL; 1560 } 1561 1562 1563 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); 1564 1565 if (file_descriptor < 0) { 1566 // Can't open library, report dlerror() message 1567 return NULL; 1568 } 1569 1570 bool failed_to_read_elf_head= 1571 (sizeof(elf_head)!= 1572 (::read(file_descriptor, &elf_head,sizeof(elf_head)))); 1573 1574 ::close(file_descriptor); 1575 if (failed_to_read_elf_head) { 1576 // file i/o error - report dlerror() msg 1577 return NULL; 1578 } 1579 1580 if (elf_head.e_ident[EI_DATA] != LITTLE_ENDIAN_ONLY(ELFDATA2LSB) BIG_ENDIAN_ONLY(ELFDATA2MSB)) { 1581 // handle invalid/out of range endianness values 1582 if (elf_head.e_ident[EI_DATA] == 0 || elf_head.e_ident[EI_DATA] > 2) { 1583 return NULL; 1584 } 1585 change_endianness(elf_head.e_machine); 1586 } 1587 1588 typedef struct { 1589 Elf32_Half code; // Actual value as defined in elf.h 1590 Elf32_Half compat_class; // Compatibility of archs at VM's sense 1591 unsigned char elf_class; // 32 or 64 bit 1592 unsigned char endianess; // MSB or LSB 1593 char* name; // String representation 1594 } arch_t; 1595 1596 #ifndef EM_AARCH64 1597 #define EM_AARCH64 183 /* ARM AARCH64 */ 1598 #endif 1599 1600 static const arch_t arch_array[]={ 1601 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1602 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1603 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, 1604 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, 1605 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1606 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1607 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, 1608 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, 1609 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, 1610 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"}, 1611 // we only support 64 bit z architecture 1612 {EM_S390, EM_S390, ELFCLASS64, ELFDATA2MSB, (char*)"IBM System/390"}, 1613 {EM_AARCH64, EM_AARCH64, ELFCLASS64, ELFDATA2LSB, (char*)"AARCH64"} 1614 }; 1615 1616 #if (defined IA32) 1617 static Elf32_Half running_arch_code=EM_386; 1618 #elif (defined AMD64) 1619 static Elf32_Half running_arch_code=EM_X86_64; 1620 #elif (defined IA64) 1621 static Elf32_Half running_arch_code=EM_IA_64; 1622 #elif (defined __sparc) && (defined _LP64) 1623 static Elf32_Half running_arch_code=EM_SPARCV9; 1624 #elif (defined __sparc) && (!defined _LP64) 1625 static Elf32_Half running_arch_code=EM_SPARC; 1626 #elif (defined __powerpc64__) 1627 static Elf32_Half running_arch_code=EM_PPC64; 1628 #elif (defined __powerpc__) 1629 static Elf32_Half running_arch_code=EM_PPC; 1630 #elif (defined ARM) 1631 static Elf32_Half running_arch_code=EM_ARM; 1632 #else 1633 #error Method os::dll_load requires that one of following is defined:\ 1634 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, ARM 1635 #endif 1636 1637 // Identify compatibility class for VM's architecture and library's architecture 1638 // Obtain string descriptions for architectures 1639 1640 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; 1641 int running_arch_index=-1; 1642 1643 for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { 1644 if (running_arch_code == arch_array[i].code) { 1645 running_arch_index = i; 1646 } 1647 if (lib_arch.code == arch_array[i].code) { 1648 lib_arch.compat_class = arch_array[i].compat_class; 1649 lib_arch.name = arch_array[i].name; 1650 } 1651 } 1652 1653 assert(running_arch_index != -1, 1654 "Didn't find running architecture code (running_arch_code) in arch_array"); 1655 if (running_arch_index == -1) { 1656 // Even though running architecture detection failed 1657 // we may still continue with reporting dlerror() message 1658 return NULL; 1659 } 1660 1661 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { 1662 if (lib_arch.name != NULL) { 1663 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1664 " (Possible cause: can't load %s .so on a %s platform)", 1665 lib_arch.name, arch_array[running_arch_index].name); 1666 } else { 1667 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1668 " (Possible cause: can't load this .so (machine code=0x%x) on a %s platform)", 1669 lib_arch.code, arch_array[running_arch_index].name); 1670 } 1671 return NULL; 1672 } 1673 1674 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { 1675 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); 1676 return NULL; 1677 } 1678 1679 // ELF file class/capacity : 0 - invalid, 1 - 32bit, 2 - 64bit 1680 if (lib_arch.elf_class > 2 || lib_arch.elf_class < 1) { 1681 ::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: invalid ELF file class)"); 1682 return NULL; 1683 } 1684 1685 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { 1686 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1687 " (Possible cause: architecture word width mismatch, can't load %d-bit .so on a %d-bit platform)", 1688 (int) lib_arch.elf_class * 32, arch_array[running_arch_index].elf_class * 32); 1689 return NULL; 1690 } 1691 1692 return NULL; 1693 } 1694 1695 void* os::dll_lookup(void* handle, const char* name) { 1696 return dlsym(handle, name); 1697 } 1698 1699 void* os::get_default_process_handle() { 1700 return (void*)::dlopen(NULL, RTLD_LAZY); 1701 } 1702 1703 static inline time_t get_mtime(const char* filename) { 1704 struct stat st; 1705 int ret = os::stat(filename, &st); 1706 assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno)); 1707 return st.st_mtime; 1708 } 1709 1710 int os::compare_file_modified_times(const char* file1, const char* file2) { 1711 time_t t1 = get_mtime(file1); 1712 time_t t2 = get_mtime(file2); 1713 return t1 - t2; 1714 } 1715 1716 static bool _print_ascii_file(const char* filename, outputStream* st) { 1717 int fd = ::open(filename, O_RDONLY); 1718 if (fd == -1) { 1719 return false; 1720 } 1721 1722 char buf[32]; 1723 int bytes; 1724 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) { 1725 st->print_raw(buf, bytes); 1726 } 1727 1728 ::close(fd); 1729 1730 return true; 1731 } 1732 1733 void os::print_os_info_brief(outputStream* st) { 1734 os::Solaris::print_distro_info(st); 1735 1736 os::Posix::print_uname_info(st); 1737 1738 os::Solaris::print_libversion_info(st); 1739 } 1740 1741 void os::print_os_info(outputStream* st) { 1742 st->print("OS:"); 1743 1744 os::Solaris::print_distro_info(st); 1745 1746 os::Posix::print_uname_info(st); 1747 1748 os::Solaris::print_libversion_info(st); 1749 1750 os::Posix::print_rlimit_info(st); 1751 1752 os::Posix::print_load_average(st); 1753 } 1754 1755 void os::Solaris::print_distro_info(outputStream* st) { 1756 if (!_print_ascii_file("/etc/release", st)) { 1757 st->print("Solaris"); 1758 } 1759 st->cr(); 1760 } 1761 1762 void os::get_summary_os_info(char* buf, size_t buflen) { 1763 strncpy(buf, "Solaris", buflen); // default to plain solaris 1764 FILE* fp = fopen("/etc/release", "r"); 1765 if (fp != NULL) { 1766 char tmp[256]; 1767 // Only get the first line and chop out everything but the os name. 1768 if (fgets(tmp, sizeof(tmp), fp)) { 1769 char* ptr = tmp; 1770 // skip past whitespace characters 1771 while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')) ptr++; 1772 if (*ptr != '\0') { 1773 char* nl = strchr(ptr, '\n'); 1774 if (nl != NULL) *nl = '\0'; 1775 strncpy(buf, ptr, buflen); 1776 } 1777 } 1778 fclose(fp); 1779 } 1780 } 1781 1782 void os::Solaris::print_libversion_info(outputStream* st) { 1783 st->print(" (T2 libthread)"); 1784 st->cr(); 1785 } 1786 1787 static bool check_addr0(outputStream* st) { 1788 jboolean status = false; 1789 const int read_chunk = 200; 1790 int ret = 0; 1791 int nmap = 0; 1792 int fd = ::open("/proc/self/map",O_RDONLY); 1793 if (fd >= 0) { 1794 prmap_t *p = NULL; 1795 char *mbuff = (char *) calloc(read_chunk, sizeof(prmap_t)); 1796 if (NULL == mbuff) { 1797 ::close(fd); 1798 return status; 1799 } 1800 while ((ret = ::read(fd, mbuff, read_chunk*sizeof(prmap_t))) > 0) { 1801 //check if read() has not read partial data 1802 if( 0 != ret % sizeof(prmap_t)){ 1803 break; 1804 } 1805 nmap = ret / sizeof(prmap_t); 1806 p = (prmap_t *)mbuff; 1807 for(int i = 0; i < nmap; i++){ 1808 if (p->pr_vaddr == 0x0) { 1809 st->print("Warning: Address: " PTR_FORMAT ", Size: " SIZE_FORMAT "K, ",p->pr_vaddr, p->pr_size/1024); 1810 st->print("Mapped file: %s, ", p->pr_mapname[0] == '\0' ? "None" : p->pr_mapname); 1811 st->print("Access: "); 1812 st->print("%s",(p->pr_mflags & MA_READ) ? "r" : "-"); 1813 st->print("%s",(p->pr_mflags & MA_WRITE) ? "w" : "-"); 1814 st->print("%s",(p->pr_mflags & MA_EXEC) ? "x" : "-"); 1815 st->cr(); 1816 status = true; 1817 } 1818 p++; 1819 } 1820 } 1821 free(mbuff); 1822 ::close(fd); 1823 } 1824 return status; 1825 } 1826 1827 void os::get_summary_cpu_info(char* buf, size_t buflen) { 1828 // Get MHz with system call. We don't seem to already have this. 1829 processor_info_t stats; 1830 processorid_t id = getcpuid(); 1831 int clock = 0; 1832 if (processor_info(id, &stats) != -1) { 1833 clock = stats.pi_clock; // pi_processor_type isn't more informative than below 1834 } 1835 #ifdef AMD64 1836 snprintf(buf, buflen, "x86 64 bit %d MHz", clock); 1837 #else 1838 // must be sparc 1839 snprintf(buf, buflen, "Sparcv9 64 bit %d MHz", clock); 1840 #endif 1841 } 1842 1843 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) { 1844 // Nothing to do for now. 1845 } 1846 1847 void os::print_memory_info(outputStream* st) { 1848 st->print("Memory:"); 1849 st->print(" %dk page", os::vm_page_size()>>10); 1850 st->print(", physical " UINT64_FORMAT "k", os::physical_memory()>>10); 1851 st->print("(" UINT64_FORMAT "k free)", os::available_memory() >> 10); 1852 st->cr(); 1853 (void) check_addr0(st); 1854 } 1855 1856 // Moved from whole group, because we need them here for diagnostic 1857 // prints. 1858 static int Maxsignum = 0; 1859 static int *ourSigFlags = NULL; 1860 1861 int os::Solaris::get_our_sigflags(int sig) { 1862 assert(ourSigFlags!=NULL, "signal data structure not initialized"); 1863 assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range"); 1864 return ourSigFlags[sig]; 1865 } 1866 1867 void os::Solaris::set_our_sigflags(int sig, int flags) { 1868 assert(ourSigFlags!=NULL, "signal data structure not initialized"); 1869 assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range"); 1870 ourSigFlags[sig] = flags; 1871 } 1872 1873 1874 static const char* get_signal_handler_name(address handler, 1875 char* buf, int buflen) { 1876 int offset; 1877 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); 1878 if (found) { 1879 // skip directory names 1880 const char *p1, *p2; 1881 p1 = buf; 1882 size_t len = strlen(os::file_separator()); 1883 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; 1884 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); 1885 } else { 1886 jio_snprintf(buf, buflen, PTR_FORMAT, handler); 1887 } 1888 return buf; 1889 } 1890 1891 static void print_signal_handler(outputStream* st, int sig, 1892 char* buf, size_t buflen) { 1893 struct sigaction sa; 1894 1895 sigaction(sig, NULL, &sa); 1896 1897 st->print("%s: ", os::exception_name(sig, buf, buflen)); 1898 1899 address handler = (sa.sa_flags & SA_SIGINFO) 1900 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) 1901 : CAST_FROM_FN_PTR(address, sa.sa_handler); 1902 1903 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { 1904 st->print("SIG_DFL"); 1905 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { 1906 st->print("SIG_IGN"); 1907 } else { 1908 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); 1909 } 1910 1911 st->print(", sa_mask[0]="); 1912 os::Posix::print_signal_set_short(st, &sa.sa_mask); 1913 1914 address rh = VMError::get_resetted_sighandler(sig); 1915 // May be, handler was resetted by VMError? 1916 if (rh != NULL) { 1917 handler = rh; 1918 sa.sa_flags = VMError::get_resetted_sigflags(sig); 1919 } 1920 1921 st->print(", sa_flags="); 1922 os::Posix::print_sa_flags(st, sa.sa_flags); 1923 1924 // Check: is it our handler? 1925 if (handler == CAST_FROM_FN_PTR(address, signalHandler)) { 1926 // It is our signal handler 1927 // check for flags 1928 if (sa.sa_flags != os::Solaris::get_our_sigflags(sig)) { 1929 st->print( 1930 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", 1931 os::Solaris::get_our_sigflags(sig)); 1932 } 1933 } 1934 st->cr(); 1935 } 1936 1937 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 1938 st->print_cr("Signal Handlers:"); 1939 print_signal_handler(st, SIGSEGV, buf, buflen); 1940 print_signal_handler(st, SIGBUS , buf, buflen); 1941 print_signal_handler(st, SIGFPE , buf, buflen); 1942 print_signal_handler(st, SIGPIPE, buf, buflen); 1943 print_signal_handler(st, SIGXFSZ, buf, buflen); 1944 print_signal_handler(st, SIGILL , buf, buflen); 1945 print_signal_handler(st, ASYNC_SIGNAL, buf, buflen); 1946 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); 1947 print_signal_handler(st, SHUTDOWN1_SIGNAL , buf, buflen); 1948 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); 1949 print_signal_handler(st, SHUTDOWN3_SIGNAL, buf, buflen); 1950 } 1951 1952 static char saved_jvm_path[MAXPATHLEN] = { 0 }; 1953 1954 // Find the full path to the current module, libjvm.so 1955 void os::jvm_path(char *buf, jint buflen) { 1956 // Error checking. 1957 if (buflen < MAXPATHLEN) { 1958 assert(false, "must use a large-enough buffer"); 1959 buf[0] = '\0'; 1960 return; 1961 } 1962 // Lazy resolve the path to current module. 1963 if (saved_jvm_path[0] != 0) { 1964 strcpy(buf, saved_jvm_path); 1965 return; 1966 } 1967 1968 Dl_info dlinfo; 1969 int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo); 1970 assert(ret != 0, "cannot locate libjvm"); 1971 if (ret != 0 && dlinfo.dli_fname != NULL) { 1972 if (os::Posix::realpath((char *)dlinfo.dli_fname, buf, buflen) == NULL) { 1973 return; 1974 } 1975 } else { 1976 buf[0] = '\0'; 1977 return; 1978 } 1979 1980 if (Arguments::sun_java_launcher_is_altjvm()) { 1981 // Support for the java launcher's '-XXaltjvm=<path>' option. Typical 1982 // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". 1983 // If "/jre/lib/" appears at the right place in the string, then 1984 // assume we are installed in a JDK and we're done. Otherwise, check 1985 // for a JAVA_HOME environment variable and fix up the path so it 1986 // looks like libjvm.so is installed there (append a fake suffix 1987 // hotspot/libjvm.so). 1988 const char *p = buf + strlen(buf) - 1; 1989 for (int count = 0; p > buf && count < 5; ++count) { 1990 for (--p; p > buf && *p != '/'; --p) 1991 /* empty */ ; 1992 } 1993 1994 if (strncmp(p, "/jre/lib/", 9) != 0) { 1995 // Look for JAVA_HOME in the environment. 1996 char* java_home_var = ::getenv("JAVA_HOME"); 1997 if (java_home_var != NULL && java_home_var[0] != 0) { 1998 char* jrelib_p; 1999 int len; 2000 2001 // Check the current module name "libjvm.so". 2002 p = strrchr(buf, '/'); 2003 assert(strstr(p, "/libjvm") == p, "invalid library name"); 2004 2005 if (os::Posix::realpath(java_home_var, buf, buflen) == NULL) { 2006 return; 2007 } 2008 // determine if this is a legacy image or modules image 2009 // modules image doesn't have "jre" subdirectory 2010 len = strlen(buf); 2011 assert(len < buflen, "Ran out of buffer space"); 2012 jrelib_p = buf + len; 2013 snprintf(jrelib_p, buflen-len, "/jre/lib"); 2014 if (0 != access(buf, F_OK)) { 2015 snprintf(jrelib_p, buflen-len, "/lib"); 2016 } 2017 2018 if (0 == access(buf, F_OK)) { 2019 // Use current module name "libjvm.so" 2020 len = strlen(buf); 2021 snprintf(buf + len, buflen-len, "/hotspot/libjvm.so"); 2022 } else { 2023 // Go back to path of .so 2024 if (os::Posix::realpath((char *)dlinfo.dli_fname, buf, buflen) == NULL) { 2025 return; 2026 } 2027 } 2028 } 2029 } 2030 } 2031 2032 strncpy(saved_jvm_path, buf, MAXPATHLEN); 2033 saved_jvm_path[MAXPATHLEN - 1] = '\0'; 2034 } 2035 2036 2037 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 2038 // no prefix required, not even "_" 2039 } 2040 2041 2042 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 2043 // no suffix required 2044 } 2045 2046 // sun.misc.Signal 2047 2048 extern "C" { 2049 static void UserHandler(int sig, void *siginfo, void *context) { 2050 // Ctrl-C is pressed during error reporting, likely because the error 2051 // handler fails to abort. Let VM die immediately. 2052 if (sig == SIGINT && VMError::is_error_reported()) { 2053 os::die(); 2054 } 2055 2056 os::signal_notify(sig); 2057 // We do not need to reinstate the signal handler each time... 2058 } 2059 } 2060 2061 void* os::user_handler() { 2062 return CAST_FROM_FN_PTR(void*, UserHandler); 2063 } 2064 2065 extern "C" { 2066 typedef void (*sa_handler_t)(int); 2067 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); 2068 } 2069 2070 void* os::signal(int signal_number, void* handler) { 2071 struct sigaction sigAct, oldSigAct; 2072 sigfillset(&(sigAct.sa_mask)); 2073 sigAct.sa_flags = SA_RESTART & ~SA_RESETHAND; 2074 sigAct.sa_flags |= SA_SIGINFO; 2075 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); 2076 2077 if (sigaction(signal_number, &sigAct, &oldSigAct)) { 2078 // -1 means registration failed 2079 return (void *)-1; 2080 } 2081 2082 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); 2083 } 2084 2085 void os::signal_raise(int signal_number) { 2086 raise(signal_number); 2087 } 2088 2089 // The following code is moved from os.cpp for making this 2090 // code platform specific, which it is by its very nature. 2091 2092 // a counter for each possible signal value 2093 static int Sigexit = 0; 2094 static jint *pending_signals = NULL; 2095 static int *preinstalled_sigs = NULL; 2096 static struct sigaction *chainedsigactions = NULL; 2097 static Semaphore* sig_sem = NULL; 2098 2099 int os::sigexitnum_pd() { 2100 assert(Sigexit > 0, "signal memory not yet initialized"); 2101 return Sigexit; 2102 } 2103 2104 void os::Solaris::init_signal_mem() { 2105 // Initialize signal structures 2106 Maxsignum = SIGRTMAX; 2107 Sigexit = Maxsignum+1; 2108 assert(Maxsignum >0, "Unable to obtain max signal number"); 2109 2110 // Initialize signal structures 2111 // pending_signals has one int per signal 2112 // The additional signal is for SIGEXIT - exit signal to signal_thread 2113 pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal); 2114 memset(pending_signals, 0, (sizeof(jint) * (Sigexit+1))); 2115 2116 if (UseSignalChaining) { 2117 chainedsigactions = (struct sigaction *)malloc(sizeof(struct sigaction) 2118 * (Maxsignum + 1), mtInternal); 2119 memset(chainedsigactions, 0, (sizeof(struct sigaction) * (Maxsignum + 1))); 2120 preinstalled_sigs = (int *)os::malloc(sizeof(int) * (Maxsignum + 1), mtInternal); 2121 memset(preinstalled_sigs, 0, (sizeof(int) * (Maxsignum + 1))); 2122 } 2123 ourSigFlags = (int*)malloc(sizeof(int) * (Maxsignum + 1), mtInternal); 2124 memset(ourSigFlags, 0, sizeof(int) * (Maxsignum + 1)); 2125 } 2126 2127 static void jdk_misc_signal_init() { 2128 // Initialize signal semaphore 2129 sig_sem = new Semaphore(); 2130 } 2131 2132 void os::signal_notify(int sig) { 2133 if (sig_sem != NULL) { 2134 Atomic::inc(&pending_signals[sig]); 2135 sig_sem->signal(); 2136 } else { 2137 // Signal thread is not created with ReduceSignalUsage and jdk_misc_signal_init 2138 // initialization isn't called. 2139 assert(ReduceSignalUsage, "signal semaphore should be created"); 2140 } 2141 } 2142 2143 static int check_pending_signals() { 2144 int ret; 2145 while (true) { 2146 for (int i = 0; i < Sigexit + 1; i++) { 2147 jint n = pending_signals[i]; 2148 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 2149 return i; 2150 } 2151 } 2152 JavaThread *thread = JavaThread::current(); 2153 ThreadBlockInVM tbivm(thread); 2154 2155 bool threadIsSuspended; 2156 do { 2157 thread->set_suspend_equivalent(); 2158 sig_sem->wait(); 2159 2160 // were we externally suspended while we were waiting? 2161 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 2162 if (threadIsSuspended) { 2163 // The semaphore has been incremented, but while we were waiting 2164 // another thread suspended us. We don't want to continue running 2165 // while suspended because that would surprise the thread that 2166 // suspended us. 2167 sig_sem->signal(); 2168 2169 thread->java_suspend_self(); 2170 } 2171 } while (threadIsSuspended); 2172 } 2173 } 2174 2175 int os::signal_wait() { 2176 return check_pending_signals(); 2177 } 2178 2179 //////////////////////////////////////////////////////////////////////////////// 2180 // Virtual Memory 2181 2182 static int page_size = -1; 2183 2184 int os::vm_page_size() { 2185 assert(page_size != -1, "must call os::init"); 2186 return page_size; 2187 } 2188 2189 // Solaris allocates memory by pages. 2190 int os::vm_allocation_granularity() { 2191 assert(page_size != -1, "must call os::init"); 2192 return page_size; 2193 } 2194 2195 static bool recoverable_mmap_error(int err) { 2196 // See if the error is one we can let the caller handle. This 2197 // list of errno values comes from the Solaris mmap(2) man page. 2198 switch (err) { 2199 case EBADF: 2200 case EINVAL: 2201 case ENOTSUP: 2202 // let the caller deal with these errors 2203 return true; 2204 2205 default: 2206 // Any remaining errors on this OS can cause our reserved mapping 2207 // to be lost. That can cause confusion where different data 2208 // structures think they have the same memory mapped. The worst 2209 // scenario is if both the VM and a library think they have the 2210 // same memory mapped. 2211 return false; 2212 } 2213 } 2214 2215 static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec, 2216 int err) { 2217 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2218 ", %d) failed; error='%s' (errno=%d)", addr, bytes, exec, 2219 os::strerror(err), err); 2220 } 2221 2222 static void warn_fail_commit_memory(char* addr, size_t bytes, 2223 size_t alignment_hint, bool exec, 2224 int err) { 2225 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2226 ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, bytes, 2227 alignment_hint, exec, os::strerror(err), err); 2228 } 2229 2230 int os::Solaris::commit_memory_impl(char* addr, size_t bytes, bool exec) { 2231 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 2232 size_t size = bytes; 2233 char *res = Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot); 2234 if (res != NULL) { 2235 if (UseNUMAInterleaving) { 2236 numa_make_global(addr, bytes); 2237 } 2238 return 0; 2239 } 2240 2241 int err = errno; // save errno from mmap() call in mmap_chunk() 2242 2243 if (!recoverable_mmap_error(err)) { 2244 warn_fail_commit_memory(addr, bytes, exec, err); 2245 vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "committing reserved memory."); 2246 } 2247 2248 return err; 2249 } 2250 2251 bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) { 2252 return Solaris::commit_memory_impl(addr, bytes, exec) == 0; 2253 } 2254 2255 void os::pd_commit_memory_or_exit(char* addr, size_t bytes, bool exec, 2256 const char* mesg) { 2257 assert(mesg != NULL, "mesg must be specified"); 2258 int err = os::Solaris::commit_memory_impl(addr, bytes, exec); 2259 if (err != 0) { 2260 // the caller wants all commit errors to exit with the specified mesg: 2261 warn_fail_commit_memory(addr, bytes, exec, err); 2262 vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg); 2263 } 2264 } 2265 2266 size_t os::Solaris::page_size_for_alignment(size_t alignment) { 2267 assert(is_aligned(alignment, (size_t) vm_page_size()), 2268 SIZE_FORMAT " is not aligned to " SIZE_FORMAT, 2269 alignment, (size_t) vm_page_size()); 2270 2271 for (int i = 0; _page_sizes[i] != 0; i++) { 2272 if (is_aligned(alignment, _page_sizes[i])) { 2273 return _page_sizes[i]; 2274 } 2275 } 2276 2277 return (size_t) vm_page_size(); 2278 } 2279 2280 int os::Solaris::commit_memory_impl(char* addr, size_t bytes, 2281 size_t alignment_hint, bool exec) { 2282 int err = Solaris::commit_memory_impl(addr, bytes, exec); 2283 if (err == 0 && UseLargePages && alignment_hint > 0) { 2284 assert(is_aligned(bytes, alignment_hint), 2285 SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, alignment_hint); 2286 2287 // The syscall memcntl requires an exact page size (see man memcntl for details). 2288 size_t page_size = page_size_for_alignment(alignment_hint); 2289 if (page_size > (size_t) vm_page_size()) { 2290 (void)Solaris::setup_large_pages(addr, bytes, page_size); 2291 } 2292 } 2293 return err; 2294 } 2295 2296 bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint, 2297 bool exec) { 2298 return Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec) == 0; 2299 } 2300 2301 void os::pd_commit_memory_or_exit(char* addr, size_t bytes, 2302 size_t alignment_hint, bool exec, 2303 const char* mesg) { 2304 assert(mesg != NULL, "mesg must be specified"); 2305 int err = os::Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec); 2306 if (err != 0) { 2307 // the caller wants all commit errors to exit with the specified mesg: 2308 warn_fail_commit_memory(addr, bytes, alignment_hint, exec, err); 2309 vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg); 2310 } 2311 } 2312 2313 // Uncommit the pages in a specified region. 2314 void os::pd_free_memory(char* addr, size_t bytes, size_t alignment_hint) { 2315 if (madvise(addr, bytes, MADV_FREE) < 0) { 2316 debug_only(warning("MADV_FREE failed.")); 2317 return; 2318 } 2319 } 2320 2321 bool os::pd_create_stack_guard_pages(char* addr, size_t size) { 2322 return os::commit_memory(addr, size, !ExecMem); 2323 } 2324 2325 bool os::remove_stack_guard_pages(char* addr, size_t size) { 2326 return os::uncommit_memory(addr, size); 2327 } 2328 2329 // Change the page size in a given range. 2330 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { 2331 assert((intptr_t)addr % alignment_hint == 0, "Address should be aligned."); 2332 assert((intptr_t)(addr + bytes) % alignment_hint == 0, "End should be aligned."); 2333 if (UseLargePages) { 2334 size_t page_size = Solaris::page_size_for_alignment(alignment_hint); 2335 if (page_size > (size_t) vm_page_size()) { 2336 Solaris::setup_large_pages(addr, bytes, page_size); 2337 } 2338 } 2339 } 2340 2341 // Tell the OS to make the range local to the first-touching LWP 2342 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { 2343 assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned."); 2344 if (madvise(addr, bytes, MADV_ACCESS_LWP) < 0) { 2345 debug_only(warning("MADV_ACCESS_LWP failed.")); 2346 } 2347 } 2348 2349 // Tell the OS that this range would be accessed from different LWPs. 2350 void os::numa_make_global(char *addr, size_t bytes) { 2351 assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned."); 2352 if (madvise(addr, bytes, MADV_ACCESS_MANY) < 0) { 2353 debug_only(warning("MADV_ACCESS_MANY failed.")); 2354 } 2355 } 2356 2357 // Get the number of the locality groups. 2358 size_t os::numa_get_groups_num() { 2359 size_t n = Solaris::lgrp_nlgrps(Solaris::lgrp_cookie()); 2360 return n != -1 ? n : 1; 2361 } 2362 2363 // Get a list of leaf locality groups. A leaf lgroup is group that 2364 // doesn't have any children. Typical leaf group is a CPU or a CPU/memory 2365 // board. An LWP is assigned to one of these groups upon creation. 2366 size_t os::numa_get_leaf_groups(int *ids, size_t size) { 2367 if ((ids[0] = Solaris::lgrp_root(Solaris::lgrp_cookie())) == -1) { 2368 ids[0] = 0; 2369 return 1; 2370 } 2371 int result_size = 0, top = 1, bottom = 0, cur = 0; 2372 for (int k = 0; k < size; k++) { 2373 int r = Solaris::lgrp_children(Solaris::lgrp_cookie(), ids[cur], 2374 (Solaris::lgrp_id_t*)&ids[top], size - top); 2375 if (r == -1) { 2376 ids[0] = 0; 2377 return 1; 2378 } 2379 if (!r) { 2380 // That's a leaf node. 2381 assert(bottom <= cur, "Sanity check"); 2382 // Check if the node has memory 2383 if (Solaris::lgrp_resources(Solaris::lgrp_cookie(), ids[cur], 2384 NULL, 0, LGRP_RSRC_MEM) > 0) { 2385 ids[bottom++] = ids[cur]; 2386 } 2387 } 2388 top += r; 2389 cur++; 2390 } 2391 if (bottom == 0) { 2392 // Handle a situation, when the OS reports no memory available. 2393 // Assume UMA architecture. 2394 ids[0] = 0; 2395 return 1; 2396 } 2397 return bottom; 2398 } 2399 2400 // Detect the topology change. Typically happens during CPU plugging-unplugging. 2401 bool os::numa_topology_changed() { 2402 int is_stale = Solaris::lgrp_cookie_stale(Solaris::lgrp_cookie()); 2403 if (is_stale != -1 && is_stale) { 2404 Solaris::lgrp_fini(Solaris::lgrp_cookie()); 2405 Solaris::lgrp_cookie_t c = Solaris::lgrp_init(Solaris::LGRP_VIEW_CALLER); 2406 assert(c != 0, "Failure to initialize LGRP API"); 2407 Solaris::set_lgrp_cookie(c); 2408 return true; 2409 } 2410 return false; 2411 } 2412 2413 // Get the group id of the current LWP. 2414 int os::numa_get_group_id() { 2415 int lgrp_id = Solaris::lgrp_home(P_LWPID, P_MYID); 2416 if (lgrp_id == -1) { 2417 return 0; 2418 } 2419 const int size = os::numa_get_groups_num(); 2420 int *ids = (int*)alloca(size * sizeof(int)); 2421 2422 // Get the ids of all lgroups with memory; r is the count. 2423 int r = Solaris::lgrp_resources(Solaris::lgrp_cookie(), lgrp_id, 2424 (Solaris::lgrp_id_t*)ids, size, LGRP_RSRC_MEM); 2425 if (r <= 0) { 2426 return 0; 2427 } 2428 return ids[os::random() % r]; 2429 } 2430 2431 // Request information about the page. 2432 bool os::get_page_info(char *start, page_info* info) { 2433 const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE }; 2434 uint64_t addr = (uintptr_t)start; 2435 uint64_t outdata[2]; 2436 uint_t validity = 0; 2437 2438 if (meminfo(&addr, 1, info_types, 2, outdata, &validity) < 0) { 2439 return false; 2440 } 2441 2442 info->size = 0; 2443 info->lgrp_id = -1; 2444 2445 if ((validity & 1) != 0) { 2446 if ((validity & 2) != 0) { 2447 info->lgrp_id = outdata[0]; 2448 } 2449 if ((validity & 4) != 0) { 2450 info->size = outdata[1]; 2451 } 2452 return true; 2453 } 2454 return false; 2455 } 2456 2457 // Scan the pages from start to end until a page different than 2458 // the one described in the info parameter is encountered. 2459 char *os::scan_pages(char *start, char* end, page_info* page_expected, 2460 page_info* page_found) { 2461 const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE }; 2462 const size_t types = sizeof(info_types) / sizeof(info_types[0]); 2463 uint64_t addrs[MAX_MEMINFO_CNT], outdata[types * MAX_MEMINFO_CNT + 1]; 2464 uint_t validity[MAX_MEMINFO_CNT]; 2465 2466 size_t page_size = MAX2((size_t)os::vm_page_size(), page_expected->size); 2467 uint64_t p = (uint64_t)start; 2468 while (p < (uint64_t)end) { 2469 addrs[0] = p; 2470 size_t addrs_count = 1; 2471 while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] + page_size < (uint64_t)end) { 2472 addrs[addrs_count] = addrs[addrs_count - 1] + page_size; 2473 addrs_count++; 2474 } 2475 2476 if (meminfo(addrs, addrs_count, info_types, types, outdata, validity) < 0) { 2477 return NULL; 2478 } 2479 2480 size_t i = 0; 2481 for (; i < addrs_count; i++) { 2482 if ((validity[i] & 1) != 0) { 2483 if ((validity[i] & 4) != 0) { 2484 if (outdata[types * i + 1] != page_expected->size) { 2485 break; 2486 } 2487 } else if (page_expected->size != 0) { 2488 break; 2489 } 2490 2491 if ((validity[i] & 2) != 0 && page_expected->lgrp_id > 0) { 2492 if (outdata[types * i] != page_expected->lgrp_id) { 2493 break; 2494 } 2495 } 2496 } else { 2497 return NULL; 2498 } 2499 } 2500 2501 if (i < addrs_count) { 2502 if ((validity[i] & 2) != 0) { 2503 page_found->lgrp_id = outdata[types * i]; 2504 } else { 2505 page_found->lgrp_id = -1; 2506 } 2507 if ((validity[i] & 4) != 0) { 2508 page_found->size = outdata[types * i + 1]; 2509 } else { 2510 page_found->size = 0; 2511 } 2512 return (char*)addrs[i]; 2513 } 2514 2515 p = addrs[addrs_count - 1] + page_size; 2516 } 2517 return end; 2518 } 2519 2520 bool os::pd_uncommit_memory(char* addr, size_t bytes) { 2521 size_t size = bytes; 2522 // Map uncommitted pages PROT_NONE so we fail early if we touch an 2523 // uncommitted page. Otherwise, the read/write might succeed if we 2524 // have enough swap space to back the physical page. 2525 return 2526 NULL != Solaris::mmap_chunk(addr, size, 2527 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, 2528 PROT_NONE); 2529 } 2530 2531 char* os::Solaris::mmap_chunk(char *addr, size_t size, int flags, int prot) { 2532 char *b = (char *)mmap(addr, size, prot, flags, os::Solaris::_dev_zero_fd, 0); 2533 2534 if (b == MAP_FAILED) { 2535 return NULL; 2536 } 2537 return b; 2538 } 2539 2540 char* os::Solaris::anon_mmap(char* requested_addr, size_t bytes, 2541 size_t alignment_hint, bool fixed) { 2542 char* addr = requested_addr; 2543 int flags = MAP_PRIVATE | MAP_NORESERVE; 2544 2545 assert(!(fixed && (alignment_hint > 0)), 2546 "alignment hint meaningless with fixed mmap"); 2547 2548 if (fixed) { 2549 flags |= MAP_FIXED; 2550 } else if (alignment_hint > (size_t) vm_page_size()) { 2551 flags |= MAP_ALIGN; 2552 addr = (char*) alignment_hint; 2553 } 2554 2555 // Map uncommitted pages PROT_NONE so we fail early if we touch an 2556 // uncommitted page. Otherwise, the read/write might succeed if we 2557 // have enough swap space to back the physical page. 2558 return mmap_chunk(addr, bytes, flags, PROT_NONE); 2559 } 2560 2561 char* os::pd_reserve_memory(size_t bytes, char* requested_addr, 2562 size_t alignment_hint) { 2563 char* addr = Solaris::anon_mmap(requested_addr, bytes, alignment_hint, 2564 (requested_addr != NULL)); 2565 2566 guarantee(requested_addr == NULL || requested_addr == addr, 2567 "OS failed to return requested mmap address."); 2568 return addr; 2569 } 2570 2571 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr, int file_desc) { 2572 assert(file_desc >= 0, "file_desc is not valid"); 2573 char* result = pd_attempt_reserve_memory_at(bytes, requested_addr); 2574 if (result != NULL) { 2575 if (replace_existing_mapping_with_file_mapping(result, bytes, file_desc) == NULL) { 2576 vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory")); 2577 } 2578 } 2579 return result; 2580 } 2581 2582 // Reserve memory at an arbitrary address, only if that area is 2583 // available (and not reserved for something else). 2584 2585 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 2586 // Assert only that the size is a multiple of the page size, since 2587 // that's all that mmap requires, and since that's all we really know 2588 // about at this low abstraction level. If we need higher alignment, 2589 // we can either pass an alignment to this method or verify alignment 2590 // in one of the methods further up the call chain. See bug 5044738. 2591 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); 2592 2593 // Since snv_84, Solaris attempts to honor the address hint - see 5003415. 2594 char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false); 2595 2596 volatile int err = errno; 2597 if (addr == requested_addr) { 2598 return addr; 2599 } 2600 2601 if (addr != NULL) { 2602 pd_unmap_memory(addr, bytes); 2603 } 2604 2605 return NULL; 2606 } 2607 2608 bool os::pd_release_memory(char* addr, size_t bytes) { 2609 size_t size = bytes; 2610 return munmap(addr, size) == 0; 2611 } 2612 2613 static bool solaris_mprotect(char* addr, size_t bytes, int prot) { 2614 assert(addr == (char*)align_down((uintptr_t)addr, os::vm_page_size()), 2615 "addr must be page aligned"); 2616 Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(addr), p2i(addr+bytes), prot); 2617 int retVal = mprotect(addr, bytes, prot); 2618 return retVal == 0; 2619 } 2620 2621 // Protect memory (Used to pass readonly pages through 2622 // JNI GetArray<type>Elements with empty arrays.) 2623 // Also, used for serialization page and for compressed oops null pointer 2624 // checking. 2625 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 2626 bool is_committed) { 2627 unsigned int p = 0; 2628 switch (prot) { 2629 case MEM_PROT_NONE: p = PROT_NONE; break; 2630 case MEM_PROT_READ: p = PROT_READ; break; 2631 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; 2632 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; 2633 default: 2634 ShouldNotReachHere(); 2635 } 2636 // is_committed is unused. 2637 return solaris_mprotect(addr, bytes, p); 2638 } 2639 2640 // guard_memory and unguard_memory only happens within stack guard pages. 2641 // Since ISM pertains only to the heap, guard and unguard memory should not 2642 /// happen with an ISM region. 2643 bool os::guard_memory(char* addr, size_t bytes) { 2644 return solaris_mprotect(addr, bytes, PROT_NONE); 2645 } 2646 2647 bool os::unguard_memory(char* addr, size_t bytes) { 2648 return solaris_mprotect(addr, bytes, PROT_READ|PROT_WRITE); 2649 } 2650 2651 // Large page support 2652 static size_t _large_page_size = 0; 2653 2654 // Insertion sort for small arrays (descending order). 2655 static void insertion_sort_descending(size_t* array, int len) { 2656 for (int i = 0; i < len; i++) { 2657 size_t val = array[i]; 2658 for (size_t key = i; key > 0 && array[key - 1] < val; --key) { 2659 size_t tmp = array[key]; 2660 array[key] = array[key - 1]; 2661 array[key - 1] = tmp; 2662 } 2663 } 2664 } 2665 2666 bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) { 2667 const unsigned int usable_count = VM_Version::page_size_count(); 2668 if (usable_count == 1) { 2669 return false; 2670 } 2671 2672 // Find the right getpagesizes interface. When solaris 11 is the minimum 2673 // build platform, getpagesizes() (without the '2') can be called directly. 2674 typedef int (*gps_t)(size_t[], int); 2675 gps_t gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes2")); 2676 if (gps_func == NULL) { 2677 gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes")); 2678 if (gps_func == NULL) { 2679 if (warn) { 2680 warning("MPSS is not supported by the operating system."); 2681 } 2682 return false; 2683 } 2684 } 2685 2686 // Fill the array of page sizes. 2687 int n = (*gps_func)(_page_sizes, page_sizes_max); 2688 assert(n > 0, "Solaris bug?"); 2689 2690 if (n == page_sizes_max) { 2691 // Add a sentinel value (necessary only if the array was completely filled 2692 // since it is static (zeroed at initialization)). 2693 _page_sizes[--n] = 0; 2694 DEBUG_ONLY(warning("increase the size of the os::_page_sizes array.");) 2695 } 2696 assert(_page_sizes[n] == 0, "missing sentinel"); 2697 trace_page_sizes("available page sizes", _page_sizes, n); 2698 2699 if (n == 1) return false; // Only one page size available. 2700 2701 // Skip sizes larger than 4M (or LargePageSizeInBytes if it was set) and 2702 // select up to usable_count elements. First sort the array, find the first 2703 // acceptable value, then copy the usable sizes to the top of the array and 2704 // trim the rest. Make sure to include the default page size :-). 2705 // 2706 // A better policy could get rid of the 4M limit by taking the sizes of the 2707 // important VM memory regions (java heap and possibly the code cache) into 2708 // account. 2709 insertion_sort_descending(_page_sizes, n); 2710 const size_t size_limit = 2711 FLAG_IS_DEFAULT(LargePageSizeInBytes) ? 4 * M : LargePageSizeInBytes; 2712 int beg; 2713 for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */; 2714 const int end = MIN2((int)usable_count, n) - 1; 2715 for (int cur = 0; cur < end; ++cur, ++beg) { 2716 _page_sizes[cur] = _page_sizes[beg]; 2717 } 2718 _page_sizes[end] = vm_page_size(); 2719 _page_sizes[end + 1] = 0; 2720 2721 if (_page_sizes[end] > _page_sizes[end - 1]) { 2722 // Default page size is not the smallest; sort again. 2723 insertion_sort_descending(_page_sizes, end + 1); 2724 } 2725 *page_size = _page_sizes[0]; 2726 2727 trace_page_sizes("usable page sizes", _page_sizes, end + 1); 2728 return true; 2729 } 2730 2731 void os::large_page_init() { 2732 if (UseLargePages) { 2733 // print a warning if any large page related flag is specified on command line 2734 bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) || 2735 !FLAG_IS_DEFAULT(LargePageSizeInBytes); 2736 2737 UseLargePages = Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size); 2738 } 2739 } 2740 2741 bool os::Solaris::is_valid_page_size(size_t bytes) { 2742 for (int i = 0; _page_sizes[i] != 0; i++) { 2743 if (_page_sizes[i] == bytes) { 2744 return true; 2745 } 2746 } 2747 return false; 2748 } 2749 2750 bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) { 2751 assert(is_valid_page_size(align), SIZE_FORMAT " is not a valid page size", align); 2752 assert(is_aligned((void*) start, align), 2753 PTR_FORMAT " is not aligned to " SIZE_FORMAT, p2i((void*) start), align); 2754 assert(is_aligned(bytes, align), 2755 SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, align); 2756 2757 // Signal to OS that we want large pages for addresses 2758 // from addr, addr + bytes 2759 struct memcntl_mha mpss_struct; 2760 mpss_struct.mha_cmd = MHA_MAPSIZE_VA; 2761 mpss_struct.mha_pagesize = align; 2762 mpss_struct.mha_flags = 0; 2763 // Upon successful completion, memcntl() returns 0 2764 if (memcntl(start, bytes, MC_HAT_ADVISE, (caddr_t) &mpss_struct, 0, 0)) { 2765 debug_only(warning("Attempt to use MPSS failed.")); 2766 return false; 2767 } 2768 return true; 2769 } 2770 2771 char* os::reserve_memory_special(size_t size, size_t alignment, char* addr, bool exec) { 2772 fatal("os::reserve_memory_special should not be called on Solaris."); 2773 return NULL; 2774 } 2775 2776 bool os::release_memory_special(char* base, size_t bytes) { 2777 fatal("os::release_memory_special should not be called on Solaris."); 2778 return false; 2779 } 2780 2781 size_t os::large_page_size() { 2782 return _large_page_size; 2783 } 2784 2785 // MPSS allows application to commit large page memory on demand; with ISM 2786 // the entire memory region must be allocated as shared memory. 2787 bool os::can_commit_large_page_memory() { 2788 return true; 2789 } 2790 2791 bool os::can_execute_large_page_memory() { 2792 return true; 2793 } 2794 2795 // Sleep forever; naked call to OS-specific sleep; use with CAUTION 2796 void os::infinite_sleep() { 2797 while (true) { // sleep forever ... 2798 ::sleep(100); // ... 100 seconds at a time 2799 } 2800 } 2801 2802 // Used to convert frequent JVM_Yield() to nops 2803 bool os::dont_yield() { 2804 if (DontYieldALot) { 2805 static hrtime_t last_time = 0; 2806 hrtime_t diff = getTimeNanos() - last_time; 2807 2808 if (diff < DontYieldALotInterval * 1000000) { 2809 return true; 2810 } 2811 2812 last_time += diff; 2813 2814 return false; 2815 } else { 2816 return false; 2817 } 2818 } 2819 2820 // Note that yield semantics are defined by the scheduling class to which 2821 // the thread currently belongs. Typically, yield will _not yield to 2822 // other equal or higher priority threads that reside on the dispatch queues 2823 // of other CPUs. 2824 2825 void os::naked_yield() { 2826 thr_yield(); 2827 } 2828 2829 // Interface for setting lwp priorities. We are using T2 libthread, 2830 // which forces the use of bound threads, so all of our threads will 2831 // be assigned to real lwp's. Using the thr_setprio function is 2832 // meaningless in this mode so we must adjust the real lwp's priority. 2833 // The routines below implement the getting and setting of lwp priorities. 2834 // 2835 // Note: There are three priority scales used on Solaris. Java priotities 2836 // which range from 1 to 10, libthread "thr_setprio" scale which range 2837 // from 0 to 127, and the current scheduling class of the process we 2838 // are running in. This is typically from -60 to +60. 2839 // The setting of the lwp priorities in done after a call to thr_setprio 2840 // so Java priorities are mapped to libthread priorities and we map from 2841 // the latter to lwp priorities. We don't keep priorities stored in 2842 // Java priorities since some of our worker threads want to set priorities 2843 // higher than all Java threads. 2844 // 2845 // For related information: 2846 // (1) man -s 2 priocntl 2847 // (2) man -s 4 priocntl 2848 // (3) man dispadmin 2849 // = librt.so 2850 // = libthread/common/rtsched.c - thrp_setlwpprio(). 2851 // = ps -cL <pid> ... to validate priority. 2852 // = sched_get_priority_min and _max 2853 // pthread_create 2854 // sched_setparam 2855 // pthread_setschedparam 2856 // 2857 // Assumptions: 2858 // + We assume that all threads in the process belong to the same 2859 // scheduling class. IE. an homogenous process. 2860 // + Must be root or in IA group to change change "interactive" attribute. 2861 // Priocntl() will fail silently. The only indication of failure is when 2862 // we read-back the value and notice that it hasn't changed. 2863 // + Interactive threads enter the runq at the head, non-interactive at the tail. 2864 // + For RT, change timeslice as well. Invariant: 2865 // constant "priority integral" 2866 // Konst == TimeSlice * (60-Priority) 2867 // Given a priority, compute appropriate timeslice. 2868 // + Higher numerical values have higher priority. 2869 2870 // sched class attributes 2871 typedef struct { 2872 int schedPolicy; // classID 2873 int maxPrio; 2874 int minPrio; 2875 } SchedInfo; 2876 2877 2878 static SchedInfo tsLimits, iaLimits, rtLimits, fxLimits; 2879 2880 #ifdef ASSERT 2881 static int ReadBackValidate = 1; 2882 #endif 2883 static int myClass = 0; 2884 static int myMin = 0; 2885 static int myMax = 0; 2886 static int myCur = 0; 2887 static bool priocntl_enable = false; 2888 2889 static const int criticalPrio = FXCriticalPriority; 2890 static int java_MaxPriority_to_os_priority = 0; // Saved mapping 2891 2892 2893 // lwp_priocntl_init 2894 // 2895 // Try to determine the priority scale for our process. 2896 // 2897 // Return errno or 0 if OK. 2898 // 2899 static int lwp_priocntl_init() { 2900 int rslt; 2901 pcinfo_t ClassInfo; 2902 pcparms_t ParmInfo; 2903 int i; 2904 2905 if (!UseThreadPriorities) return 0; 2906 2907 // If ThreadPriorityPolicy is 1, switch tables 2908 if (ThreadPriorityPolicy == 1) { 2909 for (i = 0; i < CriticalPriority+1; i++) 2910 os::java_to_os_priority[i] = prio_policy1[i]; 2911 } 2912 if (UseCriticalJavaThreadPriority) { 2913 // MaxPriority always maps to the FX scheduling class and criticalPrio. 2914 // See set_native_priority() and set_lwp_class_and_priority(). 2915 // Save original MaxPriority mapping in case attempt to 2916 // use critical priority fails. 2917 java_MaxPriority_to_os_priority = os::java_to_os_priority[MaxPriority]; 2918 // Set negative to distinguish from other priorities 2919 os::java_to_os_priority[MaxPriority] = -criticalPrio; 2920 } 2921 2922 // Get IDs for a set of well-known scheduling classes. 2923 // TODO-FIXME: GETCLINFO returns the current # of classes in the 2924 // the system. We should have a loop that iterates over the 2925 // classID values, which are known to be "small" integers. 2926 2927 strcpy(ClassInfo.pc_clname, "TS"); 2928 ClassInfo.pc_cid = -1; 2929 rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); 2930 if (rslt < 0) return errno; 2931 assert(ClassInfo.pc_cid != -1, "cid for TS class is -1"); 2932 tsLimits.schedPolicy = ClassInfo.pc_cid; 2933 tsLimits.maxPrio = ((tsinfo_t*)ClassInfo.pc_clinfo)->ts_maxupri; 2934 tsLimits.minPrio = -tsLimits.maxPrio; 2935 2936 strcpy(ClassInfo.pc_clname, "IA"); 2937 ClassInfo.pc_cid = -1; 2938 rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); 2939 if (rslt < 0) return errno; 2940 assert(ClassInfo.pc_cid != -1, "cid for IA class is -1"); 2941 iaLimits.schedPolicy = ClassInfo.pc_cid; 2942 iaLimits.maxPrio = ((iainfo_t*)ClassInfo.pc_clinfo)->ia_maxupri; 2943 iaLimits.minPrio = -iaLimits.maxPrio; 2944 2945 strcpy(ClassInfo.pc_clname, "RT"); 2946 ClassInfo.pc_cid = -1; 2947 rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); 2948 if (rslt < 0) return errno; 2949 assert(ClassInfo.pc_cid != -1, "cid for RT class is -1"); 2950 rtLimits.schedPolicy = ClassInfo.pc_cid; 2951 rtLimits.maxPrio = ((rtinfo_t*)ClassInfo.pc_clinfo)->rt_maxpri; 2952 rtLimits.minPrio = 0; 2953 2954 strcpy(ClassInfo.pc_clname, "FX"); 2955 ClassInfo.pc_cid = -1; 2956 rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); 2957 if (rslt < 0) return errno; 2958 assert(ClassInfo.pc_cid != -1, "cid for FX class is -1"); 2959 fxLimits.schedPolicy = ClassInfo.pc_cid; 2960 fxLimits.maxPrio = ((fxinfo_t*)ClassInfo.pc_clinfo)->fx_maxupri; 2961 fxLimits.minPrio = 0; 2962 2963 // Query our "current" scheduling class. 2964 // This will normally be IA, TS or, rarely, FX or RT. 2965 memset(&ParmInfo, 0, sizeof(ParmInfo)); 2966 ParmInfo.pc_cid = PC_CLNULL; 2967 rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo); 2968 if (rslt < 0) return errno; 2969 myClass = ParmInfo.pc_cid; 2970 2971 // We now know our scheduling classId, get specific information 2972 // about the class. 2973 ClassInfo.pc_cid = myClass; 2974 ClassInfo.pc_clname[0] = 0; 2975 rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo); 2976 if (rslt < 0) return errno; 2977 2978 if (ThreadPriorityVerbose) { 2979 tty->print_cr("lwp_priocntl_init: Class=%d(%s)...", myClass, ClassInfo.pc_clname); 2980 } 2981 2982 memset(&ParmInfo, 0, sizeof(pcparms_t)); 2983 ParmInfo.pc_cid = PC_CLNULL; 2984 rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo); 2985 if (rslt < 0) return errno; 2986 2987 if (ParmInfo.pc_cid == rtLimits.schedPolicy) { 2988 myMin = rtLimits.minPrio; 2989 myMax = rtLimits.maxPrio; 2990 } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) { 2991 iaparms_t *iaInfo = (iaparms_t*)ParmInfo.pc_clparms; 2992 myMin = iaLimits.minPrio; 2993 myMax = iaLimits.maxPrio; 2994 myMax = MIN2(myMax, (int)iaInfo->ia_uprilim); // clamp - restrict 2995 } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) { 2996 tsparms_t *tsInfo = (tsparms_t*)ParmInfo.pc_clparms; 2997 myMin = tsLimits.minPrio; 2998 myMax = tsLimits.maxPrio; 2999 myMax = MIN2(myMax, (int)tsInfo->ts_uprilim); // clamp - restrict 3000 } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) { 3001 fxparms_t *fxInfo = (fxparms_t*)ParmInfo.pc_clparms; 3002 myMin = fxLimits.minPrio; 3003 myMax = fxLimits.maxPrio; 3004 myMax = MIN2(myMax, (int)fxInfo->fx_uprilim); // clamp - restrict 3005 } else { 3006 // No clue - punt 3007 if (ThreadPriorityVerbose) { 3008 tty->print_cr("Unknown scheduling class: %s ... \n", 3009 ClassInfo.pc_clname); 3010 } 3011 return EINVAL; // no clue, punt 3012 } 3013 3014 if (ThreadPriorityVerbose) { 3015 tty->print_cr("Thread priority Range: [%d..%d]\n", myMin, myMax); 3016 } 3017 3018 priocntl_enable = true; // Enable changing priorities 3019 return 0; 3020 } 3021 3022 #define IAPRI(x) ((iaparms_t *)((x).pc_clparms)) 3023 #define RTPRI(x) ((rtparms_t *)((x).pc_clparms)) 3024 #define TSPRI(x) ((tsparms_t *)((x).pc_clparms)) 3025 #define FXPRI(x) ((fxparms_t *)((x).pc_clparms)) 3026 3027 3028 // scale_to_lwp_priority 3029 // 3030 // Convert from the libthread "thr_setprio" scale to our current 3031 // lwp scheduling class scale. 3032 // 3033 static int scale_to_lwp_priority(int rMin, int rMax, int x) { 3034 int v; 3035 3036 if (x == 127) return rMax; // avoid round-down 3037 v = (((x*(rMax-rMin)))/128)+rMin; 3038 return v; 3039 } 3040 3041 3042 // set_lwp_class_and_priority 3043 int set_lwp_class_and_priority(int ThreadID, int lwpid, 3044 int newPrio, int new_class, bool scale) { 3045 int rslt; 3046 int Actual, Expected, prv; 3047 pcparms_t ParmInfo; // for GET-SET 3048 #ifdef ASSERT 3049 pcparms_t ReadBack; // for readback 3050 #endif 3051 3052 // Set priority via PC_GETPARMS, update, PC_SETPARMS 3053 // Query current values. 3054 // TODO: accelerate this by eliminating the PC_GETPARMS call. 3055 // Cache "pcparms_t" in global ParmCache. 3056 // TODO: elide set-to-same-value 3057 3058 // If something went wrong on init, don't change priorities. 3059 if (!priocntl_enable) { 3060 if (ThreadPriorityVerbose) { 3061 tty->print_cr("Trying to set priority but init failed, ignoring"); 3062 } 3063 return EINVAL; 3064 } 3065 3066 // If lwp hasn't started yet, just return 3067 // the _start routine will call us again. 3068 if (lwpid <= 0) { 3069 if (ThreadPriorityVerbose) { 3070 tty->print_cr("deferring the set_lwp_class_and_priority of thread " 3071 INTPTR_FORMAT " to %d, lwpid not set", 3072 ThreadID, newPrio); 3073 } 3074 return 0; 3075 } 3076 3077 if (ThreadPriorityVerbose) { 3078 tty->print_cr ("set_lwp_class_and_priority(" 3079 INTPTR_FORMAT "@" INTPTR_FORMAT " %d) ", 3080 ThreadID, lwpid, newPrio); 3081 } 3082 3083 memset(&ParmInfo, 0, sizeof(pcparms_t)); 3084 ParmInfo.pc_cid = PC_CLNULL; 3085 rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo); 3086 if (rslt < 0) return errno; 3087 3088 int cur_class = ParmInfo.pc_cid; 3089 ParmInfo.pc_cid = (id_t)new_class; 3090 3091 if (new_class == rtLimits.schedPolicy) { 3092 rtparms_t *rtInfo = (rtparms_t*)ParmInfo.pc_clparms; 3093 rtInfo->rt_pri = scale ? scale_to_lwp_priority(rtLimits.minPrio, 3094 rtLimits.maxPrio, newPrio) 3095 : newPrio; 3096 rtInfo->rt_tqsecs = RT_NOCHANGE; 3097 rtInfo->rt_tqnsecs = RT_NOCHANGE; 3098 if (ThreadPriorityVerbose) { 3099 tty->print_cr("RT: %d->%d\n", newPrio, rtInfo->rt_pri); 3100 } 3101 } else if (new_class == iaLimits.schedPolicy) { 3102 iaparms_t* iaInfo = (iaparms_t*)ParmInfo.pc_clparms; 3103 int maxClamped = MIN2(iaLimits.maxPrio, 3104 cur_class == new_class 3105 ? (int)iaInfo->ia_uprilim : iaLimits.maxPrio); 3106 iaInfo->ia_upri = scale ? scale_to_lwp_priority(iaLimits.minPrio, 3107 maxClamped, newPrio) 3108 : newPrio; 3109 iaInfo->ia_uprilim = cur_class == new_class 3110 ? IA_NOCHANGE : (pri_t)iaLimits.maxPrio; 3111 iaInfo->ia_mode = IA_NOCHANGE; 3112 if (ThreadPriorityVerbose) { 3113 tty->print_cr("IA: [%d...%d] %d->%d\n", 3114 iaLimits.minPrio, maxClamped, newPrio, iaInfo->ia_upri); 3115 } 3116 } else if (new_class == tsLimits.schedPolicy) { 3117 tsparms_t* tsInfo = (tsparms_t*)ParmInfo.pc_clparms; 3118 int maxClamped = MIN2(tsLimits.maxPrio, 3119 cur_class == new_class 3120 ? (int)tsInfo->ts_uprilim : tsLimits.maxPrio); 3121 tsInfo->ts_upri = scale ? scale_to_lwp_priority(tsLimits.minPrio, 3122 maxClamped, newPrio) 3123 : newPrio; 3124 tsInfo->ts_uprilim = cur_class == new_class 3125 ? TS_NOCHANGE : (pri_t)tsLimits.maxPrio; 3126 if (ThreadPriorityVerbose) { 3127 tty->print_cr("TS: [%d...%d] %d->%d\n", 3128 tsLimits.minPrio, maxClamped, newPrio, tsInfo->ts_upri); 3129 } 3130 } else if (new_class == fxLimits.schedPolicy) { 3131 fxparms_t* fxInfo = (fxparms_t*)ParmInfo.pc_clparms; 3132 int maxClamped = MIN2(fxLimits.maxPrio, 3133 cur_class == new_class 3134 ? (int)fxInfo->fx_uprilim : fxLimits.maxPrio); 3135 fxInfo->fx_upri = scale ? scale_to_lwp_priority(fxLimits.minPrio, 3136 maxClamped, newPrio) 3137 : newPrio; 3138 fxInfo->fx_uprilim = cur_class == new_class 3139 ? FX_NOCHANGE : (pri_t)fxLimits.maxPrio; 3140 fxInfo->fx_tqsecs = FX_NOCHANGE; 3141 fxInfo->fx_tqnsecs = FX_NOCHANGE; 3142 if (ThreadPriorityVerbose) { 3143 tty->print_cr("FX: [%d...%d] %d->%d\n", 3144 fxLimits.minPrio, maxClamped, newPrio, fxInfo->fx_upri); 3145 } 3146 } else { 3147 if (ThreadPriorityVerbose) { 3148 tty->print_cr("Unknown new scheduling class %d\n", new_class); 3149 } 3150 return EINVAL; // no clue, punt 3151 } 3152 3153 rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo); 3154 if (ThreadPriorityVerbose && rslt) { 3155 tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno); 3156 } 3157 if (rslt < 0) return errno; 3158 3159 #ifdef ASSERT 3160 // Sanity check: read back what we just attempted to set. 3161 // In theory it could have changed in the interim ... 3162 // 3163 // The priocntl system call is tricky. 3164 // Sometimes it'll validate the priority value argument and 3165 // return EINVAL if unhappy. At other times it fails silently. 3166 // Readbacks are prudent. 3167 3168 if (!ReadBackValidate) return 0; 3169 3170 memset(&ReadBack, 0, sizeof(pcparms_t)); 3171 ReadBack.pc_cid = PC_CLNULL; 3172 rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack); 3173 assert(rslt >= 0, "priocntl failed"); 3174 Actual = Expected = 0xBAD; 3175 assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match"); 3176 if (ParmInfo.pc_cid == rtLimits.schedPolicy) { 3177 Actual = RTPRI(ReadBack)->rt_pri; 3178 Expected = RTPRI(ParmInfo)->rt_pri; 3179 } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) { 3180 Actual = IAPRI(ReadBack)->ia_upri; 3181 Expected = IAPRI(ParmInfo)->ia_upri; 3182 } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) { 3183 Actual = TSPRI(ReadBack)->ts_upri; 3184 Expected = TSPRI(ParmInfo)->ts_upri; 3185 } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) { 3186 Actual = FXPRI(ReadBack)->fx_upri; 3187 Expected = FXPRI(ParmInfo)->fx_upri; 3188 } else { 3189 if (ThreadPriorityVerbose) { 3190 tty->print_cr("set_lwp_class_and_priority: unexpected class in readback: %d\n", 3191 ParmInfo.pc_cid); 3192 } 3193 } 3194 3195 if (Actual != Expected) { 3196 if (ThreadPriorityVerbose) { 3197 tty->print_cr ("set_lwp_class_and_priority(%d %d) Class=%d: actual=%d vs expected=%d\n", 3198 lwpid, newPrio, ReadBack.pc_cid, Actual, Expected); 3199 } 3200 } 3201 #endif 3202 3203 return 0; 3204 } 3205 3206 // Solaris only gives access to 128 real priorities at a time, 3207 // so we expand Java's ten to fill this range. This would be better 3208 // if we dynamically adjusted relative priorities. 3209 // 3210 // The ThreadPriorityPolicy option allows us to select 2 different 3211 // priority scales. 3212 // 3213 // ThreadPriorityPolicy=0 3214 // Since the Solaris' default priority is MaximumPriority, we do not 3215 // set a priority lower than Max unless a priority lower than 3216 // NormPriority is requested. 3217 // 3218 // ThreadPriorityPolicy=1 3219 // This mode causes the priority table to get filled with 3220 // linear values. NormPriority get's mapped to 50% of the 3221 // Maximum priority an so on. This will cause VM threads 3222 // to get unfair treatment against other Solaris processes 3223 // which do not explicitly alter their thread priorities. 3224 3225 int os::java_to_os_priority[CriticalPriority + 1] = { 3226 -99999, // 0 Entry should never be used 3227 3228 0, // 1 MinPriority 3229 32, // 2 3230 64, // 3 3231 3232 96, // 4 3233 127, // 5 NormPriority 3234 127, // 6 3235 3236 127, // 7 3237 127, // 8 3238 127, // 9 NearMaxPriority 3239 3240 127, // 10 MaxPriority 3241 3242 -criticalPrio // 11 CriticalPriority 3243 }; 3244 3245 OSReturn os::set_native_priority(Thread* thread, int newpri) { 3246 OSThread* osthread = thread->osthread(); 3247 3248 // Save requested priority in case the thread hasn't been started 3249 osthread->set_native_priority(newpri); 3250 3251 // Check for critical priority request 3252 bool fxcritical = false; 3253 if (newpri == -criticalPrio) { 3254 fxcritical = true; 3255 newpri = criticalPrio; 3256 } 3257 3258 assert(newpri >= MinimumPriority && newpri <= MaximumPriority, "bad priority mapping"); 3259 if (!UseThreadPriorities) return OS_OK; 3260 3261 int status = 0; 3262 3263 if (!fxcritical) { 3264 // Use thr_setprio only if we have a priority that thr_setprio understands 3265 status = thr_setprio(thread->osthread()->thread_id(), newpri); 3266 } 3267 3268 int lwp_status = 3269 set_lwp_class_and_priority(osthread->thread_id(), 3270 osthread->lwp_id(), 3271 newpri, 3272 fxcritical ? fxLimits.schedPolicy : myClass, 3273 !fxcritical); 3274 if (lwp_status != 0 && fxcritical) { 3275 // Try again, this time without changing the scheduling class 3276 newpri = java_MaxPriority_to_os_priority; 3277 lwp_status = set_lwp_class_and_priority(osthread->thread_id(), 3278 osthread->lwp_id(), 3279 newpri, myClass, false); 3280 } 3281 status |= lwp_status; 3282 return (status == 0) ? OS_OK : OS_ERR; 3283 } 3284 3285 3286 OSReturn os::get_native_priority(const Thread* const thread, 3287 int *priority_ptr) { 3288 int p; 3289 if (!UseThreadPriorities) { 3290 *priority_ptr = NormalPriority; 3291 return OS_OK; 3292 } 3293 int status = thr_getprio(thread->osthread()->thread_id(), &p); 3294 if (status != 0) { 3295 return OS_ERR; 3296 } 3297 *priority_ptr = p; 3298 return OS_OK; 3299 } 3300 3301 //////////////////////////////////////////////////////////////////////////////// 3302 // suspend/resume support 3303 3304 // The low-level signal-based suspend/resume support is a remnant from the 3305 // old VM-suspension that used to be for java-suspension, safepoints etc, 3306 // within hotspot. Currently used by JFR's OSThreadSampler 3307 // 3308 // The remaining code is greatly simplified from the more general suspension 3309 // code that used to be used. 3310 // 3311 // The protocol is quite simple: 3312 // - suspend: 3313 // - sends a signal to the target thread 3314 // - polls the suspend state of the osthread using a yield loop 3315 // - target thread signal handler (SR_handler) sets suspend state 3316 // and blocks in sigsuspend until continued 3317 // - resume: 3318 // - sets target osthread state to continue 3319 // - sends signal to end the sigsuspend loop in the SR_handler 3320 // 3321 // Note that the SR_lock plays no role in this suspend/resume protocol, 3322 // but is checked for NULL in SR_handler as a thread termination indicator. 3323 // The SR_lock is, however, used by JavaThread::java_suspend()/java_resume() APIs. 3324 // 3325 // Note that resume_clear_context() and suspend_save_context() are needed 3326 // by SR_handler(), so that fetch_frame_from_ucontext() works, 3327 // which in part is used by: 3328 // - Forte Analyzer: AsyncGetCallTrace() 3329 // - StackBanging: get_frame_at_stack_banging_point() 3330 // - JFR: get_topframe()-->....-->get_valid_uc_in_signal_handler() 3331 3332 static void resume_clear_context(OSThread *osthread) { 3333 osthread->set_ucontext(NULL); 3334 } 3335 3336 static void suspend_save_context(OSThread *osthread, ucontext_t* context) { 3337 osthread->set_ucontext(context); 3338 } 3339 3340 static PosixSemaphore sr_semaphore; 3341 3342 void os::Solaris::SR_handler(Thread* thread, ucontext_t* context) { 3343 // Save and restore errno to avoid confusing native code with EINTR 3344 // after sigsuspend. 3345 int old_errno = errno; 3346 3347 OSThread* osthread = thread->osthread(); 3348 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); 3349 3350 os::SuspendResume::State current = osthread->sr.state(); 3351 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { 3352 suspend_save_context(osthread, context); 3353 3354 // attempt to switch the state, we assume we had a SUSPEND_REQUEST 3355 os::SuspendResume::State state = osthread->sr.suspended(); 3356 if (state == os::SuspendResume::SR_SUSPENDED) { 3357 sigset_t suspend_set; // signals for sigsuspend() 3358 3359 // get current set of blocked signals and unblock resume signal 3360 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); 3361 sigdelset(&suspend_set, ASYNC_SIGNAL); 3362 3363 sr_semaphore.signal(); 3364 // wait here until we are resumed 3365 while (1) { 3366 sigsuspend(&suspend_set); 3367 3368 os::SuspendResume::State result = osthread->sr.running(); 3369 if (result == os::SuspendResume::SR_RUNNING) { 3370 sr_semaphore.signal(); 3371 break; 3372 } 3373 } 3374 3375 } else if (state == os::SuspendResume::SR_RUNNING) { 3376 // request was cancelled, continue 3377 } else { 3378 ShouldNotReachHere(); 3379 } 3380 3381 resume_clear_context(osthread); 3382 } else if (current == os::SuspendResume::SR_RUNNING) { 3383 // request was cancelled, continue 3384 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { 3385 // ignore 3386 } else { 3387 // ignore 3388 } 3389 3390 errno = old_errno; 3391 } 3392 3393 void os::print_statistics() { 3394 } 3395 3396 bool os::message_box(const char* title, const char* message) { 3397 int i; 3398 fdStream err(defaultStream::error_fd()); 3399 for (i = 0; i < 78; i++) err.print_raw("="); 3400 err.cr(); 3401 err.print_raw_cr(title); 3402 for (i = 0; i < 78; i++) err.print_raw("-"); 3403 err.cr(); 3404 err.print_raw_cr(message); 3405 for (i = 0; i < 78; i++) err.print_raw("="); 3406 err.cr(); 3407 3408 char buf[16]; 3409 // Prevent process from exiting upon "read error" without consuming all CPU 3410 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } 3411 3412 return buf[0] == 'y' || buf[0] == 'Y'; 3413 } 3414 3415 static int sr_notify(OSThread* osthread) { 3416 int status = thr_kill(osthread->thread_id(), ASYNC_SIGNAL); 3417 assert_status(status == 0, status, "thr_kill"); 3418 return status; 3419 } 3420 3421 // "Randomly" selected value for how long we want to spin 3422 // before bailing out on suspending a thread, also how often 3423 // we send a signal to a thread we want to resume 3424 static const int RANDOMLY_LARGE_INTEGER = 1000000; 3425 static const int RANDOMLY_LARGE_INTEGER2 = 100; 3426 3427 static bool do_suspend(OSThread* osthread) { 3428 assert(osthread->sr.is_running(), "thread should be running"); 3429 assert(!sr_semaphore.trywait(), "semaphore has invalid state"); 3430 3431 // mark as suspended and send signal 3432 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { 3433 // failed to switch, state wasn't running? 3434 ShouldNotReachHere(); 3435 return false; 3436 } 3437 3438 if (sr_notify(osthread) != 0) { 3439 ShouldNotReachHere(); 3440 } 3441 3442 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED 3443 while (true) { 3444 if (sr_semaphore.timedwait(2000)) { 3445 break; 3446 } else { 3447 // timeout 3448 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); 3449 if (cancelled == os::SuspendResume::SR_RUNNING) { 3450 return false; 3451 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { 3452 // make sure that we consume the signal on the semaphore as well 3453 sr_semaphore.wait(); 3454 break; 3455 } else { 3456 ShouldNotReachHere(); 3457 return false; 3458 } 3459 } 3460 } 3461 3462 guarantee(osthread->sr.is_suspended(), "Must be suspended"); 3463 return true; 3464 } 3465 3466 static void do_resume(OSThread* osthread) { 3467 assert(osthread->sr.is_suspended(), "thread should be suspended"); 3468 assert(!sr_semaphore.trywait(), "invalid semaphore state"); 3469 3470 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { 3471 // failed to switch to WAKEUP_REQUEST 3472 ShouldNotReachHere(); 3473 return; 3474 } 3475 3476 while (true) { 3477 if (sr_notify(osthread) == 0) { 3478 if (sr_semaphore.timedwait(2)) { 3479 if (osthread->sr.is_running()) { 3480 return; 3481 } 3482 } 3483 } else { 3484 ShouldNotReachHere(); 3485 } 3486 } 3487 3488 guarantee(osthread->sr.is_running(), "Must be running!"); 3489 } 3490 3491 void os::SuspendedThreadTask::internal_do_task() { 3492 if (do_suspend(_thread->osthread())) { 3493 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); 3494 do_task(context); 3495 do_resume(_thread->osthread()); 3496 } 3497 } 3498 3499 // This does not do anything on Solaris. This is basically a hook for being 3500 // able to use structured exception handling (thread-local exception filters) on, e.g., Win32. 3501 void os::os_exception_wrapper(java_call_t f, JavaValue* value, 3502 const methodHandle& method, JavaCallArguments* args, 3503 Thread* thread) { 3504 f(value, method, args, thread); 3505 } 3506 3507 // This routine may be used by user applications as a "hook" to catch signals. 3508 // The user-defined signal handler must pass unrecognized signals to this 3509 // routine, and if it returns true (non-zero), then the signal handler must 3510 // return immediately. If the flag "abort_if_unrecognized" is true, then this 3511 // routine will never retun false (zero), but instead will execute a VM panic 3512 // routine kill the process. 3513 // 3514 // If this routine returns false, it is OK to call it again. This allows 3515 // the user-defined signal handler to perform checks either before or after 3516 // the VM performs its own checks. Naturally, the user code would be making 3517 // a serious error if it tried to handle an exception (such as a null check 3518 // or breakpoint) that the VM was generating for its own correct operation. 3519 // 3520 // This routine may recognize any of the following kinds of signals: 3521 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, BREAK_SIGNAL, SIGPIPE, SIGXFSZ, 3522 // ASYNC_SIGNAL. 3523 // It should be consulted by handlers for any of those signals. 3524 // 3525 // The caller of this routine must pass in the three arguments supplied 3526 // to the function referred to in the "sa_sigaction" (not the "sa_handler") 3527 // field of the structure passed to sigaction(). This routine assumes that 3528 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. 3529 // 3530 // Note that the VM will print warnings if it detects conflicting signal 3531 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". 3532 // 3533 extern "C" JNIEXPORT int JVM_handle_solaris_signal(int signo, 3534 siginfo_t* siginfo, 3535 void* ucontext, 3536 int abort_if_unrecognized); 3537 3538 3539 void signalHandler(int sig, siginfo_t* info, void* ucVoid) { 3540 int orig_errno = errno; // Preserve errno value over signal handler. 3541 JVM_handle_solaris_signal(sig, info, ucVoid, true); 3542 errno = orig_errno; 3543 } 3544 3545 // This boolean allows users to forward their own non-matching signals 3546 // to JVM_handle_solaris_signal, harmlessly. 3547 bool os::Solaris::signal_handlers_are_installed = false; 3548 3549 // For signal-chaining 3550 bool os::Solaris::libjsig_is_loaded = false; 3551 typedef struct sigaction *(*get_signal_t)(int); 3552 get_signal_t os::Solaris::get_signal_action = NULL; 3553 3554 struct sigaction* os::Solaris::get_chained_signal_action(int sig) { 3555 struct sigaction *actp = NULL; 3556 3557 if ((libjsig_is_loaded) && (sig <= Maxsignum)) { 3558 // Retrieve the old signal handler from libjsig 3559 actp = (*get_signal_action)(sig); 3560 } 3561 if (actp == NULL) { 3562 // Retrieve the preinstalled signal handler from jvm 3563 actp = get_preinstalled_handler(sig); 3564 } 3565 3566 return actp; 3567 } 3568 3569 static bool call_chained_handler(struct sigaction *actp, int sig, 3570 siginfo_t *siginfo, void *context) { 3571 // Call the old signal handler 3572 if (actp->sa_handler == SIG_DFL) { 3573 // It's more reasonable to let jvm treat it as an unexpected exception 3574 // instead of taking the default action. 3575 return false; 3576 } else if (actp->sa_handler != SIG_IGN) { 3577 if ((actp->sa_flags & SA_NODEFER) == 0) { 3578 // automaticlly block the signal 3579 sigaddset(&(actp->sa_mask), sig); 3580 } 3581 3582 sa_handler_t hand; 3583 sa_sigaction_t sa; 3584 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; 3585 // retrieve the chained handler 3586 if (siginfo_flag_set) { 3587 sa = actp->sa_sigaction; 3588 } else { 3589 hand = actp->sa_handler; 3590 } 3591 3592 if ((actp->sa_flags & SA_RESETHAND) != 0) { 3593 actp->sa_handler = SIG_DFL; 3594 } 3595 3596 // try to honor the signal mask 3597 sigset_t oset; 3598 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); 3599 3600 // call into the chained handler 3601 if (siginfo_flag_set) { 3602 (*sa)(sig, siginfo, context); 3603 } else { 3604 (*hand)(sig); 3605 } 3606 3607 // restore the signal mask 3608 pthread_sigmask(SIG_SETMASK, &oset, 0); 3609 } 3610 // Tell jvm's signal handler the signal is taken care of. 3611 return true; 3612 } 3613 3614 bool os::Solaris::chained_handler(int sig, siginfo_t* siginfo, void* context) { 3615 bool chained = false; 3616 // signal-chaining 3617 if (UseSignalChaining) { 3618 struct sigaction *actp = get_chained_signal_action(sig); 3619 if (actp != NULL) { 3620 chained = call_chained_handler(actp, sig, siginfo, context); 3621 } 3622 } 3623 return chained; 3624 } 3625 3626 struct sigaction* os::Solaris::get_preinstalled_handler(int sig) { 3627 assert((chainedsigactions != (struct sigaction *)NULL) && 3628 (preinstalled_sigs != (int *)NULL), "signals not yet initialized"); 3629 if (preinstalled_sigs[sig] != 0) { 3630 return &chainedsigactions[sig]; 3631 } 3632 return NULL; 3633 } 3634 3635 void os::Solaris::save_preinstalled_handler(int sig, 3636 struct sigaction& oldAct) { 3637 assert(sig > 0 && sig <= Maxsignum, "vm signal out of expected range"); 3638 assert((chainedsigactions != (struct sigaction *)NULL) && 3639 (preinstalled_sigs != (int *)NULL), "signals not yet initialized"); 3640 chainedsigactions[sig] = oldAct; 3641 preinstalled_sigs[sig] = 1; 3642 } 3643 3644 void os::Solaris::set_signal_handler(int sig, bool set_installed, 3645 bool oktochain) { 3646 // Check for overwrite. 3647 struct sigaction oldAct; 3648 sigaction(sig, (struct sigaction*)NULL, &oldAct); 3649 void* oldhand = 3650 oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3651 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3652 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && 3653 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && 3654 oldhand != CAST_FROM_FN_PTR(void*, signalHandler)) { 3655 if (AllowUserSignalHandlers || !set_installed) { 3656 // Do not overwrite; user takes responsibility to forward to us. 3657 return; 3658 } else if (UseSignalChaining) { 3659 if (oktochain) { 3660 // save the old handler in jvm 3661 save_preinstalled_handler(sig, oldAct); 3662 } else { 3663 vm_exit_during_initialization("Signal chaining not allowed for VM interrupt signal."); 3664 } 3665 // libjsig also interposes the sigaction() call below and saves the 3666 // old sigaction on it own. 3667 } else { 3668 fatal("Encountered unexpected pre-existing sigaction handler " 3669 "%#lx for signal %d.", (long)oldhand, sig); 3670 } 3671 } 3672 3673 struct sigaction sigAct; 3674 sigfillset(&(sigAct.sa_mask)); 3675 sigAct.sa_handler = SIG_DFL; 3676 3677 sigAct.sa_sigaction = signalHandler; 3678 // Handle SIGSEGV on alternate signal stack if 3679 // not using stack banging 3680 if (!UseStackBanging && sig == SIGSEGV) { 3681 sigAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK; 3682 } else { 3683 sigAct.sa_flags = SA_SIGINFO | SA_RESTART; 3684 } 3685 os::Solaris::set_our_sigflags(sig, sigAct.sa_flags); 3686 3687 sigaction(sig, &sigAct, &oldAct); 3688 3689 void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3690 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3691 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); 3692 } 3693 3694 3695 #define DO_SIGNAL_CHECK(sig) \ 3696 do { \ 3697 if (!sigismember(&check_signal_done, sig)) { \ 3698 os::Solaris::check_signal_handler(sig); \ 3699 } \ 3700 } while (0) 3701 3702 // This method is a periodic task to check for misbehaving JNI applications 3703 // under CheckJNI, we can add any periodic checks here 3704 3705 void os::run_periodic_checks() { 3706 // A big source of grief is hijacking virt. addr 0x0 on Solaris, 3707 // thereby preventing a NULL checks. 3708 if (!check_addr0_done) check_addr0_done = check_addr0(tty); 3709 3710 if (check_signals == false) return; 3711 3712 // SEGV and BUS if overridden could potentially prevent 3713 // generation of hs*.log in the event of a crash, debugging 3714 // such a case can be very challenging, so we absolutely 3715 // check for the following for a good measure: 3716 DO_SIGNAL_CHECK(SIGSEGV); 3717 DO_SIGNAL_CHECK(SIGILL); 3718 DO_SIGNAL_CHECK(SIGFPE); 3719 DO_SIGNAL_CHECK(SIGBUS); 3720 DO_SIGNAL_CHECK(SIGPIPE); 3721 DO_SIGNAL_CHECK(SIGXFSZ); 3722 DO_SIGNAL_CHECK(ASYNC_SIGNAL); 3723 3724 // ReduceSignalUsage allows the user to override these handlers 3725 // see comments at the very top and jvm_solaris.h 3726 if (!ReduceSignalUsage) { 3727 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); 3728 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); 3729 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); 3730 DO_SIGNAL_CHECK(BREAK_SIGNAL); 3731 } 3732 } 3733 3734 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); 3735 3736 static os_sigaction_t os_sigaction = NULL; 3737 3738 void os::Solaris::check_signal_handler(int sig) { 3739 char buf[O_BUFLEN]; 3740 address jvmHandler = NULL; 3741 3742 struct sigaction act; 3743 if (os_sigaction == NULL) { 3744 // only trust the default sigaction, in case it has been interposed 3745 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); 3746 if (os_sigaction == NULL) return; 3747 } 3748 3749 os_sigaction(sig, (struct sigaction*)NULL, &act); 3750 3751 address thisHandler = (act.sa_flags & SA_SIGINFO) 3752 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) 3753 : CAST_FROM_FN_PTR(address, act.sa_handler); 3754 3755 3756 switch (sig) { 3757 case SIGSEGV: 3758 case SIGBUS: 3759 case SIGFPE: 3760 case SIGPIPE: 3761 case SIGXFSZ: 3762 case SIGILL: 3763 case ASYNC_SIGNAL: 3764 jvmHandler = CAST_FROM_FN_PTR(address, signalHandler); 3765 break; 3766 3767 case SHUTDOWN1_SIGNAL: 3768 case SHUTDOWN2_SIGNAL: 3769 case SHUTDOWN3_SIGNAL: 3770 case BREAK_SIGNAL: 3771 jvmHandler = (address)user_handler(); 3772 break; 3773 3774 default: 3775 return; 3776 } 3777 3778 if (thisHandler != jvmHandler) { 3779 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); 3780 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); 3781 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); 3782 // No need to check this sig any longer 3783 sigaddset(&check_signal_done, sig); 3784 // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN 3785 if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) { 3786 tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell", 3787 exception_name(sig, buf, O_BUFLEN)); 3788 } 3789 } else if(os::Solaris::get_our_sigflags(sig) != 0 && act.sa_flags != os::Solaris::get_our_sigflags(sig)) { 3790 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); 3791 tty->print("expected:"); 3792 os::Posix::print_sa_flags(tty, os::Solaris::get_our_sigflags(sig)); 3793 tty->cr(); 3794 tty->print(" found:"); 3795 os::Posix::print_sa_flags(tty, act.sa_flags); 3796 tty->cr(); 3797 // No need to check this sig any longer 3798 sigaddset(&check_signal_done, sig); 3799 } 3800 3801 // Print all the signal handler state 3802 if (sigismember(&check_signal_done, sig)) { 3803 print_signal_handlers(tty, buf, O_BUFLEN); 3804 } 3805 3806 } 3807 3808 void os::Solaris::install_signal_handlers() { 3809 signal_handlers_are_installed = true; 3810 3811 // signal-chaining 3812 typedef void (*signal_setting_t)(); 3813 signal_setting_t begin_signal_setting = NULL; 3814 signal_setting_t end_signal_setting = NULL; 3815 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 3816 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); 3817 if (begin_signal_setting != NULL) { 3818 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 3819 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); 3820 get_signal_action = CAST_TO_FN_PTR(get_signal_t, 3821 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); 3822 libjsig_is_loaded = true; 3823 assert(UseSignalChaining, "should enable signal-chaining"); 3824 } 3825 if (libjsig_is_loaded) { 3826 // Tell libjsig jvm is setting signal handlers 3827 (*begin_signal_setting)(); 3828 } 3829 3830 set_signal_handler(SIGSEGV, true, true); 3831 set_signal_handler(SIGPIPE, true, true); 3832 set_signal_handler(SIGXFSZ, true, true); 3833 set_signal_handler(SIGBUS, true, true); 3834 set_signal_handler(SIGILL, true, true); 3835 set_signal_handler(SIGFPE, true, true); 3836 set_signal_handler(ASYNC_SIGNAL, true, true); 3837 3838 if (libjsig_is_loaded) { 3839 // Tell libjsig jvm finishes setting signal handlers 3840 (*end_signal_setting)(); 3841 } 3842 3843 // We don't activate signal checker if libjsig is in place, we trust ourselves 3844 // and if UserSignalHandler is installed all bets are off. 3845 // Log that signal checking is off only if -verbose:jni is specified. 3846 if (CheckJNICalls) { 3847 if (libjsig_is_loaded) { 3848 if (PrintJNIResolving) { 3849 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); 3850 } 3851 check_signals = false; 3852 } 3853 if (AllowUserSignalHandlers) { 3854 if (PrintJNIResolving) { 3855 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); 3856 } 3857 check_signals = false; 3858 } 3859 } 3860 } 3861 3862 3863 void report_error(const char* file_name, int line_no, const char* title, 3864 const char* format, ...); 3865 3866 // (Static) wrappers for the liblgrp API 3867 os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home; 3868 os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init; 3869 os::Solaris::lgrp_fini_func_t os::Solaris::_lgrp_fini; 3870 os::Solaris::lgrp_root_func_t os::Solaris::_lgrp_root; 3871 os::Solaris::lgrp_children_func_t os::Solaris::_lgrp_children; 3872 os::Solaris::lgrp_resources_func_t os::Solaris::_lgrp_resources; 3873 os::Solaris::lgrp_nlgrps_func_t os::Solaris::_lgrp_nlgrps; 3874 os::Solaris::lgrp_cookie_stale_func_t os::Solaris::_lgrp_cookie_stale; 3875 os::Solaris::lgrp_cookie_t os::Solaris::_lgrp_cookie = 0; 3876 3877 static address resolve_symbol_lazy(const char* name) { 3878 address addr = (address) dlsym(RTLD_DEFAULT, name); 3879 if (addr == NULL) { 3880 // RTLD_DEFAULT was not defined on some early versions of 2.5.1 3881 addr = (address) dlsym(RTLD_NEXT, name); 3882 } 3883 return addr; 3884 } 3885 3886 static address resolve_symbol(const char* name) { 3887 address addr = resolve_symbol_lazy(name); 3888 if (addr == NULL) { 3889 fatal(dlerror()); 3890 } 3891 return addr; 3892 } 3893 3894 void os::Solaris::libthread_init() { 3895 address func = (address)dlsym(RTLD_DEFAULT, "_thr_suspend_allmutators"); 3896 3897 lwp_priocntl_init(); 3898 3899 // RTLD_DEFAULT was not defined on some early versions of 5.5.1 3900 if (func == NULL) { 3901 func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators"); 3902 // Guarantee that this VM is running on an new enough OS (5.6 or 3903 // later) that it will have a new enough libthread.so. 3904 guarantee(func != NULL, "libthread.so is too old."); 3905 } 3906 3907 int size; 3908 void (*handler_info_func)(address *, int *); 3909 handler_info_func = CAST_TO_FN_PTR(void (*)(address *, int *), resolve_symbol("thr_sighndlrinfo")); 3910 handler_info_func(&handler_start, &size); 3911 handler_end = handler_start + size; 3912 } 3913 3914 3915 int_fnP_mutex_tP os::Solaris::_mutex_lock; 3916 int_fnP_mutex_tP os::Solaris::_mutex_trylock; 3917 int_fnP_mutex_tP os::Solaris::_mutex_unlock; 3918 int_fnP_mutex_tP_i_vP os::Solaris::_mutex_init; 3919 int_fnP_mutex_tP os::Solaris::_mutex_destroy; 3920 int os::Solaris::_mutex_scope = USYNC_THREAD; 3921 3922 int_fnP_cond_tP_mutex_tP_timestruc_tP os::Solaris::_cond_timedwait; 3923 int_fnP_cond_tP_mutex_tP os::Solaris::_cond_wait; 3924 int_fnP_cond_tP os::Solaris::_cond_signal; 3925 int_fnP_cond_tP os::Solaris::_cond_broadcast; 3926 int_fnP_cond_tP_i_vP os::Solaris::_cond_init; 3927 int_fnP_cond_tP os::Solaris::_cond_destroy; 3928 int os::Solaris::_cond_scope = USYNC_THREAD; 3929 bool os::Solaris::_synchronization_initialized; 3930 3931 void os::Solaris::synchronization_init() { 3932 if (UseLWPSynchronization) { 3933 os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock"))); 3934 os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock"))); 3935 os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock"))); 3936 os::Solaris::set_mutex_init(lwp_mutex_init); 3937 os::Solaris::set_mutex_destroy(lwp_mutex_destroy); 3938 os::Solaris::set_mutex_scope(USYNC_THREAD); 3939 3940 os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("_lwp_cond_timedwait"))); 3941 os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("_lwp_cond_wait"))); 3942 os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_signal"))); 3943 os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_broadcast"))); 3944 os::Solaris::set_cond_init(lwp_cond_init); 3945 os::Solaris::set_cond_destroy(lwp_cond_destroy); 3946 os::Solaris::set_cond_scope(USYNC_THREAD); 3947 } else { 3948 os::Solaris::set_mutex_scope(USYNC_THREAD); 3949 os::Solaris::set_cond_scope(USYNC_THREAD); 3950 3951 if (UsePthreads) { 3952 os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock"))); 3953 os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock"))); 3954 os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock"))); 3955 os::Solaris::set_mutex_init(pthread_mutex_default_init); 3956 os::Solaris::set_mutex_destroy(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_destroy"))); 3957 3958 os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("pthread_cond_timedwait"))); 3959 os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("pthread_cond_wait"))); 3960 os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_signal"))); 3961 os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_broadcast"))); 3962 os::Solaris::set_cond_init(pthread_cond_default_init); 3963 os::Solaris::set_cond_destroy(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_destroy"))); 3964 } else { 3965 os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_lock"))); 3966 os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_trylock"))); 3967 os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_unlock"))); 3968 os::Solaris::set_mutex_init(::mutex_init); 3969 os::Solaris::set_mutex_destroy(::mutex_destroy); 3970 3971 os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("cond_timedwait"))); 3972 os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("cond_wait"))); 3973 os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_signal"))); 3974 os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_broadcast"))); 3975 os::Solaris::set_cond_init(::cond_init); 3976 os::Solaris::set_cond_destroy(::cond_destroy); 3977 } 3978 } 3979 _synchronization_initialized = true; 3980 } 3981 3982 bool os::Solaris::liblgrp_init() { 3983 void *handle = dlopen("liblgrp.so.1", RTLD_LAZY); 3984 if (handle != NULL) { 3985 os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home"))); 3986 os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init"))); 3987 os::Solaris::set_lgrp_fini(CAST_TO_FN_PTR(lgrp_fini_func_t, dlsym(handle, "lgrp_fini"))); 3988 os::Solaris::set_lgrp_root(CAST_TO_FN_PTR(lgrp_root_func_t, dlsym(handle, "lgrp_root"))); 3989 os::Solaris::set_lgrp_children(CAST_TO_FN_PTR(lgrp_children_func_t, dlsym(handle, "lgrp_children"))); 3990 os::Solaris::set_lgrp_resources(CAST_TO_FN_PTR(lgrp_resources_func_t, dlsym(handle, "lgrp_resources"))); 3991 os::Solaris::set_lgrp_nlgrps(CAST_TO_FN_PTR(lgrp_nlgrps_func_t, dlsym(handle, "lgrp_nlgrps"))); 3992 os::Solaris::set_lgrp_cookie_stale(CAST_TO_FN_PTR(lgrp_cookie_stale_func_t, 3993 dlsym(handle, "lgrp_cookie_stale"))); 3994 3995 lgrp_cookie_t c = lgrp_init(LGRP_VIEW_CALLER); 3996 set_lgrp_cookie(c); 3997 return true; 3998 } 3999 return false; 4000 } 4001 4002 // int pset_getloadavg(psetid_t pset, double loadavg[], int nelem); 4003 typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem); 4004 static pset_getloadavg_type pset_getloadavg_ptr = NULL; 4005 4006 void init_pset_getloadavg_ptr(void) { 4007 pset_getloadavg_ptr = 4008 (pset_getloadavg_type)dlsym(RTLD_DEFAULT, "pset_getloadavg"); 4009 if (pset_getloadavg_ptr == NULL) { 4010 log_warning(os)("pset_getloadavg function not found"); 4011 } 4012 } 4013 4014 int os::Solaris::_dev_zero_fd = -1; 4015 4016 // this is called _before_ the global arguments have been parsed 4017 void os::init(void) { 4018 _initial_pid = getpid(); 4019 4020 max_hrtime = first_hrtime = gethrtime(); 4021 4022 init_random(1234567); 4023 4024 page_size = sysconf(_SC_PAGESIZE); 4025 if (page_size == -1) { 4026 fatal("os_solaris.cpp: os::init: sysconf failed (%s)", os::strerror(errno)); 4027 } 4028 init_page_sizes((size_t) page_size); 4029 4030 Solaris::initialize_system_info(); 4031 4032 int fd = ::open("/dev/zero", O_RDWR); 4033 if (fd < 0) { 4034 fatal("os::init: cannot open /dev/zero (%s)", os::strerror(errno)); 4035 } else { 4036 Solaris::set_dev_zero_fd(fd); 4037 4038 // Close on exec, child won't inherit. 4039 fcntl(fd, F_SETFD, FD_CLOEXEC); 4040 } 4041 4042 clock_tics_per_sec = CLK_TCK; 4043 4044 // check if dladdr1() exists; dladdr1 can provide more information than 4045 // dladdr for os::dll_address_to_function_name. It comes with SunOS 5.9 4046 // and is available on linker patches for 5.7 and 5.8. 4047 // libdl.so must have been loaded, this call is just an entry lookup 4048 void * hdl = dlopen("libdl.so", RTLD_NOW); 4049 if (hdl) { 4050 dladdr1_func = CAST_TO_FN_PTR(dladdr1_func_type, dlsym(hdl, "dladdr1")); 4051 } 4052 4053 // main_thread points to the thread that created/loaded the JVM. 4054 main_thread = thr_self(); 4055 4056 // dynamic lookup of functions that may not be available in our lowest 4057 // supported Solaris release 4058 void * handle = dlopen("libc.so.1", RTLD_LAZY); 4059 if (handle != NULL) { 4060 Solaris::_pthread_setname_np = // from 11.3 4061 (Solaris::pthread_setname_np_func_t)dlsym(handle, "pthread_setname_np"); 4062 } 4063 4064 // Shared Posix initialization 4065 os::Posix::init(); 4066 } 4067 4068 // To install functions for atexit system call 4069 extern "C" { 4070 static void perfMemory_exit_helper() { 4071 perfMemory_exit(); 4072 } 4073 } 4074 4075 // this is called _after_ the global arguments have been parsed 4076 jint os::init_2(void) { 4077 // try to enable extended file IO ASAP, see 6431278 4078 os::Solaris::try_enable_extended_io(); 4079 4080 // Check and sets minimum stack sizes against command line options 4081 if (Posix::set_minimum_stack_sizes() == JNI_ERR) { 4082 return JNI_ERR; 4083 } 4084 4085 Solaris::libthread_init(); 4086 4087 if (UseNUMA) { 4088 if (!Solaris::liblgrp_init()) { 4089 UseNUMA = false; 4090 } else { 4091 size_t lgrp_limit = os::numa_get_groups_num(); 4092 int *lgrp_ids = NEW_C_HEAP_ARRAY(int, lgrp_limit, mtInternal); 4093 size_t lgrp_num = os::numa_get_leaf_groups(lgrp_ids, lgrp_limit); 4094 FREE_C_HEAP_ARRAY(int, lgrp_ids); 4095 if (lgrp_num < 2) { 4096 // There's only one locality group, disable NUMA. 4097 UseNUMA = false; 4098 } 4099 } 4100 if (!UseNUMA && ForceNUMA) { 4101 UseNUMA = true; 4102 } 4103 } 4104 4105 Solaris::signal_sets_init(); 4106 Solaris::init_signal_mem(); 4107 Solaris::install_signal_handlers(); 4108 // Initialize data for jdk.internal.misc.Signal 4109 if (!ReduceSignalUsage) { 4110 jdk_misc_signal_init(); 4111 } 4112 4113 // initialize synchronization primitives to use either thread or 4114 // lwp synchronization (controlled by UseLWPSynchronization) 4115 Solaris::synchronization_init(); 4116 DEBUG_ONLY(os::set_mutex_init_done();) 4117 4118 if (MaxFDLimit) { 4119 // set the number of file descriptors to max. print out error 4120 // if getrlimit/setrlimit fails but continue regardless. 4121 struct rlimit nbr_files; 4122 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); 4123 if (status != 0) { 4124 log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno)); 4125 } else { 4126 nbr_files.rlim_cur = nbr_files.rlim_max; 4127 status = setrlimit(RLIMIT_NOFILE, &nbr_files); 4128 if (status != 0) { 4129 log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno)); 4130 } 4131 } 4132 } 4133 4134 // Calculate theoretical max. size of Threads to guard gainst 4135 // artifical out-of-memory situations, where all available address- 4136 // space has been reserved by thread stacks. Default stack size is 1Mb. 4137 size_t pre_thread_stack_size = (JavaThread::stack_size_at_create()) ? 4138 JavaThread::stack_size_at_create() : (1*K*K); 4139 assert(pre_thread_stack_size != 0, "Must have a stack"); 4140 // Solaris has a maximum of 4Gb of user programs. Calculate the thread limit when 4141 // we should start doing Virtual Memory banging. Currently when the threads will 4142 // have used all but 200Mb of space. 4143 size_t max_address_space = ((unsigned int)4 * K * K * K) - (200 * K * K); 4144 Solaris::_os_thread_limit = max_address_space / pre_thread_stack_size; 4145 4146 // at-exit methods are called in the reverse order of their registration. 4147 // In Solaris 7 and earlier, atexit functions are called on return from 4148 // main or as a result of a call to exit(3C). There can be only 32 of 4149 // these functions registered and atexit() does not set errno. In Solaris 4150 // 8 and later, there is no limit to the number of functions registered 4151 // and atexit() sets errno. In addition, in Solaris 8 and later, atexit 4152 // functions are called upon dlclose(3DL) in addition to return from main 4153 // and exit(3C). 4154 4155 if (PerfAllowAtExitRegistration) { 4156 // only register atexit functions if PerfAllowAtExitRegistration is set. 4157 // atexit functions can be delayed until process exit time, which 4158 // can be problematic for embedded VM situations. Embedded VMs should 4159 // call DestroyJavaVM() to assure that VM resources are released. 4160 4161 // note: perfMemory_exit_helper atexit function may be removed in 4162 // the future if the appropriate cleanup code can be added to the 4163 // VM_Exit VMOperation's doit method. 4164 if (atexit(perfMemory_exit_helper) != 0) { 4165 warning("os::init2 atexit(perfMemory_exit_helper) failed"); 4166 } 4167 } 4168 4169 // Init pset_loadavg function pointer 4170 init_pset_getloadavg_ptr(); 4171 4172 // Shared Posix initialization 4173 os::Posix::init_2(); 4174 4175 return JNI_OK; 4176 } 4177 4178 // Mark the polling page as unreadable 4179 void os::make_polling_page_unreadable(void) { 4180 Events::log(NULL, "Protecting polling page " INTPTR_FORMAT " with PROT_NONE", p2i(_polling_page)); 4181 if (mprotect((char *)_polling_page, page_size, PROT_NONE) != 0) { 4182 fatal("Could not disable polling page"); 4183 } 4184 } 4185 4186 // Mark the polling page as readable 4187 void os::make_polling_page_readable(void) { 4188 Events::log(NULL, "Protecting polling page " INTPTR_FORMAT " with PROT_READ", p2i(_polling_page)); 4189 if (mprotect((char *)_polling_page, page_size, PROT_READ) != 0) { 4190 fatal("Could not enable polling page"); 4191 } 4192 } 4193 4194 // Is a (classpath) directory empty? 4195 bool os::dir_is_empty(const char* path) { 4196 DIR *dir = NULL; 4197 struct dirent *ptr; 4198 4199 dir = opendir(path); 4200 if (dir == NULL) return true; 4201 4202 // Scan the directory 4203 bool result = true; 4204 while (result && (ptr = readdir(dir)) != NULL) { 4205 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { 4206 result = false; 4207 } 4208 } 4209 closedir(dir); 4210 return result; 4211 } 4212 4213 // This code originates from JDK's sysOpen and open64_w 4214 // from src/solaris/hpi/src/system_md.c 4215 4216 int os::open(const char *path, int oflag, int mode) { 4217 if (strlen(path) > MAX_PATH - 1) { 4218 errno = ENAMETOOLONG; 4219 return -1; 4220 } 4221 int fd; 4222 4223 fd = ::open64(path, oflag, mode); 4224 if (fd == -1) return -1; 4225 4226 // If the open succeeded, the file might still be a directory 4227 { 4228 struct stat64 buf64; 4229 int ret = ::fstat64(fd, &buf64); 4230 int st_mode = buf64.st_mode; 4231 4232 if (ret != -1) { 4233 if ((st_mode & S_IFMT) == S_IFDIR) { 4234 errno = EISDIR; 4235 ::close(fd); 4236 return -1; 4237 } 4238 } else { 4239 ::close(fd); 4240 return -1; 4241 } 4242 } 4243 4244 // 32-bit Solaris systems suffer from: 4245 // 4246 // - an historical default soft limit of 256 per-process file 4247 // descriptors that is too low for many Java programs. 4248 // 4249 // - a design flaw where file descriptors created using stdio 4250 // fopen must be less than 256, _even_ when the first limit above 4251 // has been raised. This can cause calls to fopen (but not calls to 4252 // open, for example) to fail mysteriously, perhaps in 3rd party 4253 // native code (although the JDK itself uses fopen). One can hardly 4254 // criticize them for using this most standard of all functions. 4255 // 4256 // We attempt to make everything work anyways by: 4257 // 4258 // - raising the soft limit on per-process file descriptors beyond 4259 // 256 4260 // 4261 // - As of Solaris 10u4, we can request that Solaris raise the 256 4262 // stdio fopen limit by calling function enable_extended_FILE_stdio. 4263 // This is done in init_2 and recorded in enabled_extended_FILE_stdio 4264 // 4265 // - If we are stuck on an old (pre 10u4) Solaris system, we can 4266 // workaround the bug by remapping non-stdio file descriptors below 4267 // 256 to ones beyond 256, which is done below. 4268 // 4269 // See: 4270 // 1085341: 32-bit stdio routines should support file descriptors >255 4271 // 6533291: Work around 32-bit Solaris stdio limit of 256 open files 4272 // 6431278: Netbeans crash on 32 bit Solaris: need to call 4273 // enable_extended_FILE_stdio() in VM initialisation 4274 // Giri Mandalika's blog 4275 // http://technopark02.blogspot.com/2005_05_01_archive.html 4276 // 4277 #ifndef _LP64 4278 if ((!enabled_extended_FILE_stdio) && fd < 256) { 4279 int newfd = ::fcntl(fd, F_DUPFD, 256); 4280 if (newfd != -1) { 4281 ::close(fd); 4282 fd = newfd; 4283 } 4284 } 4285 #endif // 32-bit Solaris 4286 4287 // All file descriptors that are opened in the JVM and not 4288 // specifically destined for a subprocess should have the 4289 // close-on-exec flag set. If we don't set it, then careless 3rd 4290 // party native code might fork and exec without closing all 4291 // appropriate file descriptors (e.g. as we do in closeDescriptors in 4292 // UNIXProcess.c), and this in turn might: 4293 // 4294 // - cause end-of-file to fail to be detected on some file 4295 // descriptors, resulting in mysterious hangs, or 4296 // 4297 // - might cause an fopen in the subprocess to fail on a system 4298 // suffering from bug 1085341. 4299 // 4300 // (Yes, the default setting of the close-on-exec flag is a Unix 4301 // design flaw) 4302 // 4303 // See: 4304 // 1085341: 32-bit stdio routines should support file descriptors >255 4305 // 4843136: (process) pipe file descriptor from Runtime.exec not being closed 4306 // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 4307 // 4308 #ifdef FD_CLOEXEC 4309 { 4310 int flags = ::fcntl(fd, F_GETFD); 4311 if (flags != -1) { 4312 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); 4313 } 4314 } 4315 #endif 4316 4317 return fd; 4318 } 4319 4320 // create binary file, rewriting existing file if required 4321 int os::create_binary_file(const char* path, bool rewrite_existing) { 4322 int oflags = O_WRONLY | O_CREAT; 4323 if (!rewrite_existing) { 4324 oflags |= O_EXCL; 4325 } 4326 return ::open64(path, oflags, S_IREAD | S_IWRITE); 4327 } 4328 4329 // return current position of file pointer 4330 jlong os::current_file_offset(int fd) { 4331 return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR); 4332 } 4333 4334 // move file pointer to the specified offset 4335 jlong os::seek_to_file_offset(int fd, jlong offset) { 4336 return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET); 4337 } 4338 4339 jlong os::lseek(int fd, jlong offset, int whence) { 4340 return (jlong) ::lseek64(fd, offset, whence); 4341 } 4342 4343 int os::ftruncate(int fd, jlong length) { 4344 return ::ftruncate64(fd, length); 4345 } 4346 4347 int os::fsync(int fd) { 4348 RESTARTABLE_RETURN_INT(::fsync(fd)); 4349 } 4350 4351 int os::available(int fd, jlong *bytes) { 4352 assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native, 4353 "Assumed _thread_in_native"); 4354 jlong cur, end; 4355 int mode; 4356 struct stat64 buf64; 4357 4358 if (::fstat64(fd, &buf64) >= 0) { 4359 mode = buf64.st_mode; 4360 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { 4361 int n,ioctl_return; 4362 4363 RESTARTABLE(::ioctl(fd, FIONREAD, &n), ioctl_return); 4364 if (ioctl_return>= 0) { 4365 *bytes = n; 4366 return 1; 4367 } 4368 } 4369 } 4370 if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) { 4371 return 0; 4372 } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) { 4373 return 0; 4374 } else if (::lseek64(fd, cur, SEEK_SET) == -1) { 4375 return 0; 4376 } 4377 *bytes = end - cur; 4378 return 1; 4379 } 4380 4381 // Map a block of memory. 4382 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, 4383 char *addr, size_t bytes, bool read_only, 4384 bool allow_exec) { 4385 int prot; 4386 int flags; 4387 4388 if (read_only) { 4389 prot = PROT_READ; 4390 flags = MAP_SHARED; 4391 } else { 4392 prot = PROT_READ | PROT_WRITE; 4393 flags = MAP_PRIVATE; 4394 } 4395 4396 if (allow_exec) { 4397 prot |= PROT_EXEC; 4398 } 4399 4400 if (addr != NULL) { 4401 flags |= MAP_FIXED; 4402 } 4403 4404 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, 4405 fd, file_offset); 4406 if (mapped_address == MAP_FAILED) { 4407 return NULL; 4408 } 4409 return mapped_address; 4410 } 4411 4412 4413 // Remap a block of memory. 4414 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, 4415 char *addr, size_t bytes, bool read_only, 4416 bool allow_exec) { 4417 // same as map_memory() on this OS 4418 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 4419 allow_exec); 4420 } 4421 4422 4423 // Unmap a block of memory. 4424 bool os::pd_unmap_memory(char* addr, size_t bytes) { 4425 return munmap(addr, bytes) == 0; 4426 } 4427 4428 void os::pause() { 4429 char filename[MAX_PATH]; 4430 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 4431 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 4432 } else { 4433 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 4434 } 4435 4436 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 4437 if (fd != -1) { 4438 struct stat buf; 4439 ::close(fd); 4440 while (::stat(filename, &buf) == 0) { 4441 (void)::poll(NULL, 0, 100); 4442 } 4443 } else { 4444 jio_fprintf(stderr, 4445 "Could not open pause file '%s', continuing immediately.\n", filename); 4446 } 4447 } 4448 4449 #ifndef PRODUCT 4450 #ifdef INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS 4451 // Turn this on if you need to trace synch operations. 4452 // Set RECORD_SYNCH_LIMIT to a large-enough value, 4453 // and call record_synch_enable and record_synch_disable 4454 // around the computation of interest. 4455 4456 void record_synch(char* name, bool returning); // defined below 4457 4458 class RecordSynch { 4459 char* _name; 4460 public: 4461 RecordSynch(char* name) :_name(name) { record_synch(_name, false); } 4462 ~RecordSynch() { record_synch(_name, true); } 4463 }; 4464 4465 #define CHECK_SYNCH_OP(ret, name, params, args, inner) \ 4466 extern "C" ret name params { \ 4467 typedef ret name##_t params; \ 4468 static name##_t* implem = NULL; \ 4469 static int callcount = 0; \ 4470 if (implem == NULL) { \ 4471 implem = (name##_t*) dlsym(RTLD_NEXT, #name); \ 4472 if (implem == NULL) fatal(dlerror()); \ 4473 } \ 4474 ++callcount; \ 4475 RecordSynch _rs(#name); \ 4476 inner; \ 4477 return implem args; \ 4478 } 4479 // in dbx, examine callcounts this way: 4480 // for n in $(eval whereis callcount | awk '{print $2}'); do print $n; done 4481 4482 #define CHECK_POINTER_OK(p) \ 4483 (!Universe::is_fully_initialized() || !Universe::is_reserved_heap((oop)(p))) 4484 #define CHECK_MU \ 4485 if (!CHECK_POINTER_OK(mu)) fatal("Mutex must be in C heap only."); 4486 #define CHECK_CV \ 4487 if (!CHECK_POINTER_OK(cv)) fatal("Condvar must be in C heap only."); 4488 #define CHECK_P(p) \ 4489 if (!CHECK_POINTER_OK(p)) fatal(false, "Pointer must be in C heap only."); 4490 4491 #define CHECK_MUTEX(mutex_op) \ 4492 CHECK_SYNCH_OP(int, mutex_op, (mutex_t *mu), (mu), CHECK_MU); 4493 4494 CHECK_MUTEX( mutex_lock) 4495 CHECK_MUTEX( _mutex_lock) 4496 CHECK_MUTEX( mutex_unlock) 4497 CHECK_MUTEX(_mutex_unlock) 4498 CHECK_MUTEX( mutex_trylock) 4499 CHECK_MUTEX(_mutex_trylock) 4500 4501 #define CHECK_COND(cond_op) \ 4502 CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu), (cv, mu), CHECK_MU; CHECK_CV); 4503 4504 CHECK_COND( cond_wait); 4505 CHECK_COND(_cond_wait); 4506 CHECK_COND(_cond_wait_cancel); 4507 4508 #define CHECK_COND2(cond_op) \ 4509 CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu, timestruc_t* ts), (cv, mu, ts), CHECK_MU; CHECK_CV); 4510 4511 CHECK_COND2( cond_timedwait); 4512 CHECK_COND2(_cond_timedwait); 4513 CHECK_COND2(_cond_timedwait_cancel); 4514 4515 // do the _lwp_* versions too 4516 #define mutex_t lwp_mutex_t 4517 #define cond_t lwp_cond_t 4518 CHECK_MUTEX( _lwp_mutex_lock) 4519 CHECK_MUTEX( _lwp_mutex_unlock) 4520 CHECK_MUTEX( _lwp_mutex_trylock) 4521 CHECK_MUTEX( __lwp_mutex_lock) 4522 CHECK_MUTEX( __lwp_mutex_unlock) 4523 CHECK_MUTEX( __lwp_mutex_trylock) 4524 CHECK_MUTEX(___lwp_mutex_lock) 4525 CHECK_MUTEX(___lwp_mutex_unlock) 4526 4527 CHECK_COND( _lwp_cond_wait); 4528 CHECK_COND( __lwp_cond_wait); 4529 CHECK_COND(___lwp_cond_wait); 4530 4531 CHECK_COND2( _lwp_cond_timedwait); 4532 CHECK_COND2( __lwp_cond_timedwait); 4533 #undef mutex_t 4534 #undef cond_t 4535 4536 CHECK_SYNCH_OP(int, _lwp_suspend2, (int lwp, int *n), (lwp, n), 0); 4537 CHECK_SYNCH_OP(int,__lwp_suspend2, (int lwp, int *n), (lwp, n), 0); 4538 CHECK_SYNCH_OP(int, _lwp_kill, (int lwp, int n), (lwp, n), 0); 4539 CHECK_SYNCH_OP(int,__lwp_kill, (int lwp, int n), (lwp, n), 0); 4540 CHECK_SYNCH_OP(int, _lwp_sema_wait, (lwp_sema_t* p), (p), CHECK_P(p)); 4541 CHECK_SYNCH_OP(int,__lwp_sema_wait, (lwp_sema_t* p), (p), CHECK_P(p)); 4542 CHECK_SYNCH_OP(int, _lwp_cond_broadcast, (lwp_cond_t* cv), (cv), CHECK_CV); 4543 CHECK_SYNCH_OP(int,__lwp_cond_broadcast, (lwp_cond_t* cv), (cv), CHECK_CV); 4544 4545 4546 // recording machinery: 4547 4548 enum { RECORD_SYNCH_LIMIT = 200 }; 4549 char* record_synch_name[RECORD_SYNCH_LIMIT]; 4550 void* record_synch_arg0ptr[RECORD_SYNCH_LIMIT]; 4551 bool record_synch_returning[RECORD_SYNCH_LIMIT]; 4552 thread_t record_synch_thread[RECORD_SYNCH_LIMIT]; 4553 int record_synch_count = 0; 4554 bool record_synch_enabled = false; 4555 4556 // in dbx, examine recorded data this way: 4557 // for n in name arg0ptr returning thread; do print record_synch_$n[0..record_synch_count-1]; done 4558 4559 void record_synch(char* name, bool returning) { 4560 if (record_synch_enabled) { 4561 if (record_synch_count < RECORD_SYNCH_LIMIT) { 4562 record_synch_name[record_synch_count] = name; 4563 record_synch_returning[record_synch_count] = returning; 4564 record_synch_thread[record_synch_count] = thr_self(); 4565 record_synch_arg0ptr[record_synch_count] = &name; 4566 record_synch_count++; 4567 } 4568 // put more checking code here: 4569 // ... 4570 } 4571 } 4572 4573 void record_synch_enable() { 4574 // start collecting trace data, if not already doing so 4575 if (!record_synch_enabled) record_synch_count = 0; 4576 record_synch_enabled = true; 4577 } 4578 4579 void record_synch_disable() { 4580 // stop collecting trace data 4581 record_synch_enabled = false; 4582 } 4583 4584 #endif // INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS 4585 #endif // PRODUCT 4586 4587 const intptr_t thr_time_off = (intptr_t)(&((prusage_t *)(NULL))->pr_utime); 4588 const intptr_t thr_time_size = (intptr_t)(&((prusage_t *)(NULL))->pr_ttime) - 4589 (intptr_t)(&((prusage_t *)(NULL))->pr_utime); 4590 4591 4592 // JVMTI & JVM monitoring and management support 4593 // The thread_cpu_time() and current_thread_cpu_time() are only 4594 // supported if is_thread_cpu_time_supported() returns true. 4595 // They are not supported on Solaris T1. 4596 4597 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 4598 // are used by JVM M&M and JVMTI to get user+sys or user CPU time 4599 // of a thread. 4600 // 4601 // current_thread_cpu_time() and thread_cpu_time(Thread *) 4602 // returns the fast estimate available on the platform. 4603 4604 // hrtime_t gethrvtime() return value includes 4605 // user time but does not include system time 4606 jlong os::current_thread_cpu_time() { 4607 return (jlong) gethrvtime(); 4608 } 4609 4610 jlong os::thread_cpu_time(Thread *thread) { 4611 // return user level CPU time only to be consistent with 4612 // what current_thread_cpu_time returns. 4613 // thread_cpu_time_info() must be changed if this changes 4614 return os::thread_cpu_time(thread, false /* user time only */); 4615 } 4616 4617 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 4618 if (user_sys_cpu_time) { 4619 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time); 4620 } else { 4621 return os::current_thread_cpu_time(); 4622 } 4623 } 4624 4625 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 4626 char proc_name[64]; 4627 int count; 4628 prusage_t prusage; 4629 jlong lwp_time; 4630 int fd; 4631 4632 sprintf(proc_name, "/proc/%d/lwp/%d/lwpusage", 4633 getpid(), 4634 thread->osthread()->lwp_id()); 4635 fd = ::open(proc_name, O_RDONLY); 4636 if (fd == -1) return -1; 4637 4638 do { 4639 count = ::pread(fd, 4640 (void *)&prusage.pr_utime, 4641 thr_time_size, 4642 thr_time_off); 4643 } while (count < 0 && errno == EINTR); 4644 ::close(fd); 4645 if (count < 0) return -1; 4646 4647 if (user_sys_cpu_time) { 4648 // user + system CPU time 4649 lwp_time = (((jlong)prusage.pr_stime.tv_sec + 4650 (jlong)prusage.pr_utime.tv_sec) * (jlong)1000000000) + 4651 (jlong)prusage.pr_stime.tv_nsec + 4652 (jlong)prusage.pr_utime.tv_nsec; 4653 } else { 4654 // user level CPU time only 4655 lwp_time = ((jlong)prusage.pr_utime.tv_sec * (jlong)1000000000) + 4656 (jlong)prusage.pr_utime.tv_nsec; 4657 } 4658 4659 return (lwp_time); 4660 } 4661 4662 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 4663 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 4664 info_ptr->may_skip_backward = false; // elapsed time not wall time 4665 info_ptr->may_skip_forward = false; // elapsed time not wall time 4666 info_ptr->kind = JVMTI_TIMER_USER_CPU; // only user time is returned 4667 } 4668 4669 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 4670 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 4671 info_ptr->may_skip_backward = false; // elapsed time not wall time 4672 info_ptr->may_skip_forward = false; // elapsed time not wall time 4673 info_ptr->kind = JVMTI_TIMER_USER_CPU; // only user time is returned 4674 } 4675 4676 bool os::is_thread_cpu_time_supported() { 4677 return true; 4678 } 4679 4680 // System loadavg support. Returns -1 if load average cannot be obtained. 4681 // Return the load average for our processor set if the primitive exists 4682 // (Solaris 9 and later). Otherwise just return system wide loadavg. 4683 int os::loadavg(double loadavg[], int nelem) { 4684 if (pset_getloadavg_ptr != NULL) { 4685 return (*pset_getloadavg_ptr)(PS_MYID, loadavg, nelem); 4686 } else { 4687 return ::getloadavg(loadavg, nelem); 4688 } 4689 } 4690 4691 //--------------------------------------------------------------------------------- 4692 4693 bool os::find(address addr, outputStream* st) { 4694 Dl_info dlinfo; 4695 memset(&dlinfo, 0, sizeof(dlinfo)); 4696 if (dladdr(addr, &dlinfo) != 0) { 4697 st->print(PTR_FORMAT ": ", addr); 4698 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { 4699 st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr); 4700 } else if (dlinfo.dli_fbase != NULL) { 4701 st->print("<offset %#lx>", addr-(intptr_t)dlinfo.dli_fbase); 4702 } else { 4703 st->print("<absolute address>"); 4704 } 4705 if (dlinfo.dli_fname != NULL) { 4706 st->print(" in %s", dlinfo.dli_fname); 4707 } 4708 if (dlinfo.dli_fbase != NULL) { 4709 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); 4710 } 4711 st->cr(); 4712 4713 if (Verbose) { 4714 // decode some bytes around the PC 4715 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size()); 4716 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size()); 4717 address lowest = (address) dlinfo.dli_sname; 4718 if (!lowest) lowest = (address) dlinfo.dli_fbase; 4719 if (begin < lowest) begin = lowest; 4720 Dl_info dlinfo2; 4721 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr 4722 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) { 4723 end = (address) dlinfo2.dli_saddr; 4724 } 4725 Disassembler::decode(begin, end, st); 4726 } 4727 return true; 4728 } 4729 return false; 4730 } 4731 4732 // Following function has been added to support HotSparc's libjvm.so running 4733 // under Solaris production JDK 1.2.2 / 1.3.0. These came from 4734 // src/solaris/hpi/native_threads in the EVM codebase. 4735 // 4736 // NOTE: This is no longer needed in the 1.3.1 and 1.4 production release 4737 // libraries and should thus be removed. We will leave it behind for a while 4738 // until we no longer want to able to run on top of 1.3.0 Solaris production 4739 // JDK. See 4341971. 4740 4741 #define STACK_SLACK 0x800 4742 4743 extern "C" { 4744 intptr_t sysThreadAvailableStackWithSlack() { 4745 stack_t st; 4746 intptr_t retval, stack_top; 4747 retval = thr_stksegment(&st); 4748 assert(retval == 0, "incorrect return value from thr_stksegment"); 4749 assert((address)&st < (address)st.ss_sp, "Invalid stack base returned"); 4750 assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned"); 4751 stack_top=(intptr_t)st.ss_sp-st.ss_size; 4752 return ((intptr_t)&stack_top - stack_top - STACK_SLACK); 4753 } 4754 } 4755 4756 // ObjectMonitor park-unpark infrastructure ... 4757 // 4758 // We implement Solaris and Linux PlatformEvents with the 4759 // obvious condvar-mutex-flag triple. 4760 // Another alternative that works quite well is pipes: 4761 // Each PlatformEvent consists of a pipe-pair. 4762 // The thread associated with the PlatformEvent 4763 // calls park(), which reads from the input end of the pipe. 4764 // Unpark() writes into the other end of the pipe. 4765 // The write-side of the pipe must be set NDELAY. 4766 // Unfortunately pipes consume a large # of handles. 4767 // Native solaris lwp_park() and lwp_unpark() work nicely, too. 4768 // Using pipes for the 1st few threads might be workable, however. 4769 // 4770 // park() is permitted to return spuriously. 4771 // Callers of park() should wrap the call to park() in 4772 // an appropriate loop. A litmus test for the correct 4773 // usage of park is the following: if park() were modified 4774 // to immediately return 0 your code should still work, 4775 // albeit degenerating to a spin loop. 4776 // 4777 // In a sense, park()-unpark() just provides more polite spinning 4778 // and polling with the key difference over naive spinning being 4779 // that a parked thread needs to be explicitly unparked() in order 4780 // to wake up and to poll the underlying condition. 4781 // 4782 // Assumption: 4783 // Only one parker can exist on an event, which is why we allocate 4784 // them per-thread. Multiple unparkers can coexist. 4785 // 4786 // _Event transitions in park() 4787 // -1 => -1 : illegal 4788 // 1 => 0 : pass - return immediately 4789 // 0 => -1 : block; then set _Event to 0 before returning 4790 // 4791 // _Event transitions in unpark() 4792 // 0 => 1 : just return 4793 // 1 => 1 : just return 4794 // -1 => either 0 or 1; must signal target thread 4795 // That is, we can safely transition _Event from -1 to either 4796 // 0 or 1. 4797 // 4798 // _Event serves as a restricted-range semaphore. 4799 // -1 : thread is blocked, i.e. there is a waiter 4800 // 0 : neutral: thread is running or ready, 4801 // could have been signaled after a wait started 4802 // 1 : signaled - thread is running or ready 4803 // 4804 // Another possible encoding of _Event would be with 4805 // explicit "PARKED" == 01b and "SIGNALED" == 10b bits. 4806 // 4807 // TODO-FIXME: add DTRACE probes for: 4808 // 1. Tx parks 4809 // 2. Ty unparks Tx 4810 // 3. Tx resumes from park 4811 4812 4813 // value determined through experimentation 4814 #define ROUNDINGFIX 11 4815 4816 // utility to compute the abstime argument to timedwait. 4817 // TODO-FIXME: switch from compute_abstime() to unpackTime(). 4818 4819 static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) { 4820 // millis is the relative timeout time 4821 // abstime will be the absolute timeout time 4822 if (millis < 0) millis = 0; 4823 struct timeval now; 4824 int status = gettimeofday(&now, NULL); 4825 assert(status == 0, "gettimeofday"); 4826 jlong seconds = millis / 1000; 4827 jlong max_wait_period; 4828 4829 if (UseLWPSynchronization) { 4830 // forward port of fix for 4275818 (not sleeping long enough) 4831 // There was a bug in Solaris 6, 7 and pre-patch 5 of 8 where 4832 // _lwp_cond_timedwait() used a round_down algorithm rather 4833 // than a round_up. For millis less than our roundfactor 4834 // it rounded down to 0 which doesn't meet the spec. 4835 // For millis > roundfactor we may return a bit sooner, but 4836 // since we can not accurately identify the patch level and 4837 // this has already been fixed in Solaris 9 and 8 we will 4838 // leave it alone rather than always rounding down. 4839 4840 if (millis > 0 && millis < ROUNDINGFIX) millis = ROUNDINGFIX; 4841 // It appears that when we go directly through Solaris _lwp_cond_timedwait() 4842 // the acceptable max time threshold is smaller than for libthread on 2.5.1 and 2.6 4843 max_wait_period = 21000000; 4844 } else { 4845 max_wait_period = 50000000; 4846 } 4847 millis %= 1000; 4848 if (seconds > max_wait_period) { // see man cond_timedwait(3T) 4849 seconds = max_wait_period; 4850 } 4851 abstime->tv_sec = now.tv_sec + seconds; 4852 long usec = now.tv_usec + millis * 1000; 4853 if (usec >= 1000000) { 4854 abstime->tv_sec += 1; 4855 usec -= 1000000; 4856 } 4857 abstime->tv_nsec = usec * 1000; 4858 return abstime; 4859 } 4860 4861 void os::PlatformEvent::park() { // AKA: down() 4862 // Transitions for _Event: 4863 // -1 => -1 : illegal 4864 // 1 => 0 : pass - return immediately 4865 // 0 => -1 : block; then set _Event to 0 before returning 4866 4867 // Invariant: Only the thread associated with the Event/PlatformEvent 4868 // may call park(). 4869 assert(_nParked == 0, "invariant"); 4870 4871 int v; 4872 for (;;) { 4873 v = _Event; 4874 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 4875 } 4876 guarantee(v >= 0, "invariant"); 4877 if (v == 0) { 4878 // Do this the hard way by blocking ... 4879 // See http://monaco.sfbay/detail.jsf?cr=5094058. 4880 int status = os::Solaris::mutex_lock(_mutex); 4881 assert_status(status == 0, status, "mutex_lock"); 4882 guarantee(_nParked == 0, "invariant"); 4883 ++_nParked; 4884 while (_Event < 0) { 4885 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... 4886 // Treat this the same as if the wait was interrupted 4887 // With usr/lib/lwp going to kernel, always handle ETIME 4888 status = os::Solaris::cond_wait(_cond, _mutex); 4889 if (status == ETIME) status = EINTR; 4890 assert_status(status == 0 || status == EINTR, status, "cond_wait"); 4891 } 4892 --_nParked; 4893 _Event = 0; 4894 status = os::Solaris::mutex_unlock(_mutex); 4895 assert_status(status == 0, status, "mutex_unlock"); 4896 // Paranoia to ensure our locked and lock-free paths interact 4897 // correctly with each other. 4898 OrderAccess::fence(); 4899 } 4900 } 4901 4902 int os::PlatformEvent::park(jlong millis) { 4903 // Transitions for _Event: 4904 // -1 => -1 : illegal 4905 // 1 => 0 : pass - return immediately 4906 // 0 => -1 : block; then set _Event to 0 before returning 4907 4908 guarantee(_nParked == 0, "invariant"); 4909 int v; 4910 for (;;) { 4911 v = _Event; 4912 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 4913 } 4914 guarantee(v >= 0, "invariant"); 4915 if (v != 0) return OS_OK; 4916 4917 int ret = OS_TIMEOUT; 4918 timestruc_t abst; 4919 compute_abstime(&abst, millis); 4920 4921 // See http://monaco.sfbay/detail.jsf?cr=5094058. 4922 int status = os::Solaris::mutex_lock(_mutex); 4923 assert_status(status == 0, status, "mutex_lock"); 4924 guarantee(_nParked == 0, "invariant"); 4925 ++_nParked; 4926 while (_Event < 0) { 4927 int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst); 4928 assert_status(status == 0 || status == EINTR || 4929 status == ETIME || status == ETIMEDOUT, 4930 status, "cond_timedwait"); 4931 if (!FilterSpuriousWakeups) break; // previous semantics 4932 if (status == ETIME || status == ETIMEDOUT) break; 4933 // We consume and ignore EINTR and spurious wakeups. 4934 } 4935 --_nParked; 4936 if (_Event >= 0) ret = OS_OK; 4937 _Event = 0; 4938 status = os::Solaris::mutex_unlock(_mutex); 4939 assert_status(status == 0, status, "mutex_unlock"); 4940 // Paranoia to ensure our locked and lock-free paths interact 4941 // correctly with each other. 4942 OrderAccess::fence(); 4943 return ret; 4944 } 4945 4946 void os::PlatformEvent::unpark() { 4947 // Transitions for _Event: 4948 // 0 => 1 : just return 4949 // 1 => 1 : just return 4950 // -1 => either 0 or 1; must signal target thread 4951 // That is, we can safely transition _Event from -1 to either 4952 // 0 or 1. 4953 // See also: "Semaphores in Plan 9" by Mullender & Cox 4954 // 4955 // Note: Forcing a transition from "-1" to "1" on an unpark() means 4956 // that it will take two back-to-back park() calls for the owning 4957 // thread to block. This has the benefit of forcing a spurious return 4958 // from the first park() call after an unpark() call which will help 4959 // shake out uses of park() and unpark() without condition variables. 4960 4961 if (Atomic::xchg(1, &_Event) >= 0) return; 4962 4963 // If the thread associated with the event was parked, wake it. 4964 // Wait for the thread assoc with the PlatformEvent to vacate. 4965 int status = os::Solaris::mutex_lock(_mutex); 4966 assert_status(status == 0, status, "mutex_lock"); 4967 int AnyWaiters = _nParked; 4968 status = os::Solaris::mutex_unlock(_mutex); 4969 assert_status(status == 0, status, "mutex_unlock"); 4970 guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant"); 4971 if (AnyWaiters != 0) { 4972 // Note that we signal() *after* dropping the lock for "immortal" Events. 4973 // This is safe and avoids a common class of futile wakeups. In rare 4974 // circumstances this can cause a thread to return prematurely from 4975 // cond_{timed}wait() but the spurious wakeup is benign and the victim 4976 // will simply re-test the condition and re-park itself. 4977 // This provides particular benefit if the underlying platform does not 4978 // provide wait morphing. 4979 status = os::Solaris::cond_signal(_cond); 4980 assert_status(status == 0, status, "cond_signal"); 4981 } 4982 } 4983 4984 // JSR166 4985 // ------------------------------------------------------- 4986 4987 // The solaris and linux implementations of park/unpark are fairly 4988 // conservative for now, but can be improved. They currently use a 4989 // mutex/condvar pair, plus _counter. 4990 // Park decrements _counter if > 0, else does a condvar wait. Unpark 4991 // sets count to 1 and signals condvar. Only one thread ever waits 4992 // on the condvar. Contention seen when trying to park implies that someone 4993 // is unparking you, so don't wait. And spurious returns are fine, so there 4994 // is no need to track notifications. 4995 4996 #define MAX_SECS 100000000 4997 4998 // This code is common to linux and solaris and will be moved to a 4999 // common place in dolphin. 5000 // 5001 // The passed in time value is either a relative time in nanoseconds 5002 // or an absolute time in milliseconds. Either way it has to be unpacked 5003 // into suitable seconds and nanoseconds components and stored in the 5004 // given timespec structure. 5005 // Given time is a 64-bit value and the time_t used in the timespec is only 5006 // a signed-32-bit value (except on 64-bit Linux) we have to watch for 5007 // overflow if times way in the future are given. Further on Solaris versions 5008 // prior to 10 there is a restriction (see cond_timedwait) that the specified 5009 // number of seconds, in abstime, is less than current_time + 100,000,000. 5010 // As it will be 28 years before "now + 100000000" will overflow we can 5011 // ignore overflow and just impose a hard-limit on seconds using the value 5012 // of "now + 100,000,000". This places a limit on the timeout of about 3.17 5013 // years from "now". 5014 // 5015 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { 5016 assert(time > 0, "convertTime"); 5017 5018 struct timeval now; 5019 int status = gettimeofday(&now, NULL); 5020 assert(status == 0, "gettimeofday"); 5021 5022 time_t max_secs = now.tv_sec + MAX_SECS; 5023 5024 if (isAbsolute) { 5025 jlong secs = time / 1000; 5026 if (secs > max_secs) { 5027 absTime->tv_sec = max_secs; 5028 } else { 5029 absTime->tv_sec = secs; 5030 } 5031 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; 5032 } else { 5033 jlong secs = time / NANOSECS_PER_SEC; 5034 if (secs >= MAX_SECS) { 5035 absTime->tv_sec = max_secs; 5036 absTime->tv_nsec = 0; 5037 } else { 5038 absTime->tv_sec = now.tv_sec + secs; 5039 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; 5040 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 5041 absTime->tv_nsec -= NANOSECS_PER_SEC; 5042 ++absTime->tv_sec; // note: this must be <= max_secs 5043 } 5044 } 5045 } 5046 assert(absTime->tv_sec >= 0, "tv_sec < 0"); 5047 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); 5048 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); 5049 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); 5050 } 5051 5052 void Parker::park(bool isAbsolute, jlong time) { 5053 // Ideally we'd do something useful while spinning, such 5054 // as calling unpackTime(). 5055 5056 // Optional fast-path check: 5057 // Return immediately if a permit is available. 5058 // We depend on Atomic::xchg() having full barrier semantics 5059 // since we are doing a lock-free update to _counter. 5060 if (Atomic::xchg(0, &_counter) > 0) return; 5061 5062 // Optional fast-exit: Check interrupt before trying to wait 5063 Thread* thread = Thread::current(); 5064 assert(thread->is_Java_thread(), "Must be JavaThread"); 5065 JavaThread *jt = (JavaThread *)thread; 5066 if (jt->is_interrupted(false)) { 5067 return; 5068 } 5069 5070 // First, demultiplex/decode time arguments 5071 timespec absTime; 5072 if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all 5073 return; 5074 } 5075 if (time > 0) { 5076 // Warning: this code might be exposed to the old Solaris time 5077 // round-down bugs. Grep "roundingFix" for details. 5078 unpackTime(&absTime, isAbsolute, time); 5079 } 5080 5081 // Enter safepoint region 5082 // Beware of deadlocks such as 6317397. 5083 // The per-thread Parker:: _mutex is a classic leaf-lock. 5084 // In particular a thread must never block on the Threads_lock while 5085 // holding the Parker:: mutex. If safepoints are pending both the 5086 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 5087 ThreadBlockInVM tbivm(jt); 5088 5089 // Don't wait if cannot get lock since interference arises from 5090 // unblocking. Also. check interrupt before trying wait 5091 if (jt->is_interrupted(false) || 5092 os::Solaris::mutex_trylock(_mutex) != 0) { 5093 return; 5094 } 5095 5096 int status; 5097 5098 if (_counter > 0) { // no wait needed 5099 _counter = 0; 5100 status = os::Solaris::mutex_unlock(_mutex); 5101 assert(status == 0, "invariant"); 5102 // Paranoia to ensure our locked and lock-free paths interact 5103 // correctly with each other and Java-level accesses. 5104 OrderAccess::fence(); 5105 return; 5106 } 5107 5108 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 5109 jt->set_suspend_equivalent(); 5110 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 5111 5112 // Do this the hard way by blocking ... 5113 // See http://monaco.sfbay/detail.jsf?cr=5094058. 5114 if (time == 0) { 5115 status = os::Solaris::cond_wait(_cond, _mutex); 5116 } else { 5117 status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime); 5118 } 5119 // Note that an untimed cond_wait() can sometimes return ETIME on older 5120 // versions of the Solaris. 5121 assert_status(status == 0 || status == EINTR || 5122 status == ETIME || status == ETIMEDOUT, 5123 status, "cond_timedwait"); 5124 5125 _counter = 0; 5126 status = os::Solaris::mutex_unlock(_mutex); 5127 assert_status(status == 0, status, "mutex_unlock"); 5128 // Paranoia to ensure our locked and lock-free paths interact 5129 // correctly with each other and Java-level accesses. 5130 OrderAccess::fence(); 5131 5132 // If externally suspended while waiting, re-suspend 5133 if (jt->handle_special_suspend_equivalent_condition()) { 5134 jt->java_suspend_self(); 5135 } 5136 } 5137 5138 void Parker::unpark() { 5139 int status = os::Solaris::mutex_lock(_mutex); 5140 assert(status == 0, "invariant"); 5141 const int s = _counter; 5142 _counter = 1; 5143 status = os::Solaris::mutex_unlock(_mutex); 5144 assert(status == 0, "invariant"); 5145 5146 if (s < 1) { 5147 status = os::Solaris::cond_signal(_cond); 5148 assert(status == 0, "invariant"); 5149 } 5150 } 5151 5152 // Platform Mutex/Monitor implementations 5153 5154 os::PlatformMutex::PlatformMutex() { 5155 int status = os::Solaris::mutex_init(&_mutex); 5156 assert_status(status == 0, status, "mutex_init"); 5157 } 5158 5159 os::PlatformMutex::~PlatformMutex() { 5160 int status = os::Solaris::mutex_destroy(&_mutex); 5161 assert_status(status == 0, status, "mutex_destroy"); 5162 } 5163 5164 void os::PlatformMutex::lock() { 5165 int status = os::Solaris::mutex_lock(&_mutex); 5166 assert_status(status == 0, status, "mutex_lock"); 5167 } 5168 5169 void os::PlatformMutex::unlock() { 5170 int status = os::Solaris::mutex_unlock(&_mutex); 5171 assert_status(status == 0, status, "mutex_unlock"); 5172 } 5173 5174 bool os::PlatformMutex::try_lock() { 5175 int status = os::Solaris::mutex_trylock(&_mutex); 5176 assert_status(status == 0 || status == EBUSY, status, "mutex_trylock"); 5177 return status == 0; 5178 } 5179 5180 os::PlatformMonitor::PlatformMonitor() { 5181 int status = os::Solaris::cond_init(&_cond); 5182 assert_status(status == 0, status, "cond_init"); 5183 } 5184 5185 os::PlatformMonitor::~PlatformMonitor() { 5186 int status = os::Solaris::cond_destroy(&_cond); 5187 assert_status(status == 0, status, "cond_destroy"); 5188 } 5189 5190 // Must already be locked 5191 int os::PlatformMonitor::wait(jlong millis) { 5192 assert(millis >= 0, "negative timeout"); 5193 if (millis > 0) { 5194 timestruc_t abst; 5195 int ret = OS_TIMEOUT; 5196 compute_abstime(&abst, millis); 5197 int status = os::Solaris::cond_timedwait(&_cond, &_mutex, &abst); 5198 assert_status(status == 0 || status == EINTR || 5199 status == ETIME || status == ETIMEDOUT, 5200 status, "cond_timedwait"); 5201 // EINTR acts as spurious wakeup - which is permitted anyway 5202 if (status == 0 || status == EINTR) { 5203 ret = OS_OK; 5204 } 5205 return ret; 5206 } else { 5207 int status = os::Solaris::cond_wait(&_cond, &_mutex); 5208 assert_status(status == 0 || status == EINTR, 5209 status, "cond_wait"); 5210 return OS_OK; 5211 } 5212 } 5213 5214 void os::PlatformMonitor::notify() { 5215 int status = os::Solaris::cond_signal(&_cond); 5216 assert_status(status == 0, status, "cond_signal"); 5217 } 5218 5219 void os::PlatformMonitor::notify_all() { 5220 int status = os::Solaris::cond_broadcast(&_cond); 5221 assert_status(status == 0, status, "cond_broadcast"); 5222 } 5223 5224 extern char** environ; 5225 5226 // Run the specified command in a separate process. Return its exit value, 5227 // or -1 on failure (e.g. can't fork a new process). 5228 // Unlike system(), this function can be called from signal handler. It 5229 // doesn't block SIGINT et al. 5230 int os::fork_and_exec(char* cmd, bool use_vfork_if_available) { 5231 char * argv[4]; 5232 argv[0] = (char *)"sh"; 5233 argv[1] = (char *)"-c"; 5234 argv[2] = cmd; 5235 argv[3] = NULL; 5236 5237 // fork is async-safe, fork1 is not so can't use in signal handler 5238 pid_t pid; 5239 Thread* t = Thread::current_or_null_safe(); 5240 if (t != NULL && t->is_inside_signal_handler()) { 5241 pid = fork(); 5242 } else { 5243 pid = fork1(); 5244 } 5245 5246 if (pid < 0) { 5247 // fork failed 5248 warning("fork failed: %s", os::strerror(errno)); 5249 return -1; 5250 5251 } else if (pid == 0) { 5252 // child process 5253 5254 // try to be consistent with system(), which uses "/usr/bin/sh" on Solaris 5255 execve("/usr/bin/sh", argv, environ); 5256 5257 // execve failed 5258 _exit(-1); 5259 5260 } else { 5261 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't 5262 // care about the actual exit code, for now. 5263 5264 int status; 5265 5266 // Wait for the child process to exit. This returns immediately if 5267 // the child has already exited. */ 5268 while (waitpid(pid, &status, 0) < 0) { 5269 switch (errno) { 5270 case ECHILD: return 0; 5271 case EINTR: break; 5272 default: return -1; 5273 } 5274 } 5275 5276 if (WIFEXITED(status)) { 5277 // The child exited normally; get its exit code. 5278 return WEXITSTATUS(status); 5279 } else if (WIFSIGNALED(status)) { 5280 // The child exited because of a signal 5281 // The best value to return is 0x80 + signal number, 5282 // because that is what all Unix shells do, and because 5283 // it allows callers to distinguish between process exit and 5284 // process death by signal. 5285 return 0x80 + WTERMSIG(status); 5286 } else { 5287 // Unknown exit code; pass it through 5288 return status; 5289 } 5290 } 5291 } 5292 5293 size_t os::write(int fd, const void *buf, unsigned int nBytes) { 5294 size_t res; 5295 RESTARTABLE((size_t) ::write(fd, buf, (size_t) nBytes), res); 5296 return res; 5297 } 5298 5299 int os::close(int fd) { 5300 return ::close(fd); 5301 } 5302 5303 int os::socket_close(int fd) { 5304 return ::close(fd); 5305 } 5306 5307 int os::recv(int fd, char* buf, size_t nBytes, uint flags) { 5308 assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native, 5309 "Assumed _thread_in_native"); 5310 RESTARTABLE_RETURN_INT((int)::recv(fd, buf, nBytes, flags)); 5311 } 5312 5313 int os::send(int fd, char* buf, size_t nBytes, uint flags) { 5314 assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native, 5315 "Assumed _thread_in_native"); 5316 RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags)); 5317 } 5318 5319 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) { 5320 RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags)); 5321 } 5322 5323 // As both poll and select can be interrupted by signals, we have to be 5324 // prepared to restart the system call after updating the timeout, unless 5325 // a poll() is done with timeout == -1, in which case we repeat with this 5326 // "wait forever" value. 5327 5328 int os::connect(int fd, struct sockaddr *him, socklen_t len) { 5329 int _result; 5330 _result = ::connect(fd, him, len); 5331 5332 // On Solaris, when a connect() call is interrupted, the connection 5333 // can be established asynchronously (see 6343810). Subsequent calls 5334 // to connect() must check the errno value which has the semantic 5335 // described below (copied from the connect() man page). Handling 5336 // of asynchronously established connections is required for both 5337 // blocking and non-blocking sockets. 5338 // EINTR The connection attempt was interrupted 5339 // before any data arrived by the delivery of 5340 // a signal. The connection, however, will be 5341 // established asynchronously. 5342 // 5343 // EINPROGRESS The socket is non-blocking, and the connec- 5344 // tion cannot be completed immediately. 5345 // 5346 // EALREADY The socket is non-blocking, and a previous 5347 // connection attempt has not yet been com- 5348 // pleted. 5349 // 5350 // EISCONN The socket is already connected. 5351 if (_result == OS_ERR && errno == EINTR) { 5352 // restarting a connect() changes its errno semantics 5353 RESTARTABLE(::connect(fd, him, len), _result); 5354 // undo these changes 5355 if (_result == OS_ERR) { 5356 if (errno == EALREADY) { 5357 errno = EINPROGRESS; // fall through 5358 } else if (errno == EISCONN) { 5359 errno = 0; 5360 return OS_OK; 5361 } 5362 } 5363 } 5364 return _result; 5365 } 5366 5367 // Get the default path to the core file 5368 // Returns the length of the string 5369 int os::get_core_path(char* buffer, size_t bufferSize) { 5370 const char* p = get_current_directory(buffer, bufferSize); 5371 5372 if (p == NULL) { 5373 assert(p != NULL, "failed to get current directory"); 5374 return 0; 5375 } 5376 5377 jio_snprintf(buffer, bufferSize, "%s/core or core.%d", 5378 p, current_process_id()); 5379 5380 return strlen(buffer); 5381 } 5382 5383 bool os::supports_map_sync() { 5384 return false; 5385 } 5386 5387 #ifndef PRODUCT 5388 void TestReserveMemorySpecial_test() { 5389 // No tests available for this platform 5390 } 5391 #endif 5392 5393 bool os::start_debugging(char *buf, int buflen) { 5394 int len = (int)strlen(buf); 5395 char *p = &buf[len]; 5396 5397 jio_snprintf(p, buflen-len, 5398 "\n\n" 5399 "Do you want to debug the problem?\n\n" 5400 "To debug, run 'dbx - %d'; then switch to thread " INTX_FORMAT "\n" 5401 "Enter 'yes' to launch dbx automatically (PATH must include dbx)\n" 5402 "Otherwise, press RETURN to abort...", 5403 os::current_process_id(), os::current_thread_id()); 5404 5405 bool yes = os::message_box("Unexpected Error", buf); 5406 5407 if (yes) { 5408 // yes, user asked VM to launch debugger 5409 jio_snprintf(buf, sizeof(buf), "dbx - %d", os::current_process_id()); 5410 5411 os::fork_and_exec(buf); 5412 yes = false; 5413 } 5414 return yes; 5415 }