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