Print this page
rev 4531 : 8013398: Adjust number of stack guard pages on systems with large memory page size
Summary: Auto adjust number of stack guard pages on systems with large memory page size
Reviewed-by: bobv, coleenp
Split |
Split |
Close |
Expand all |
Collapse all |
--- old/src/os/linux/vm/os_linux.cpp
+++ new/src/os/linux/vm/os_linux.cpp
1 1 /*
2 2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 4 *
5 5 * This code is free software; you can redistribute it and/or modify it
6 6 * under the terms of the GNU General Public License version 2 only, as
7 7 * published by the Free Software Foundation.
8 8 *
9 9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 12 * version 2 for more details (a copy is included in the LICENSE file that
13 13 * accompanied this code).
14 14 *
15 15 * You should have received a copy of the GNU General Public License version
16 16 * 2 along with this work; if not, write to the Free Software Foundation,
17 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 18 *
19 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 20 * or visit www.oracle.com if you need additional information or have any
21 21 * questions.
22 22 *
23 23 */
24 24
25 25 // no precompiled headers
26 26 #include "classfile/classLoader.hpp"
27 27 #include "classfile/systemDictionary.hpp"
28 28 #include "classfile/vmSymbols.hpp"
29 29 #include "code/icBuffer.hpp"
30 30 #include "code/vtableStubs.hpp"
31 31 #include "compiler/compileBroker.hpp"
32 32 #include "interpreter/interpreter.hpp"
33 33 #include "jvm_linux.h"
34 34 #include "memory/allocation.inline.hpp"
35 35 #include "memory/filemap.hpp"
36 36 #include "mutex_linux.inline.hpp"
37 37 #include "oops/oop.inline.hpp"
38 38 #include "os_share_linux.hpp"
39 39 #include "prims/jniFastGetField.hpp"
40 40 #include "prims/jvm.h"
41 41 #include "prims/jvm_misc.hpp"
42 42 #include "runtime/arguments.hpp"
43 43 #include "runtime/extendedPC.hpp"
44 44 #include "runtime/globals.hpp"
45 45 #include "runtime/interfaceSupport.hpp"
46 46 #include "runtime/init.hpp"
47 47 #include "runtime/java.hpp"
48 48 #include "runtime/javaCalls.hpp"
49 49 #include "runtime/mutexLocker.hpp"
50 50 #include "runtime/objectMonitor.hpp"
51 51 #include "runtime/osThread.hpp"
52 52 #include "runtime/perfMemory.hpp"
53 53 #include "runtime/sharedRuntime.hpp"
54 54 #include "runtime/statSampler.hpp"
55 55 #include "runtime/stubRoutines.hpp"
56 56 #include "runtime/threadCritical.hpp"
57 57 #include "runtime/timer.hpp"
58 58 #include "services/attachListener.hpp"
59 59 #include "services/memTracker.hpp"
60 60 #include "services/runtimeService.hpp"
61 61 #include "thread_linux.inline.hpp"
62 62 #include "utilities/decoder.hpp"
63 63 #include "utilities/defaultStream.hpp"
64 64 #include "utilities/events.hpp"
65 65 #include "utilities/elfFile.hpp"
66 66 #include "utilities/growableArray.hpp"
67 67 #include "utilities/vmError.hpp"
68 68 #ifdef TARGET_ARCH_x86
69 69 # include "assembler_x86.inline.hpp"
70 70 # include "nativeInst_x86.hpp"
71 71 #endif
72 72 #ifdef TARGET_ARCH_sparc
73 73 # include "assembler_sparc.inline.hpp"
74 74 # include "nativeInst_sparc.hpp"
75 75 #endif
76 76 #ifdef TARGET_ARCH_zero
77 77 # include "assembler_zero.inline.hpp"
78 78 # include "nativeInst_zero.hpp"
79 79 #endif
80 80 #ifdef TARGET_ARCH_arm
81 81 # include "assembler_arm.inline.hpp"
82 82 # include "nativeInst_arm.hpp"
83 83 #endif
84 84 #ifdef TARGET_ARCH_ppc
85 85 # include "assembler_ppc.inline.hpp"
86 86 # include "nativeInst_ppc.hpp"
87 87 #endif
88 88
89 89 // put OS-includes here
90 90 # include <sys/types.h>
91 91 # include <sys/mman.h>
92 92 # include <sys/stat.h>
93 93 # include <sys/select.h>
94 94 # include <pthread.h>
95 95 # include <signal.h>
96 96 # include <errno.h>
97 97 # include <dlfcn.h>
98 98 # include <stdio.h>
99 99 # include <unistd.h>
100 100 # include <sys/resource.h>
101 101 # include <pthread.h>
102 102 # include <sys/stat.h>
103 103 # include <sys/time.h>
104 104 # include <sys/times.h>
105 105 # include <sys/utsname.h>
106 106 # include <sys/socket.h>
107 107 # include <sys/wait.h>
108 108 # include <pwd.h>
109 109 # include <poll.h>
110 110 # include <semaphore.h>
111 111 # include <fcntl.h>
112 112 # include <string.h>
113 113 # include <syscall.h>
114 114 # include <sys/sysinfo.h>
115 115 # include <gnu/libc-version.h>
116 116 # include <sys/ipc.h>
117 117 # include <sys/shm.h>
118 118 # include <link.h>
119 119 # include <stdint.h>
120 120 # include <inttypes.h>
121 121 # include <sys/ioctl.h>
122 122
123 123 #define MAX_PATH (2 * K)
124 124
125 125 // for timer info max values which include all bits
126 126 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
127 127
128 128 #define LARGEPAGES_BIT (1 << 6)
129 129 ////////////////////////////////////////////////////////////////////////////////
130 130 // global variables
↓ open down ↓ |
130 lines elided |
↑ open up ↑ |
131 131 julong os::Linux::_physical_memory = 0;
132 132
133 133 address os::Linux::_initial_thread_stack_bottom = NULL;
134 134 uintptr_t os::Linux::_initial_thread_stack_size = 0;
135 135
136 136 int (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL;
137 137 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL;
138 138 Mutex* os::Linux::_createThread_lock = NULL;
139 139 pthread_t os::Linux::_main_thread;
140 140 int os::Linux::_page_size = -1;
141 +const int os::Linux::_vm_default_page_size = (8 * K);
141 142 bool os::Linux::_is_floating_stack = false;
142 143 bool os::Linux::_is_NPTL = false;
143 144 bool os::Linux::_supports_fast_thread_cpu_time = false;
144 145 const char * os::Linux::_glibc_version = NULL;
145 146 const char * os::Linux::_libpthread_version = NULL;
146 147
147 148 static jlong initial_time_count=0;
148 149
149 150 static int clock_tics_per_sec = 100;
150 151
151 152 // For diagnostics to print a message once. see run_periodic_checks
152 153 static sigset_t check_signal_done;
153 154 static bool check_signals = true;;
154 155
155 156 static pid_t _initial_pid = 0;
156 157
157 158 /* Signal number used to suspend/resume a thread */
158 159
159 160 /* do not use any signal number less than SIGSEGV, see 4355769 */
160 161 static int SR_signum = SIGUSR2;
161 162 sigset_t SR_sigset;
162 163
163 164 /* Used to protect dlsym() calls */
164 165 static pthread_mutex_t dl_mutex;
165 166
166 167 // Declarations
167 168 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
168 169
169 170 #ifdef JAVASE_EMBEDDED
170 171 class MemNotifyThread: public Thread {
171 172 friend class VMStructs;
172 173 public:
173 174 virtual void run();
174 175
175 176 private:
176 177 static MemNotifyThread* _memnotify_thread;
177 178 int _fd;
178 179
179 180 public:
180 181
181 182 // Constructor
182 183 MemNotifyThread(int fd);
183 184
184 185 // Tester
185 186 bool is_memnotify_thread() const { return true; }
186 187
187 188 // Printing
188 189 char* name() const { return (char*)"Linux MemNotify Thread"; }
189 190
190 191 // Returns the single instance of the MemNotifyThread
191 192 static MemNotifyThread* memnotify_thread() { return _memnotify_thread; }
192 193
193 194 // Create and start the single instance of MemNotifyThread
194 195 static void start();
195 196 };
196 197 #endif // JAVASE_EMBEDDED
197 198
198 199 // utility functions
199 200
200 201 static int SR_initialize();
201 202 static int SR_finalize();
202 203
203 204 julong os::available_memory() {
204 205 return Linux::available_memory();
205 206 }
206 207
207 208 julong os::Linux::available_memory() {
208 209 // values in struct sysinfo are "unsigned long"
209 210 struct sysinfo si;
210 211 sysinfo(&si);
211 212
212 213 return (julong)si.freeram * si.mem_unit;
213 214 }
214 215
215 216 julong os::physical_memory() {
216 217 return Linux::physical_memory();
217 218 }
218 219
219 220 julong os::allocatable_physical_memory(julong size) {
220 221 #ifdef _LP64
221 222 return size;
222 223 #else
223 224 julong result = MIN2(size, (julong)3800*M);
224 225 if (!is_allocatable(result)) {
225 226 // See comments under solaris for alignment considerations
226 227 julong reasonable_size = (julong)2*G - 2 * os::vm_page_size();
227 228 result = MIN2(size, reasonable_size);
228 229 }
229 230 return result;
230 231 #endif // _LP64
231 232 }
232 233
233 234 ////////////////////////////////////////////////////////////////////////////////
234 235 // environment support
235 236
236 237 bool os::getenv(const char* name, char* buf, int len) {
237 238 const char* val = ::getenv(name);
238 239 if (val != NULL && strlen(val) < (size_t)len) {
239 240 strcpy(buf, val);
240 241 return true;
241 242 }
242 243 if (len > 0) buf[0] = 0; // return a null string
243 244 return false;
244 245 }
245 246
246 247
247 248 // Return true if user is running as root.
248 249
249 250 bool os::have_special_privileges() {
250 251 static bool init = false;
251 252 static bool privileges = false;
252 253 if (!init) {
253 254 privileges = (getuid() != geteuid()) || (getgid() != getegid());
254 255 init = true;
255 256 }
256 257 return privileges;
257 258 }
258 259
259 260
260 261 #ifndef SYS_gettid
261 262 // i386: 224, ia64: 1105, amd64: 186, sparc 143
262 263 #ifdef __ia64__
263 264 #define SYS_gettid 1105
264 265 #elif __i386__
265 266 #define SYS_gettid 224
266 267 #elif __amd64__
267 268 #define SYS_gettid 186
268 269 #elif __sparc__
269 270 #define SYS_gettid 143
270 271 #else
271 272 #error define gettid for the arch
272 273 #endif
273 274 #endif
274 275
275 276 // Cpu architecture string
276 277 #if defined(ZERO)
277 278 static char cpu_arch[] = ZERO_LIBARCH;
278 279 #elif defined(IA64)
279 280 static char cpu_arch[] = "ia64";
280 281 #elif defined(IA32)
281 282 static char cpu_arch[] = "i386";
282 283 #elif defined(AMD64)
283 284 static char cpu_arch[] = "amd64";
284 285 #elif defined(ARM)
285 286 static char cpu_arch[] = "arm";
286 287 #elif defined(PPC)
287 288 static char cpu_arch[] = "ppc";
288 289 #elif defined(SPARC)
289 290 # ifdef _LP64
290 291 static char cpu_arch[] = "sparcv9";
291 292 # else
292 293 static char cpu_arch[] = "sparc";
293 294 # endif
294 295 #else
295 296 #error Add appropriate cpu_arch setting
296 297 #endif
297 298
298 299
299 300 // pid_t gettid()
300 301 //
301 302 // Returns the kernel thread id of the currently running thread. Kernel
302 303 // thread id is used to access /proc.
303 304 //
304 305 // (Note that getpid() on LinuxThreads returns kernel thread id too; but
305 306 // on NPTL, it returns the same pid for all threads, as required by POSIX.)
306 307 //
307 308 pid_t os::Linux::gettid() {
308 309 int rslt = syscall(SYS_gettid);
309 310 if (rslt == -1) {
310 311 // old kernel, no NPTL support
311 312 return getpid();
312 313 } else {
313 314 return (pid_t)rslt;
314 315 }
315 316 }
316 317
317 318 // Most versions of linux have a bug where the number of processors are
318 319 // determined by looking at the /proc file system. In a chroot environment,
319 320 // the system call returns 1. This causes the VM to act as if it is
320 321 // a single processor and elide locking (see is_MP() call).
321 322 static bool unsafe_chroot_detected = false;
322 323 static const char *unstable_chroot_error = "/proc file system not found.\n"
323 324 "Java may be unstable running multithreaded in a chroot "
324 325 "environment on Linux when /proc filesystem is not mounted.";
325 326
326 327 void os::Linux::initialize_system_info() {
327 328 set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
328 329 if (processor_count() == 1) {
329 330 pid_t pid = os::Linux::gettid();
330 331 char fname[32];
331 332 jio_snprintf(fname, sizeof(fname), "/proc/%d", pid);
332 333 FILE *fp = fopen(fname, "r");
333 334 if (fp == NULL) {
334 335 unsafe_chroot_detected = true;
335 336 } else {
336 337 fclose(fp);
337 338 }
338 339 }
339 340 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
340 341 assert(processor_count() > 0, "linux error");
341 342 }
342 343
343 344 void os::init_system_properties_values() {
344 345 // char arch[12];
345 346 // sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
346 347
347 348 // The next steps are taken in the product version:
348 349 //
349 350 // Obtain the JAVA_HOME value from the location of libjvm[_g].so.
350 351 // This library should be located at:
351 352 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm[_g].so.
352 353 //
353 354 // If "/jre/lib/" appears at the right place in the path, then we
354 355 // assume libjvm[_g].so is installed in a JDK and we use this path.
355 356 //
356 357 // Otherwise exit with message: "Could not create the Java virtual machine."
357 358 //
358 359 // The following extra steps are taken in the debugging version:
359 360 //
360 361 // If "/jre/lib/" does NOT appear at the right place in the path
361 362 // instead of exit check for $JAVA_HOME environment variable.
362 363 //
363 364 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
364 365 // then we append a fake suffix "hotspot/libjvm[_g].so" to this path so
365 366 // it looks like libjvm[_g].so is installed there
366 367 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm[_g].so.
367 368 //
368 369 // Otherwise exit.
369 370 //
370 371 // Important note: if the location of libjvm.so changes this
371 372 // code needs to be changed accordingly.
372 373
373 374 // The next few definitions allow the code to be verbatim:
374 375 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
375 376 #define getenv(n) ::getenv(n)
376 377
377 378 /*
378 379 * See ld(1):
379 380 * The linker uses the following search paths to locate required
380 381 * shared libraries:
381 382 * 1: ...
382 383 * ...
383 384 * 7: The default directories, normally /lib and /usr/lib.
384 385 */
385 386 #if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390))
386 387 #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"
387 388 #else
388 389 #define DEFAULT_LIBPATH "/lib:/usr/lib"
389 390 #endif
390 391
391 392 #define EXTENSIONS_DIR "/lib/ext"
392 393 #define ENDORSED_DIR "/lib/endorsed"
393 394 #define REG_DIR "/usr/java/packages"
394 395
395 396 {
396 397 /* sysclasspath, java_home, dll_dir */
397 398 {
398 399 char *home_path;
399 400 char *dll_path;
400 401 char *pslash;
401 402 char buf[MAXPATHLEN];
402 403 os::jvm_path(buf, sizeof(buf));
403 404
404 405 // Found the full path to libjvm.so.
405 406 // Now cut the path to <java_home>/jre if we can.
406 407 *(strrchr(buf, '/')) = '\0'; /* get rid of /libjvm.so */
407 408 pslash = strrchr(buf, '/');
408 409 if (pslash != NULL)
409 410 *pslash = '\0'; /* get rid of /{client|server|hotspot} */
410 411 dll_path = malloc(strlen(buf) + 1);
411 412 if (dll_path == NULL)
412 413 return;
413 414 strcpy(dll_path, buf);
414 415 Arguments::set_dll_dir(dll_path);
415 416
416 417 if (pslash != NULL) {
417 418 pslash = strrchr(buf, '/');
418 419 if (pslash != NULL) {
419 420 *pslash = '\0'; /* get rid of /<arch> */
420 421 pslash = strrchr(buf, '/');
421 422 if (pslash != NULL)
422 423 *pslash = '\0'; /* get rid of /lib */
423 424 }
424 425 }
425 426
426 427 home_path = malloc(strlen(buf) + 1);
427 428 if (home_path == NULL)
428 429 return;
429 430 strcpy(home_path, buf);
430 431 Arguments::set_java_home(home_path);
431 432
432 433 if (!set_boot_path('/', ':'))
433 434 return;
434 435 }
435 436
436 437 /*
437 438 * Where to look for native libraries
438 439 *
439 440 * Note: Due to a legacy implementation, most of the library path
440 441 * is set in the launcher. This was to accomodate linking restrictions
441 442 * on legacy Linux implementations (which are no longer supported).
442 443 * Eventually, all the library path setting will be done here.
443 444 *
444 445 * However, to prevent the proliferation of improperly built native
445 446 * libraries, the new path component /usr/java/packages is added here.
446 447 * Eventually, all the library path setting will be done here.
447 448 */
448 449 {
449 450 char *ld_library_path;
450 451
451 452 /*
452 453 * Construct the invariant part of ld_library_path. Note that the
453 454 * space for the colon and the trailing null are provided by the
454 455 * nulls included by the sizeof operator (so actually we allocate
455 456 * a byte more than necessary).
456 457 */
457 458 ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
458 459 strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
459 460 sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
460 461
461 462 /*
462 463 * Get the user setting of LD_LIBRARY_PATH, and prepended it. It
463 464 * should always exist (until the legacy problem cited above is
464 465 * addressed).
465 466 */
466 467 char *v = getenv("LD_LIBRARY_PATH");
467 468 if (v != NULL) {
468 469 char *t = ld_library_path;
469 470 /* That's +1 for the colon and +1 for the trailing '\0' */
470 471 ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
471 472 sprintf(ld_library_path, "%s:%s", v, t);
472 473 }
473 474 Arguments::set_library_path(ld_library_path);
474 475 }
475 476
476 477 /*
477 478 * Extensions directories.
478 479 *
479 480 * Note that the space for the colon and the trailing null are provided
480 481 * by the nulls included by the sizeof operator (so actually one byte more
481 482 * than necessary is allocated).
482 483 */
483 484 {
484 485 char *buf = malloc(strlen(Arguments::get_java_home()) +
485 486 sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
486 487 sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
487 488 Arguments::get_java_home());
488 489 Arguments::set_ext_dirs(buf);
489 490 }
490 491
491 492 /* Endorsed standards default directory. */
492 493 {
493 494 char * buf;
494 495 buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
495 496 sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
496 497 Arguments::set_endorsed_dirs(buf);
497 498 }
498 499 }
499 500
500 501 #undef malloc
501 502 #undef getenv
502 503 #undef EXTENSIONS_DIR
503 504 #undef ENDORSED_DIR
504 505
505 506 // Done
506 507 return;
507 508 }
508 509
509 510 ////////////////////////////////////////////////////////////////////////////////
510 511 // breakpoint support
511 512
512 513 void os::breakpoint() {
513 514 BREAKPOINT;
514 515 }
515 516
516 517 extern "C" void breakpoint() {
517 518 // use debugger to set breakpoint here
518 519 }
519 520
520 521 ////////////////////////////////////////////////////////////////////////////////
521 522 // signal support
522 523
523 524 debug_only(static bool signal_sets_initialized = false);
524 525 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
525 526
526 527 bool os::Linux::is_sig_ignored(int sig) {
527 528 struct sigaction oact;
528 529 sigaction(sig, (struct sigaction*)NULL, &oact);
529 530 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction)
530 531 : CAST_FROM_FN_PTR(void*, oact.sa_handler);
531 532 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
532 533 return true;
533 534 else
534 535 return false;
535 536 }
536 537
537 538 void os::Linux::signal_sets_init() {
538 539 // Should also have an assertion stating we are still single-threaded.
539 540 assert(!signal_sets_initialized, "Already initialized");
540 541 // Fill in signals that are necessarily unblocked for all threads in
541 542 // the VM. Currently, we unblock the following signals:
542 543 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
543 544 // by -Xrs (=ReduceSignalUsage));
544 545 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
545 546 // other threads. The "ReduceSignalUsage" boolean tells us not to alter
546 547 // the dispositions or masks wrt these signals.
547 548 // Programs embedding the VM that want to use the above signals for their
548 549 // own purposes must, at this time, use the "-Xrs" option to prevent
549 550 // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
550 551 // (See bug 4345157, and other related bugs).
551 552 // In reality, though, unblocking these signals is really a nop, since
552 553 // these signals are not blocked by default.
553 554 sigemptyset(&unblocked_sigs);
554 555 sigemptyset(&allowdebug_blocked_sigs);
555 556 sigaddset(&unblocked_sigs, SIGILL);
556 557 sigaddset(&unblocked_sigs, SIGSEGV);
557 558 sigaddset(&unblocked_sigs, SIGBUS);
558 559 sigaddset(&unblocked_sigs, SIGFPE);
559 560 sigaddset(&unblocked_sigs, SR_signum);
560 561
561 562 if (!ReduceSignalUsage) {
562 563 if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
563 564 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
564 565 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
565 566 }
566 567 if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
567 568 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
568 569 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
569 570 }
570 571 if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
571 572 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
572 573 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
573 574 }
574 575 }
575 576 // Fill in signals that are blocked by all but the VM thread.
576 577 sigemptyset(&vm_sigs);
577 578 if (!ReduceSignalUsage)
578 579 sigaddset(&vm_sigs, BREAK_SIGNAL);
579 580 debug_only(signal_sets_initialized = true);
580 581
581 582 }
582 583
583 584 // These are signals that are unblocked while a thread is running Java.
584 585 // (For some reason, they get blocked by default.)
585 586 sigset_t* os::Linux::unblocked_signals() {
586 587 assert(signal_sets_initialized, "Not initialized");
587 588 return &unblocked_sigs;
588 589 }
589 590
590 591 // These are the signals that are blocked while a (non-VM) thread is
591 592 // running Java. Only the VM thread handles these signals.
592 593 sigset_t* os::Linux::vm_signals() {
593 594 assert(signal_sets_initialized, "Not initialized");
594 595 return &vm_sigs;
595 596 }
596 597
597 598 // These are signals that are blocked during cond_wait to allow debugger in
598 599 sigset_t* os::Linux::allowdebug_blocked_signals() {
599 600 assert(signal_sets_initialized, "Not initialized");
600 601 return &allowdebug_blocked_sigs;
601 602 }
602 603
603 604 void os::Linux::hotspot_sigmask(Thread* thread) {
604 605
605 606 //Save caller's signal mask before setting VM signal mask
606 607 sigset_t caller_sigmask;
607 608 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
608 609
609 610 OSThread* osthread = thread->osthread();
610 611 osthread->set_caller_sigmask(caller_sigmask);
611 612
612 613 pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL);
613 614
614 615 if (!ReduceSignalUsage) {
615 616 if (thread->is_VM_thread()) {
616 617 // Only the VM thread handles BREAK_SIGNAL ...
617 618 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
618 619 } else {
619 620 // ... all other threads block BREAK_SIGNAL
620 621 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
621 622 }
622 623 }
623 624 }
624 625
625 626 //////////////////////////////////////////////////////////////////////////////
626 627 // detecting pthread library
627 628
628 629 void os::Linux::libpthread_init() {
629 630 // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION
630 631 // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a
631 632 // generic name for earlier versions.
632 633 // Define macros here so we can build HotSpot on old systems.
633 634 # ifndef _CS_GNU_LIBC_VERSION
634 635 # define _CS_GNU_LIBC_VERSION 2
635 636 # endif
636 637 # ifndef _CS_GNU_LIBPTHREAD_VERSION
637 638 # define _CS_GNU_LIBPTHREAD_VERSION 3
638 639 # endif
639 640
640 641 size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0);
641 642 if (n > 0) {
642 643 char *str = (char *)malloc(n, mtInternal);
643 644 confstr(_CS_GNU_LIBC_VERSION, str, n);
644 645 os::Linux::set_glibc_version(str);
645 646 } else {
646 647 // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version()
647 648 static char _gnu_libc_version[32];
648 649 jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version),
649 650 "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release());
650 651 os::Linux::set_glibc_version(_gnu_libc_version);
651 652 }
652 653
653 654 n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);
654 655 if (n > 0) {
655 656 char *str = (char *)malloc(n, mtInternal);
656 657 confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);
657 658 // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells
658 659 // us "NPTL-0.29" even we are running with LinuxThreads. Check if this
659 660 // is the case. LinuxThreads has a hard limit on max number of threads.
660 661 // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value.
661 662 // On the other hand, NPTL does not have such a limit, sysconf()
662 663 // will return -1 and errno is not changed. Check if it is really NPTL.
663 664 if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 &&
664 665 strstr(str, "NPTL") &&
665 666 sysconf(_SC_THREAD_THREADS_MAX) > 0) {
666 667 free(str);
667 668 os::Linux::set_libpthread_version("linuxthreads");
668 669 } else {
669 670 os::Linux::set_libpthread_version(str);
670 671 }
671 672 } else {
672 673 // glibc before 2.3.2 only has LinuxThreads.
673 674 os::Linux::set_libpthread_version("linuxthreads");
674 675 }
675 676
676 677 if (strstr(libpthread_version(), "NPTL")) {
677 678 os::Linux::set_is_NPTL();
678 679 } else {
679 680 os::Linux::set_is_LinuxThreads();
680 681 }
681 682
682 683 // LinuxThreads have two flavors: floating-stack mode, which allows variable
683 684 // stack size; and fixed-stack mode. NPTL is always floating-stack.
684 685 if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) {
685 686 os::Linux::set_is_floating_stack();
686 687 }
687 688 }
688 689
689 690 /////////////////////////////////////////////////////////////////////////////
690 691 // thread stack
691 692
692 693 // Force Linux kernel to expand current thread stack. If "bottom" is close
693 694 // to the stack guard, caller should block all signals.
694 695 //
695 696 // MAP_GROWSDOWN:
696 697 // A special mmap() flag that is used to implement thread stacks. It tells
697 698 // kernel that the memory region should extend downwards when needed. This
698 699 // allows early versions of LinuxThreads to only mmap the first few pages
699 700 // when creating a new thread. Linux kernel will automatically expand thread
700 701 // stack as needed (on page faults).
701 702 //
702 703 // However, because the memory region of a MAP_GROWSDOWN stack can grow on
703 704 // demand, if a page fault happens outside an already mapped MAP_GROWSDOWN
704 705 // region, it's hard to tell if the fault is due to a legitimate stack
705 706 // access or because of reading/writing non-exist memory (e.g. buffer
706 707 // overrun). As a rule, if the fault happens below current stack pointer,
707 708 // Linux kernel does not expand stack, instead a SIGSEGV is sent to the
708 709 // application (see Linux kernel fault.c).
709 710 //
710 711 // This Linux feature can cause SIGSEGV when VM bangs thread stack for
711 712 // stack overflow detection.
712 713 //
713 714 // Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do
714 715 // not use this flag. However, the stack of initial thread is not created
715 716 // by pthread, it is still MAP_GROWSDOWN. Also it's possible (though
716 717 // unlikely) that user code can create a thread with MAP_GROWSDOWN stack
717 718 // and then attach the thread to JVM.
718 719 //
719 720 // To get around the problem and allow stack banging on Linux, we need to
720 721 // manually expand thread stack after receiving the SIGSEGV.
721 722 //
722 723 // There are two ways to expand thread stack to address "bottom", we used
723 724 // both of them in JVM before 1.5:
724 725 // 1. adjust stack pointer first so that it is below "bottom", and then
725 726 // touch "bottom"
726 727 // 2. mmap() the page in question
727 728 //
728 729 // Now alternate signal stack is gone, it's harder to use 2. For instance,
729 730 // if current sp is already near the lower end of page 101, and we need to
730 731 // call mmap() to map page 100, it is possible that part of the mmap() frame
731 732 // will be placed in page 100. When page 100 is mapped, it is zero-filled.
732 733 // That will destroy the mmap() frame and cause VM to crash.
733 734 //
734 735 // The following code works by adjusting sp first, then accessing the "bottom"
735 736 // page to force a page fault. Linux kernel will then automatically expand the
736 737 // stack mapping.
737 738 //
738 739 // _expand_stack_to() assumes its frame size is less than page size, which
739 740 // should always be true if the function is not inlined.
740 741
741 742 #if __GNUC__ < 3 // gcc 2.x does not support noinline attribute
742 743 #define NOINLINE
743 744 #else
744 745 #define NOINLINE __attribute__ ((noinline))
745 746 #endif
746 747
747 748 static void _expand_stack_to(address bottom) NOINLINE;
748 749
749 750 static void _expand_stack_to(address bottom) {
750 751 address sp;
751 752 size_t size;
752 753 volatile char *p;
753 754
754 755 // Adjust bottom to point to the largest address within the same page, it
755 756 // gives us a one-page buffer if alloca() allocates slightly more memory.
756 757 bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size());
757 758 bottom += os::Linux::page_size() - 1;
758 759
759 760 // sp might be slightly above current stack pointer; if that's the case, we
760 761 // will alloca() a little more space than necessary, which is OK. Don't use
761 762 // os::current_stack_pointer(), as its result can be slightly below current
762 763 // stack pointer, causing us to not alloca enough to reach "bottom".
763 764 sp = (address)&sp;
764 765
765 766 if (sp > bottom) {
766 767 size = sp - bottom;
767 768 p = (volatile char *)alloca(size);
768 769 assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?");
769 770 p[0] = '\0';
770 771 }
771 772 }
772 773
773 774 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) {
774 775 assert(t!=NULL, "just checking");
775 776 assert(t->osthread()->expanding_stack(), "expand should be set");
776 777 assert(t->stack_base() != NULL, "stack_base was not initialized");
777 778
778 779 if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) {
779 780 sigset_t mask_all, old_sigset;
780 781 sigfillset(&mask_all);
781 782 pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset);
782 783 _expand_stack_to(addr);
783 784 pthread_sigmask(SIG_SETMASK, &old_sigset, NULL);
784 785 return true;
785 786 }
786 787 return false;
787 788 }
788 789
789 790 //////////////////////////////////////////////////////////////////////////////
790 791 // create new thread
791 792
792 793 static address highest_vm_reserved_address();
793 794
794 795 // check if it's safe to start a new thread
795 796 static bool _thread_safety_check(Thread* thread) {
796 797 if (os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack()) {
797 798 // Fixed stack LinuxThreads (SuSE Linux/x86, and some versions of Redhat)
798 799 // Heap is mmap'ed at lower end of memory space. Thread stacks are
799 800 // allocated (MAP_FIXED) from high address space. Every thread stack
800 801 // occupies a fixed size slot (usually 2Mbytes, but user can change
801 802 // it to other values if they rebuild LinuxThreads).
802 803 //
803 804 // Problem with MAP_FIXED is that mmap() can still succeed even part of
804 805 // the memory region has already been mmap'ed. That means if we have too
805 806 // many threads and/or very large heap, eventually thread stack will
806 807 // collide with heap.
807 808 //
808 809 // Here we try to prevent heap/stack collision by comparing current
809 810 // stack bottom with the highest address that has been mmap'ed by JVM
810 811 // plus a safety margin for memory maps created by native code.
811 812 //
812 813 // This feature can be disabled by setting ThreadSafetyMargin to 0
813 814 //
814 815 if (ThreadSafetyMargin > 0) {
815 816 address stack_bottom = os::current_stack_base() - os::current_stack_size();
816 817
817 818 // not safe if our stack extends below the safety margin
818 819 return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address();
819 820 } else {
820 821 return true;
821 822 }
822 823 } else {
823 824 // Floating stack LinuxThreads or NPTL:
824 825 // Unlike fixed stack LinuxThreads, thread stacks are not MAP_FIXED. When
825 826 // there's not enough space left, pthread_create() will fail. If we come
826 827 // here, that means enough space has been reserved for stack.
827 828 return true;
828 829 }
829 830 }
830 831
831 832 // Thread start routine for all newly created threads
832 833 static void *java_start(Thread *thread) {
833 834 // Try to randomize the cache line index of hot stack frames.
834 835 // This helps when threads of the same stack traces evict each other's
835 836 // cache lines. The threads can be either from the same JVM instance, or
836 837 // from different JVM instances. The benefit is especially true for
837 838 // processors with hyperthreading technology.
838 839 static int counter = 0;
839 840 int pid = os::current_process_id();
840 841 alloca(((pid ^ counter++) & 7) * 128);
841 842
842 843 ThreadLocalStorage::set_thread(thread);
843 844
844 845 OSThread* osthread = thread->osthread();
845 846 Monitor* sync = osthread->startThread_lock();
846 847
847 848 // non floating stack LinuxThreads needs extra check, see above
848 849 if (!_thread_safety_check(thread)) {
849 850 // notify parent thread
850 851 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
851 852 osthread->set_state(ZOMBIE);
852 853 sync->notify_all();
853 854 return NULL;
854 855 }
855 856
856 857 // thread_id is kernel thread id (similar to Solaris LWP id)
857 858 osthread->set_thread_id(os::Linux::gettid());
858 859
859 860 if (UseNUMA) {
860 861 int lgrp_id = os::numa_get_group_id();
861 862 if (lgrp_id != -1) {
862 863 thread->set_lgrp_id(lgrp_id);
863 864 }
864 865 }
865 866 // initialize signal mask for this thread
866 867 os::Linux::hotspot_sigmask(thread);
867 868
868 869 // initialize floating point control register
869 870 os::Linux::init_thread_fpu_state();
870 871
871 872 // handshaking with parent thread
872 873 {
873 874 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
874 875
875 876 // notify parent thread
876 877 osthread->set_state(INITIALIZED);
877 878 sync->notify_all();
878 879
879 880 // wait until os::start_thread()
880 881 while (osthread->get_state() == INITIALIZED) {
881 882 sync->wait(Mutex::_no_safepoint_check_flag);
882 883 }
883 884 }
884 885
885 886 // call one more level start routine
886 887 thread->run();
887 888
888 889 return 0;
889 890 }
890 891
891 892 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
892 893 assert(thread->osthread() == NULL, "caller responsible");
893 894
894 895 // Allocate the OSThread object
895 896 OSThread* osthread = new OSThread(NULL, NULL);
896 897 if (osthread == NULL) {
897 898 return false;
898 899 }
899 900
900 901 // set the correct thread state
901 902 osthread->set_thread_type(thr_type);
902 903
903 904 // Initial state is ALLOCATED but not INITIALIZED
904 905 osthread->set_state(ALLOCATED);
905 906
906 907 thread->set_osthread(osthread);
907 908
908 909 // init thread attributes
909 910 pthread_attr_t attr;
910 911 pthread_attr_init(&attr);
911 912 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
912 913
913 914 // stack size
914 915 if (os::Linux::supports_variable_stack_size()) {
915 916 // calculate stack size if it's not specified by caller
916 917 if (stack_size == 0) {
917 918 stack_size = os::Linux::default_stack_size(thr_type);
918 919
919 920 switch (thr_type) {
920 921 case os::java_thread:
921 922 // Java threads use ThreadStackSize which default value can be
922 923 // changed with the flag -Xss
923 924 assert (JavaThread::stack_size_at_create() > 0, "this should be set");
924 925 stack_size = JavaThread::stack_size_at_create();
925 926 break;
926 927 case os::compiler_thread:
927 928 if (CompilerThreadStackSize > 0) {
928 929 stack_size = (size_t)(CompilerThreadStackSize * K);
929 930 break;
930 931 } // else fall through:
931 932 // use VMThreadStackSize if CompilerThreadStackSize is not defined
932 933 case os::vm_thread:
933 934 case os::pgc_thread:
934 935 case os::cgc_thread:
935 936 case os::watcher_thread:
936 937 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
937 938 break;
938 939 }
939 940 }
940 941
941 942 stack_size = MAX2(stack_size, os::Linux::min_stack_allowed);
942 943 pthread_attr_setstacksize(&attr, stack_size);
943 944 } else {
944 945 // let pthread_create() pick the default value.
945 946 }
946 947
947 948 // glibc guard page
948 949 pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type));
949 950
950 951 ThreadState state;
951 952
952 953 {
953 954 // Serialize thread creation if we are running with fixed stack LinuxThreads
954 955 bool lock = os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack();
955 956 if (lock) {
956 957 os::Linux::createThread_lock()->lock_without_safepoint_check();
957 958 }
958 959
959 960 pthread_t tid;
960 961 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
961 962
962 963 pthread_attr_destroy(&attr);
963 964
964 965 if (ret != 0) {
965 966 if (PrintMiscellaneous && (Verbose || WizardMode)) {
966 967 perror("pthread_create()");
967 968 }
968 969 // Need to clean up stuff we've allocated so far
969 970 thread->set_osthread(NULL);
970 971 delete osthread;
971 972 if (lock) os::Linux::createThread_lock()->unlock();
972 973 return false;
973 974 }
974 975
975 976 // Store pthread info into the OSThread
976 977 osthread->set_pthread_id(tid);
977 978
978 979 // Wait until child thread is either initialized or aborted
979 980 {
980 981 Monitor* sync_with_child = osthread->startThread_lock();
981 982 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
982 983 while ((state = osthread->get_state()) == ALLOCATED) {
983 984 sync_with_child->wait(Mutex::_no_safepoint_check_flag);
984 985 }
985 986 }
986 987
987 988 if (lock) {
988 989 os::Linux::createThread_lock()->unlock();
989 990 }
990 991 }
991 992
992 993 // Aborted due to thread limit being reached
993 994 if (state == ZOMBIE) {
994 995 thread->set_osthread(NULL);
995 996 delete osthread;
996 997 return false;
997 998 }
998 999
999 1000 // The thread is returned suspended (in state INITIALIZED),
1000 1001 // and is started higher up in the call chain
1001 1002 assert(state == INITIALIZED, "race condition");
1002 1003 return true;
1003 1004 }
1004 1005
1005 1006 /////////////////////////////////////////////////////////////////////////////
1006 1007 // attach existing thread
1007 1008
1008 1009 // bootstrap the main thread
1009 1010 bool os::create_main_thread(JavaThread* thread) {
1010 1011 assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread");
1011 1012 return create_attached_thread(thread);
1012 1013 }
1013 1014
1014 1015 bool os::create_attached_thread(JavaThread* thread) {
1015 1016 #ifdef ASSERT
1016 1017 thread->verify_not_published();
1017 1018 #endif
1018 1019
1019 1020 // Allocate the OSThread object
1020 1021 OSThread* osthread = new OSThread(NULL, NULL);
1021 1022
1022 1023 if (osthread == NULL) {
1023 1024 return false;
1024 1025 }
1025 1026
1026 1027 // Store pthread info into the OSThread
1027 1028 osthread->set_thread_id(os::Linux::gettid());
1028 1029 osthread->set_pthread_id(::pthread_self());
1029 1030
1030 1031 // initialize floating point control register
1031 1032 os::Linux::init_thread_fpu_state();
1032 1033
1033 1034 // Initial thread state is RUNNABLE
1034 1035 osthread->set_state(RUNNABLE);
1035 1036
1036 1037 thread->set_osthread(osthread);
1037 1038
1038 1039 if (UseNUMA) {
1039 1040 int lgrp_id = os::numa_get_group_id();
1040 1041 if (lgrp_id != -1) {
1041 1042 thread->set_lgrp_id(lgrp_id);
1042 1043 }
1043 1044 }
1044 1045
1045 1046 if (os::Linux::is_initial_thread()) {
1046 1047 // If current thread is initial thread, its stack is mapped on demand,
1047 1048 // see notes about MAP_GROWSDOWN. Here we try to force kernel to map
1048 1049 // the entire stack region to avoid SEGV in stack banging.
1049 1050 // It is also useful to get around the heap-stack-gap problem on SuSE
1050 1051 // kernel (see 4821821 for details). We first expand stack to the top
1051 1052 // of yellow zone, then enable stack yellow zone (order is significant,
1052 1053 // enabling yellow zone first will crash JVM on SuSE Linux), so there
1053 1054 // is no gap between the last two virtual memory regions.
1054 1055
1055 1056 JavaThread *jt = (JavaThread *)thread;
1056 1057 address addr = jt->stack_yellow_zone_base();
1057 1058 assert(addr != NULL, "initialization problem?");
1058 1059 assert(jt->stack_available(addr) > 0, "stack guard should not be enabled");
1059 1060
1060 1061 osthread->set_expanding_stack();
1061 1062 os::Linux::manually_expand_stack(jt, addr);
1062 1063 osthread->clear_expanding_stack();
1063 1064 }
1064 1065
1065 1066 // initialize signal mask for this thread
1066 1067 // and save the caller's signal mask
1067 1068 os::Linux::hotspot_sigmask(thread);
1068 1069
1069 1070 return true;
1070 1071 }
1071 1072
1072 1073 void os::pd_start_thread(Thread* thread) {
1073 1074 OSThread * osthread = thread->osthread();
1074 1075 assert(osthread->get_state() != INITIALIZED, "just checking");
1075 1076 Monitor* sync_with_child = osthread->startThread_lock();
1076 1077 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
1077 1078 sync_with_child->notify();
1078 1079 }
1079 1080
1080 1081 // Free Linux resources related to the OSThread
1081 1082 void os::free_thread(OSThread* osthread) {
1082 1083 assert(osthread != NULL, "osthread not set");
1083 1084
1084 1085 if (Thread::current()->osthread() == osthread) {
1085 1086 // Restore caller's signal mask
1086 1087 sigset_t sigmask = osthread->caller_sigmask();
1087 1088 pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
1088 1089 }
1089 1090
1090 1091 delete osthread;
1091 1092 }
1092 1093
1093 1094 //////////////////////////////////////////////////////////////////////////////
1094 1095 // thread local storage
1095 1096
1096 1097 int os::allocate_thread_local_storage() {
1097 1098 pthread_key_t key;
1098 1099 int rslt = pthread_key_create(&key, NULL);
1099 1100 assert(rslt == 0, "cannot allocate thread local storage");
1100 1101 return (int)key;
1101 1102 }
1102 1103
1103 1104 // Note: This is currently not used by VM, as we don't destroy TLS key
1104 1105 // on VM exit.
1105 1106 void os::free_thread_local_storage(int index) {
1106 1107 int rslt = pthread_key_delete((pthread_key_t)index);
1107 1108 assert(rslt == 0, "invalid index");
1108 1109 }
1109 1110
1110 1111 void os::thread_local_storage_at_put(int index, void* value) {
1111 1112 int rslt = pthread_setspecific((pthread_key_t)index, value);
1112 1113 assert(rslt == 0, "pthread_setspecific failed");
1113 1114 }
1114 1115
1115 1116 extern "C" Thread* get_thread() {
1116 1117 return ThreadLocalStorage::thread();
1117 1118 }
1118 1119
1119 1120 //////////////////////////////////////////////////////////////////////////////
1120 1121 // initial thread
1121 1122
1122 1123 // Check if current thread is the initial thread, similar to Solaris thr_main.
1123 1124 bool os::Linux::is_initial_thread(void) {
1124 1125 char dummy;
1125 1126 // If called before init complete, thread stack bottom will be null.
1126 1127 // Can be called if fatal error occurs before initialization.
1127 1128 if (initial_thread_stack_bottom() == NULL) return false;
1128 1129 assert(initial_thread_stack_bottom() != NULL &&
1129 1130 initial_thread_stack_size() != 0,
1130 1131 "os::init did not locate initial thread's stack region");
1131 1132 if ((address)&dummy >= initial_thread_stack_bottom() &&
1132 1133 (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size())
1133 1134 return true;
1134 1135 else return false;
1135 1136 }
1136 1137
1137 1138 // Find the virtual memory area that contains addr
1138 1139 static bool find_vma(address addr, address* vma_low, address* vma_high) {
1139 1140 FILE *fp = fopen("/proc/self/maps", "r");
1140 1141 if (fp) {
1141 1142 address low, high;
1142 1143 while (!feof(fp)) {
1143 1144 if (fscanf(fp, "%p-%p", &low, &high) == 2) {
1144 1145 if (low <= addr && addr < high) {
1145 1146 if (vma_low) *vma_low = low;
1146 1147 if (vma_high) *vma_high = high;
1147 1148 fclose (fp);
1148 1149 return true;
1149 1150 }
1150 1151 }
1151 1152 for (;;) {
1152 1153 int ch = fgetc(fp);
1153 1154 if (ch == EOF || ch == (int)'\n') break;
1154 1155 }
1155 1156 }
1156 1157 fclose(fp);
1157 1158 }
1158 1159 return false;
1159 1160 }
1160 1161
1161 1162 // Locate initial thread stack. This special handling of initial thread stack
1162 1163 // is needed because pthread_getattr_np() on most (all?) Linux distros returns
1163 1164 // bogus value for initial thread.
1164 1165 void os::Linux::capture_initial_stack(size_t max_size) {
1165 1166 // stack size is the easy part, get it from RLIMIT_STACK
1166 1167 size_t stack_size;
1167 1168 struct rlimit rlim;
1168 1169 getrlimit(RLIMIT_STACK, &rlim);
1169 1170 stack_size = rlim.rlim_cur;
1170 1171
1171 1172 // 6308388: a bug in ld.so will relocate its own .data section to the
1172 1173 // lower end of primordial stack; reduce ulimit -s value a little bit
1173 1174 // so we won't install guard page on ld.so's data section.
1174 1175 stack_size -= 2 * page_size();
1175 1176
1176 1177 // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat
1177 1178 // 7.1, in both cases we will get 2G in return value.
1178 1179 // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0,
1179 1180 // SuSE 7.2, Debian) can not handle alternate signal stack correctly
1180 1181 // for initial thread if its stack size exceeds 6M. Cap it at 2M,
1181 1182 // in case other parts in glibc still assumes 2M max stack size.
1182 1183 // FIXME: alt signal stack is gone, maybe we can relax this constraint?
1183 1184 #ifndef IA64
1184 1185 if (stack_size > 2 * K * K) stack_size = 2 * K * K;
1185 1186 #else
1186 1187 // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small
1187 1188 if (stack_size > 4 * K * K) stack_size = 4 * K * K;
1188 1189 #endif
1189 1190
1190 1191 // Try to figure out where the stack base (top) is. This is harder.
1191 1192 //
1192 1193 // When an application is started, glibc saves the initial stack pointer in
1193 1194 // a global variable "__libc_stack_end", which is then used by system
1194 1195 // libraries. __libc_stack_end should be pretty close to stack top. The
1195 1196 // variable is available since the very early days. However, because it is
1196 1197 // a private interface, it could disappear in the future.
1197 1198 //
1198 1199 // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar
1199 1200 // to __libc_stack_end, it is very close to stack top, but isn't the real
1200 1201 // stack top. Note that /proc may not exist if VM is running as a chroot
1201 1202 // program, so reading /proc/<pid>/stat could fail. Also the contents of
1202 1203 // /proc/<pid>/stat could change in the future (though unlikely).
1203 1204 //
1204 1205 // We try __libc_stack_end first. If that doesn't work, look for
1205 1206 // /proc/<pid>/stat. If neither of them works, we use current stack pointer
1206 1207 // as a hint, which should work well in most cases.
1207 1208
1208 1209 uintptr_t stack_start;
1209 1210
1210 1211 // try __libc_stack_end first
1211 1212 uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end");
1212 1213 if (p && *p) {
1213 1214 stack_start = *p;
1214 1215 } else {
1215 1216 // see if we can get the start_stack field from /proc/self/stat
1216 1217 FILE *fp;
1217 1218 int pid;
1218 1219 char state;
1219 1220 int ppid;
1220 1221 int pgrp;
1221 1222 int session;
1222 1223 int nr;
1223 1224 int tpgrp;
1224 1225 unsigned long flags;
1225 1226 unsigned long minflt;
1226 1227 unsigned long cminflt;
1227 1228 unsigned long majflt;
1228 1229 unsigned long cmajflt;
1229 1230 unsigned long utime;
1230 1231 unsigned long stime;
1231 1232 long cutime;
1232 1233 long cstime;
1233 1234 long prio;
1234 1235 long nice;
1235 1236 long junk;
1236 1237 long it_real;
1237 1238 uintptr_t start;
1238 1239 uintptr_t vsize;
1239 1240 intptr_t rss;
1240 1241 uintptr_t rsslim;
1241 1242 uintptr_t scodes;
1242 1243 uintptr_t ecode;
1243 1244 int i;
1244 1245
1245 1246 // Figure what the primordial thread stack base is. Code is inspired
1246 1247 // by email from Hans Boehm. /proc/self/stat begins with current pid,
1247 1248 // followed by command name surrounded by parentheses, state, etc.
1248 1249 char stat[2048];
1249 1250 int statlen;
1250 1251
1251 1252 fp = fopen("/proc/self/stat", "r");
1252 1253 if (fp) {
1253 1254 statlen = fread(stat, 1, 2047, fp);
1254 1255 stat[statlen] = '\0';
1255 1256 fclose(fp);
1256 1257
1257 1258 // Skip pid and the command string. Note that we could be dealing with
1258 1259 // weird command names, e.g. user could decide to rename java launcher
1259 1260 // to "java 1.4.2 :)", then the stat file would look like
1260 1261 // 1234 (java 1.4.2 :)) R ... ...
1261 1262 // We don't really need to know the command string, just find the last
1262 1263 // occurrence of ")" and then start parsing from there. See bug 4726580.
1263 1264 char * s = strrchr(stat, ')');
1264 1265
1265 1266 i = 0;
1266 1267 if (s) {
1267 1268 // Skip blank chars
1268 1269 do s++; while (isspace(*s));
1269 1270
1270 1271 #define _UFM UINTX_FORMAT
1271 1272 #define _DFM INTX_FORMAT
1272 1273
1273 1274 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */
1274 1275 /* 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 */
1275 1276 i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM,
1276 1277 &state, /* 3 %c */
1277 1278 &ppid, /* 4 %d */
1278 1279 &pgrp, /* 5 %d */
1279 1280 &session, /* 6 %d */
1280 1281 &nr, /* 7 %d */
1281 1282 &tpgrp, /* 8 %d */
1282 1283 &flags, /* 9 %lu */
1283 1284 &minflt, /* 10 %lu */
1284 1285 &cminflt, /* 11 %lu */
1285 1286 &majflt, /* 12 %lu */
1286 1287 &cmajflt, /* 13 %lu */
1287 1288 &utime, /* 14 %lu */
1288 1289 &stime, /* 15 %lu */
1289 1290 &cutime, /* 16 %ld */
1290 1291 &cstime, /* 17 %ld */
1291 1292 &prio, /* 18 %ld */
1292 1293 &nice, /* 19 %ld */
1293 1294 &junk, /* 20 %ld */
1294 1295 &it_real, /* 21 %ld */
1295 1296 &start, /* 22 UINTX_FORMAT */
1296 1297 &vsize, /* 23 UINTX_FORMAT */
1297 1298 &rss, /* 24 INTX_FORMAT */
1298 1299 &rsslim, /* 25 UINTX_FORMAT */
1299 1300 &scodes, /* 26 UINTX_FORMAT */
1300 1301 &ecode, /* 27 UINTX_FORMAT */
1301 1302 &stack_start); /* 28 UINTX_FORMAT */
1302 1303 }
1303 1304
1304 1305 #undef _UFM
1305 1306 #undef _DFM
1306 1307
1307 1308 if (i != 28 - 2) {
1308 1309 assert(false, "Bad conversion from /proc/self/stat");
1309 1310 // product mode - assume we are the initial thread, good luck in the
1310 1311 // embedded case.
1311 1312 warning("Can't detect initial thread stack location - bad conversion");
1312 1313 stack_start = (uintptr_t) &rlim;
1313 1314 }
1314 1315 } else {
1315 1316 // For some reason we can't open /proc/self/stat (for example, running on
1316 1317 // FreeBSD with a Linux emulator, or inside chroot), this should work for
1317 1318 // most cases, so don't abort:
1318 1319 warning("Can't detect initial thread stack location - no /proc/self/stat");
1319 1320 stack_start = (uintptr_t) &rlim;
1320 1321 }
1321 1322 }
1322 1323
1323 1324 // Now we have a pointer (stack_start) very close to the stack top, the
1324 1325 // next thing to do is to figure out the exact location of stack top. We
1325 1326 // can find out the virtual memory area that contains stack_start by
1326 1327 // reading /proc/self/maps, it should be the last vma in /proc/self/maps,
1327 1328 // and its upper limit is the real stack top. (again, this would fail if
1328 1329 // running inside chroot, because /proc may not exist.)
1329 1330
1330 1331 uintptr_t stack_top;
1331 1332 address low, high;
1332 1333 if (find_vma((address)stack_start, &low, &high)) {
1333 1334 // success, "high" is the true stack top. (ignore "low", because initial
1334 1335 // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)
1335 1336 stack_top = (uintptr_t)high;
1336 1337 } else {
1337 1338 // failed, likely because /proc/self/maps does not exist
1338 1339 warning("Can't detect initial thread stack location - find_vma failed");
1339 1340 // best effort: stack_start is normally within a few pages below the real
1340 1341 // stack top, use it as stack top, and reduce stack size so we won't put
1341 1342 // guard page outside stack.
1342 1343 stack_top = stack_start;
1343 1344 stack_size -= 16 * page_size();
1344 1345 }
1345 1346
1346 1347 // stack_top could be partially down the page so align it
1347 1348 stack_top = align_size_up(stack_top, page_size());
1348 1349
1349 1350 if (max_size && stack_size > max_size) {
1350 1351 _initial_thread_stack_size = max_size;
1351 1352 } else {
1352 1353 _initial_thread_stack_size = stack_size;
1353 1354 }
1354 1355
1355 1356 _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size());
1356 1357 _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;
1357 1358 }
1358 1359
1359 1360 ////////////////////////////////////////////////////////////////////////////////
1360 1361 // time support
1361 1362
1362 1363 // Time since start-up in seconds to a fine granularity.
1363 1364 // Used by VMSelfDestructTimer and the MemProfiler.
1364 1365 double os::elapsedTime() {
1365 1366
1366 1367 return (double)(os::elapsed_counter()) * 0.000001;
1367 1368 }
1368 1369
1369 1370 jlong os::elapsed_counter() {
1370 1371 timeval time;
1371 1372 int status = gettimeofday(&time, NULL);
1372 1373 return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
1373 1374 }
1374 1375
1375 1376 jlong os::elapsed_frequency() {
1376 1377 return (1000 * 1000);
1377 1378 }
1378 1379
1379 1380 // For now, we say that linux does not support vtime. I have no idea
1380 1381 // whether it can actually be made to (DLD, 9/13/05).
1381 1382
1382 1383 bool os::supports_vtime() { return false; }
1383 1384 bool os::enable_vtime() { return false; }
1384 1385 bool os::vtime_enabled() { return false; }
1385 1386 double os::elapsedVTime() {
1386 1387 // better than nothing, but not much
1387 1388 return elapsedTime();
1388 1389 }
1389 1390
1390 1391 jlong os::javaTimeMillis() {
1391 1392 timeval time;
1392 1393 int status = gettimeofday(&time, NULL);
1393 1394 assert(status != -1, "linux error");
1394 1395 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);
1395 1396 }
1396 1397
1397 1398 #ifndef CLOCK_MONOTONIC
1398 1399 #define CLOCK_MONOTONIC (1)
1399 1400 #endif
1400 1401
1401 1402 void os::Linux::clock_init() {
1402 1403 // we do dlopen's in this particular order due to bug in linux
1403 1404 // dynamical loader (see 6348968) leading to crash on exit
1404 1405 void* handle = dlopen("librt.so.1", RTLD_LAZY);
1405 1406 if (handle == NULL) {
1406 1407 handle = dlopen("librt.so", RTLD_LAZY);
1407 1408 }
1408 1409
1409 1410 if (handle) {
1410 1411 int (*clock_getres_func)(clockid_t, struct timespec*) =
1411 1412 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres");
1412 1413 int (*clock_gettime_func)(clockid_t, struct timespec*) =
1413 1414 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime");
1414 1415 if (clock_getres_func && clock_gettime_func) {
1415 1416 // See if monotonic clock is supported by the kernel. Note that some
1416 1417 // early implementations simply return kernel jiffies (updated every
1417 1418 // 1/100 or 1/1000 second). It would be bad to use such a low res clock
1418 1419 // for nano time (though the monotonic property is still nice to have).
1419 1420 // It's fixed in newer kernels, however clock_getres() still returns
1420 1421 // 1/HZ. We check if clock_getres() works, but will ignore its reported
1421 1422 // resolution for now. Hopefully as people move to new kernels, this
1422 1423 // won't be a problem.
1423 1424 struct timespec res;
1424 1425 struct timespec tp;
1425 1426 if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 &&
1426 1427 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) {
1427 1428 // yes, monotonic clock is supported
1428 1429 _clock_gettime = clock_gettime_func;
1429 1430 } else {
1430 1431 // close librt if there is no monotonic clock
1431 1432 dlclose(handle);
1432 1433 }
1433 1434 }
1434 1435 }
1435 1436 }
1436 1437
1437 1438 #ifndef SYS_clock_getres
1438 1439
1439 1440 #if defined(IA32) || defined(AMD64)
1440 1441 #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229)
1441 1442 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y)
1442 1443 #else
1443 1444 #warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time"
1444 1445 #define sys_clock_getres(x,y) -1
1445 1446 #endif
1446 1447
1447 1448 #else
1448 1449 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y)
1449 1450 #endif
1450 1451
1451 1452 void os::Linux::fast_thread_clock_init() {
1452 1453 if (!UseLinuxPosixThreadCPUClocks) {
1453 1454 return;
1454 1455 }
1455 1456 clockid_t clockid;
1456 1457 struct timespec tp;
1457 1458 int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) =
1458 1459 (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");
1459 1460
1460 1461 // Switch to using fast clocks for thread cpu time if
1461 1462 // the sys_clock_getres() returns 0 error code.
1462 1463 // Note, that some kernels may support the current thread
1463 1464 // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks
1464 1465 // returned by the pthread_getcpuclockid().
1465 1466 // If the fast Posix clocks are supported then the sys_clock_getres()
1466 1467 // must return at least tp.tv_sec == 0 which means a resolution
1467 1468 // better than 1 sec. This is extra check for reliability.
1468 1469
1469 1470 if(pthread_getcpuclockid_func &&
1470 1471 pthread_getcpuclockid_func(_main_thread, &clockid) == 0 &&
1471 1472 sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) {
1472 1473
1473 1474 _supports_fast_thread_cpu_time = true;
1474 1475 _pthread_getcpuclockid = pthread_getcpuclockid_func;
1475 1476 }
1476 1477 }
1477 1478
1478 1479 jlong os::javaTimeNanos() {
1479 1480 if (Linux::supports_monotonic_clock()) {
1480 1481 struct timespec tp;
1481 1482 int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp);
1482 1483 assert(status == 0, "gettime error");
1483 1484 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
1484 1485 return result;
1485 1486 } else {
1486 1487 timeval time;
1487 1488 int status = gettimeofday(&time, NULL);
1488 1489 assert(status != -1, "linux error");
1489 1490 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
1490 1491 return 1000 * usecs;
1491 1492 }
1492 1493 }
1493 1494
1494 1495 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1495 1496 if (Linux::supports_monotonic_clock()) {
1496 1497 info_ptr->max_value = ALL_64_BITS;
1497 1498
1498 1499 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1499 1500 info_ptr->may_skip_backward = false; // not subject to resetting or drifting
1500 1501 info_ptr->may_skip_forward = false; // not subject to resetting or drifting
1501 1502 } else {
1502 1503 // gettimeofday - based on time in seconds since the Epoch thus does not wrap
1503 1504 info_ptr->max_value = ALL_64_BITS;
1504 1505
1505 1506 // gettimeofday is a real time clock so it skips
1506 1507 info_ptr->may_skip_backward = true;
1507 1508 info_ptr->may_skip_forward = true;
1508 1509 }
1509 1510
1510 1511 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
1511 1512 }
1512 1513
1513 1514 // Return the real, user, and system times in seconds from an
1514 1515 // arbitrary fixed point in the past.
1515 1516 bool os::getTimesSecs(double* process_real_time,
1516 1517 double* process_user_time,
1517 1518 double* process_system_time) {
1518 1519 struct tms ticks;
1519 1520 clock_t real_ticks = times(&ticks);
1520 1521
1521 1522 if (real_ticks == (clock_t) (-1)) {
1522 1523 return false;
1523 1524 } else {
1524 1525 double ticks_per_second = (double) clock_tics_per_sec;
1525 1526 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1526 1527 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1527 1528 *process_real_time = ((double) real_ticks) / ticks_per_second;
1528 1529
1529 1530 return true;
1530 1531 }
1531 1532 }
1532 1533
1533 1534
1534 1535 char * os::local_time_string(char *buf, size_t buflen) {
1535 1536 struct tm t;
1536 1537 time_t long_time;
1537 1538 time(&long_time);
1538 1539 localtime_r(&long_time, &t);
1539 1540 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1540 1541 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1541 1542 t.tm_hour, t.tm_min, t.tm_sec);
1542 1543 return buf;
1543 1544 }
1544 1545
1545 1546 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
1546 1547 return localtime_r(clock, res);
1547 1548 }
1548 1549
1549 1550 ////////////////////////////////////////////////////////////////////////////////
1550 1551 // runtime exit support
1551 1552
1552 1553 // Note: os::shutdown() might be called very early during initialization, or
1553 1554 // called from signal handler. Before adding something to os::shutdown(), make
1554 1555 // sure it is async-safe and can handle partially initialized VM.
1555 1556 void os::shutdown() {
1556 1557
1557 1558 // allow PerfMemory to attempt cleanup of any persistent resources
1558 1559 perfMemory_exit();
1559 1560
1560 1561 // needs to remove object in file system
1561 1562 AttachListener::abort();
1562 1563
1563 1564 // flush buffered output, finish log files
1564 1565 ostream_abort();
1565 1566
1566 1567 // Check for abort hook
1567 1568 abort_hook_t abort_hook = Arguments::abort_hook();
1568 1569 if (abort_hook != NULL) {
1569 1570 abort_hook();
1570 1571 }
1571 1572
1572 1573 }
1573 1574
1574 1575 // Note: os::abort() might be called very early during initialization, or
1575 1576 // called from signal handler. Before adding something to os::abort(), make
1576 1577 // sure it is async-safe and can handle partially initialized VM.
1577 1578 void os::abort(bool dump_core) {
1578 1579 os::shutdown();
1579 1580 if (dump_core) {
1580 1581 #ifndef PRODUCT
1581 1582 fdStream out(defaultStream::output_fd());
1582 1583 out.print_raw("Current thread is ");
1583 1584 char buf[16];
1584 1585 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1585 1586 out.print_raw_cr(buf);
1586 1587 out.print_raw_cr("Dumping core ...");
1587 1588 #endif
1588 1589 ::abort(); // dump core
1589 1590 }
1590 1591
1591 1592 ::exit(1);
1592 1593 }
1593 1594
1594 1595 // Die immediately, no exit hook, no abort hook, no cleanup.
1595 1596 void os::die() {
1596 1597 // _exit() on LinuxThreads only kills current thread
1597 1598 ::abort();
1598 1599 }
1599 1600
1600 1601 // unused on linux for now.
1601 1602 void os::set_error_file(const char *logfile) {}
1602 1603
1603 1604
1604 1605 // This method is a copy of JDK's sysGetLastErrorString
1605 1606 // from src/solaris/hpi/src/system_md.c
1606 1607
1607 1608 size_t os::lasterror(char *buf, size_t len) {
1608 1609
1609 1610 if (errno == 0) return 0;
1610 1611
1611 1612 const char *s = ::strerror(errno);
1612 1613 size_t n = ::strlen(s);
1613 1614 if (n >= len) {
1614 1615 n = len - 1;
1615 1616 }
1616 1617 ::strncpy(buf, s, n);
1617 1618 buf[n] = '\0';
1618 1619 return n;
1619 1620 }
1620 1621
1621 1622 intx os::current_thread_id() { return (intx)pthread_self(); }
1622 1623 int os::current_process_id() {
1623 1624
1624 1625 // Under the old linux thread library, linux gives each thread
1625 1626 // its own process id. Because of this each thread will return
1626 1627 // a different pid if this method were to return the result
1627 1628 // of getpid(2). Linux provides no api that returns the pid
1628 1629 // of the launcher thread for the vm. This implementation
1629 1630 // returns a unique pid, the pid of the launcher thread
1630 1631 // that starts the vm 'process'.
1631 1632
1632 1633 // Under the NPTL, getpid() returns the same pid as the
1633 1634 // launcher thread rather than a unique pid per thread.
1634 1635 // Use gettid() if you want the old pre NPTL behaviour.
1635 1636
1636 1637 // if you are looking for the result of a call to getpid() that
1637 1638 // returns a unique pid for the calling thread, then look at the
1638 1639 // OSThread::thread_id() method in osThread_linux.hpp file
1639 1640
1640 1641 return (int)(_initial_pid ? _initial_pid : getpid());
1641 1642 }
1642 1643
1643 1644 // DLL functions
1644 1645
1645 1646 const char* os::dll_file_extension() { return ".so"; }
1646 1647
1647 1648 // This must be hard coded because it's the system's temporary
1648 1649 // directory not the java application's temp directory, ala java.io.tmpdir.
1649 1650 const char* os::get_temp_directory() { return "/tmp"; }
1650 1651
1651 1652 static bool file_exists(const char* filename) {
1652 1653 struct stat statbuf;
1653 1654 if (filename == NULL || strlen(filename) == 0) {
1654 1655 return false;
1655 1656 }
1656 1657 return os::stat(filename, &statbuf) == 0;
1657 1658 }
1658 1659
1659 1660 void os::dll_build_name(char* buffer, size_t buflen,
1660 1661 const char* pname, const char* fname) {
1661 1662 // Copied from libhpi
1662 1663 const size_t pnamelen = pname ? strlen(pname) : 0;
1663 1664
1664 1665 // Quietly truncate on buffer overflow. Should be an error.
1665 1666 if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
1666 1667 *buffer = '\0';
1667 1668 return;
1668 1669 }
1669 1670
1670 1671 if (pnamelen == 0) {
1671 1672 snprintf(buffer, buflen, "lib%s.so", fname);
1672 1673 } else if (strchr(pname, *os::path_separator()) != NULL) {
1673 1674 int n;
1674 1675 char** pelements = split_path(pname, &n);
1675 1676 for (int i = 0 ; i < n ; i++) {
1676 1677 // Really shouldn't be NULL, but check can't hurt
1677 1678 if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1678 1679 continue; // skip the empty path values
1679 1680 }
1680 1681 snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
1681 1682 if (file_exists(buffer)) {
1682 1683 break;
1683 1684 }
1684 1685 }
1685 1686 // release the storage
1686 1687 for (int i = 0 ; i < n ; i++) {
1687 1688 if (pelements[i] != NULL) {
1688 1689 FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
1689 1690 }
1690 1691 }
1691 1692 if (pelements != NULL) {
1692 1693 FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
1693 1694 }
1694 1695 } else {
1695 1696 snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
1696 1697 }
1697 1698 }
1698 1699
1699 1700 const char* os::get_current_directory(char *buf, int buflen) {
1700 1701 return getcwd(buf, buflen);
1701 1702 }
1702 1703
1703 1704 // check if addr is inside libjvm[_g].so
1704 1705 bool os::address_is_in_vm(address addr) {
1705 1706 static address libjvm_base_addr;
1706 1707 Dl_info dlinfo;
1707 1708
1708 1709 if (libjvm_base_addr == NULL) {
1709 1710 dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo);
1710 1711 libjvm_base_addr = (address)dlinfo.dli_fbase;
1711 1712 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1712 1713 }
1713 1714
1714 1715 if (dladdr((void *)addr, &dlinfo)) {
1715 1716 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1716 1717 }
1717 1718
1718 1719 return false;
1719 1720 }
1720 1721
1721 1722 bool os::dll_address_to_function_name(address addr, char *buf,
1722 1723 int buflen, int *offset) {
1723 1724 Dl_info dlinfo;
1724 1725
1725 1726 if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) {
1726 1727 if (buf != NULL) {
1727 1728 if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
1728 1729 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1729 1730 }
1730 1731 }
1731 1732 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1732 1733 return true;
1733 1734 } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) {
1734 1735 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1735 1736 buf, buflen, offset, dlinfo.dli_fname)) {
1736 1737 return true;
1737 1738 }
1738 1739 }
1739 1740
1740 1741 if (buf != NULL) buf[0] = '\0';
1741 1742 if (offset != NULL) *offset = -1;
1742 1743 return false;
1743 1744 }
1744 1745
1745 1746 struct _address_to_library_name {
1746 1747 address addr; // input : memory address
1747 1748 size_t buflen; // size of fname
1748 1749 char* fname; // output: library name
1749 1750 address base; // library base addr
1750 1751 };
1751 1752
1752 1753 static int address_to_library_name_callback(struct dl_phdr_info *info,
1753 1754 size_t size, void *data) {
1754 1755 int i;
1755 1756 bool found = false;
1756 1757 address libbase = NULL;
1757 1758 struct _address_to_library_name * d = (struct _address_to_library_name *)data;
1758 1759
1759 1760 // iterate through all loadable segments
1760 1761 for (i = 0; i < info->dlpi_phnum; i++) {
1761 1762 address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1762 1763 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1763 1764 // base address of a library is the lowest address of its loaded
1764 1765 // segments.
1765 1766 if (libbase == NULL || libbase > segbase) {
1766 1767 libbase = segbase;
1767 1768 }
1768 1769 // see if 'addr' is within current segment
1769 1770 if (segbase <= d->addr &&
1770 1771 d->addr < segbase + info->dlpi_phdr[i].p_memsz) {
1771 1772 found = true;
1772 1773 }
1773 1774 }
1774 1775 }
1775 1776
1776 1777 // dlpi_name is NULL or empty if the ELF file is executable, return 0
1777 1778 // so dll_address_to_library_name() can fall through to use dladdr() which
1778 1779 // can figure out executable name from argv[0].
1779 1780 if (found && info->dlpi_name && info->dlpi_name[0]) {
1780 1781 d->base = libbase;
1781 1782 if (d->fname) {
1782 1783 jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name);
1783 1784 }
1784 1785 return 1;
1785 1786 }
1786 1787 return 0;
1787 1788 }
1788 1789
1789 1790 bool os::dll_address_to_library_name(address addr, char* buf,
1790 1791 int buflen, int* offset) {
1791 1792 Dl_info dlinfo;
1792 1793 struct _address_to_library_name data;
1793 1794
1794 1795 // There is a bug in old glibc dladdr() implementation that it could resolve
1795 1796 // to wrong library name if the .so file has a base address != NULL. Here
1796 1797 // we iterate through the program headers of all loaded libraries to find
1797 1798 // out which library 'addr' really belongs to. This workaround can be
1798 1799 // removed once the minimum requirement for glibc is moved to 2.3.x.
1799 1800 data.addr = addr;
1800 1801 data.fname = buf;
1801 1802 data.buflen = buflen;
1802 1803 data.base = NULL;
1803 1804 int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data);
1804 1805
1805 1806 if (rslt) {
1806 1807 // buf already contains library name
1807 1808 if (offset) *offset = addr - data.base;
1808 1809 return true;
1809 1810 } else if (dladdr((void*)addr, &dlinfo)){
1810 1811 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1811 1812 if (offset) *offset = addr - (address)dlinfo.dli_fbase;
1812 1813 return true;
1813 1814 } else {
1814 1815 if (buf) buf[0] = '\0';
1815 1816 if (offset) *offset = -1;
1816 1817 return false;
1817 1818 }
1818 1819 }
1819 1820
1820 1821 // Loads .dll/.so and
1821 1822 // in case of error it checks if .dll/.so was built for the
1822 1823 // same architecture as Hotspot is running on
1823 1824
1824 1825
1825 1826 // Remember the stack's state. The Linux dynamic linker will change
1826 1827 // the stack to 'executable' at most once, so we must safepoint only once.
1827 1828 bool os::Linux::_stack_is_executable = false;
1828 1829
1829 1830 // VM operation that loads a library. This is necessary if stack protection
1830 1831 // of the Java stacks can be lost during loading the library. If we
1831 1832 // do not stop the Java threads, they can stack overflow before the stacks
1832 1833 // are protected again.
1833 1834 class VM_LinuxDllLoad: public VM_Operation {
1834 1835 private:
1835 1836 const char *_filename;
1836 1837 char *_ebuf;
1837 1838 int _ebuflen;
1838 1839 void *_lib;
1839 1840 public:
1840 1841 VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :
1841 1842 _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {}
1842 1843 VMOp_Type type() const { return VMOp_LinuxDllLoad; }
1843 1844 void doit() {
1844 1845 _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);
1845 1846 os::Linux::_stack_is_executable = true;
1846 1847 }
1847 1848 void* loaded_library() { return _lib; }
1848 1849 };
1849 1850
1850 1851 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
1851 1852 {
1852 1853 void * result = NULL;
1853 1854 bool load_attempted = false;
1854 1855
1855 1856 // Check whether the library to load might change execution rights
1856 1857 // of the stack. If they are changed, the protection of the stack
1857 1858 // guard pages will be lost. We need a safepoint to fix this.
1858 1859 //
1859 1860 // See Linux man page execstack(8) for more info.
1860 1861 if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {
1861 1862 ElfFile ef(filename);
1862 1863 if (!ef.specifies_noexecstack()) {
1863 1864 if (!is_init_completed()) {
1864 1865 os::Linux::_stack_is_executable = true;
1865 1866 // This is OK - No Java threads have been created yet, and hence no
1866 1867 // stack guard pages to fix.
1867 1868 //
1868 1869 // This should happen only when you are building JDK7 using a very
1869 1870 // old version of JDK6 (e.g., with JPRT) and running test_gamma.
1870 1871 //
1871 1872 // Dynamic loader will make all stacks executable after
1872 1873 // this function returns, and will not do that again.
1873 1874 assert(Threads::first() == NULL, "no Java threads should exist yet.");
1874 1875 } else {
1875 1876 warning("You have loaded library %s which might have disabled stack guard. "
1876 1877 "The VM will try to fix the stack guard now.\n"
1877 1878 "It's highly recommended that you fix the library with "
1878 1879 "'execstack -c <libfile>', or link it with '-z noexecstack'.",
1879 1880 filename);
1880 1881
1881 1882 assert(Thread::current()->is_Java_thread(), "must be Java thread");
1882 1883 JavaThread *jt = JavaThread::current();
1883 1884 if (jt->thread_state() != _thread_in_native) {
1884 1885 // This happens when a compiler thread tries to load a hsdis-<arch>.so file
1885 1886 // that requires ExecStack. Cannot enter safe point. Let's give up.
1886 1887 warning("Unable to fix stack guard. Giving up.");
1887 1888 } else {
1888 1889 if (!LoadExecStackDllInVMThread) {
1889 1890 // This is for the case where the DLL has an static
1890 1891 // constructor function that executes JNI code. We cannot
1891 1892 // load such DLLs in the VMThread.
1892 1893 result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1893 1894 }
1894 1895
1895 1896 ThreadInVMfromNative tiv(jt);
1896 1897 debug_only(VMNativeEntryWrapper vew;)
1897 1898
1898 1899 VM_LinuxDllLoad op(filename, ebuf, ebuflen);
1899 1900 VMThread::execute(&op);
1900 1901 if (LoadExecStackDllInVMThread) {
1901 1902 result = op.loaded_library();
1902 1903 }
1903 1904 load_attempted = true;
1904 1905 }
1905 1906 }
1906 1907 }
1907 1908 }
1908 1909
1909 1910 if (!load_attempted) {
1910 1911 result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1911 1912 }
1912 1913
1913 1914 if (result != NULL) {
1914 1915 // Successful loading
1915 1916 return result;
1916 1917 }
1917 1918
1918 1919 Elf32_Ehdr elf_head;
1919 1920 int diag_msg_max_length=ebuflen-strlen(ebuf);
1920 1921 char* diag_msg_buf=ebuf+strlen(ebuf);
1921 1922
1922 1923 if (diag_msg_max_length==0) {
1923 1924 // No more space in ebuf for additional diagnostics message
1924 1925 return NULL;
1925 1926 }
1926 1927
1927 1928
1928 1929 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1929 1930
1930 1931 if (file_descriptor < 0) {
1931 1932 // Can't open library, report dlerror() message
1932 1933 return NULL;
1933 1934 }
1934 1935
1935 1936 bool failed_to_read_elf_head=
1936 1937 (sizeof(elf_head)!=
1937 1938 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
1938 1939
1939 1940 ::close(file_descriptor);
1940 1941 if (failed_to_read_elf_head) {
1941 1942 // file i/o error - report dlerror() msg
1942 1943 return NULL;
1943 1944 }
1944 1945
1945 1946 typedef struct {
1946 1947 Elf32_Half code; // Actual value as defined in elf.h
1947 1948 Elf32_Half compat_class; // Compatibility of archs at VM's sense
1948 1949 char elf_class; // 32 or 64 bit
1949 1950 char endianess; // MSB or LSB
1950 1951 char* name; // String representation
1951 1952 } arch_t;
1952 1953
1953 1954 #ifndef EM_486
1954 1955 #define EM_486 6 /* Intel 80486 */
1955 1956 #endif
1956 1957
1957 1958 static const arch_t arch_array[]={
1958 1959 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1959 1960 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1960 1961 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1961 1962 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1962 1963 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1963 1964 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1964 1965 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1965 1966 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1966 1967 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1967 1968 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1968 1969 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1969 1970 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1970 1971 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1971 1972 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1972 1973 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1973 1974 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1974 1975 };
1975 1976
1976 1977 #if (defined IA32)
1977 1978 static Elf32_Half running_arch_code=EM_386;
1978 1979 #elif (defined AMD64)
1979 1980 static Elf32_Half running_arch_code=EM_X86_64;
1980 1981 #elif (defined IA64)
1981 1982 static Elf32_Half running_arch_code=EM_IA_64;
1982 1983 #elif (defined __sparc) && (defined _LP64)
1983 1984 static Elf32_Half running_arch_code=EM_SPARCV9;
1984 1985 #elif (defined __sparc) && (!defined _LP64)
1985 1986 static Elf32_Half running_arch_code=EM_SPARC;
1986 1987 #elif (defined __powerpc64__)
1987 1988 static Elf32_Half running_arch_code=EM_PPC64;
1988 1989 #elif (defined __powerpc__)
1989 1990 static Elf32_Half running_arch_code=EM_PPC;
1990 1991 #elif (defined ARM)
1991 1992 static Elf32_Half running_arch_code=EM_ARM;
1992 1993 #elif (defined S390)
1993 1994 static Elf32_Half running_arch_code=EM_S390;
1994 1995 #elif (defined ALPHA)
1995 1996 static Elf32_Half running_arch_code=EM_ALPHA;
1996 1997 #elif (defined MIPSEL)
1997 1998 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1998 1999 #elif (defined PARISC)
1999 2000 static Elf32_Half running_arch_code=EM_PARISC;
2000 2001 #elif (defined MIPS)
2001 2002 static Elf32_Half running_arch_code=EM_MIPS;
2002 2003 #elif (defined M68K)
2003 2004 static Elf32_Half running_arch_code=EM_68K;
2004 2005 #else
2005 2006 #error Method os::dll_load requires that one of following is defined:\
2006 2007 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
2007 2008 #endif
2008 2009
2009 2010 // Identify compatability class for VM's architecture and library's architecture
2010 2011 // Obtain string descriptions for architectures
2011 2012
2012 2013 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
2013 2014 int running_arch_index=-1;
2014 2015
2015 2016 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
2016 2017 if (running_arch_code == arch_array[i].code) {
2017 2018 running_arch_index = i;
2018 2019 }
2019 2020 if (lib_arch.code == arch_array[i].code) {
2020 2021 lib_arch.compat_class = arch_array[i].compat_class;
2021 2022 lib_arch.name = arch_array[i].name;
2022 2023 }
2023 2024 }
2024 2025
2025 2026 assert(running_arch_index != -1,
2026 2027 "Didn't find running architecture code (running_arch_code) in arch_array");
2027 2028 if (running_arch_index == -1) {
2028 2029 // Even though running architecture detection failed
2029 2030 // we may still continue with reporting dlerror() message
2030 2031 return NULL;
2031 2032 }
2032 2033
2033 2034 if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
2034 2035 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
2035 2036 return NULL;
2036 2037 }
2037 2038
2038 2039 #ifndef S390
2039 2040 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
2040 2041 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
2041 2042 return NULL;
2042 2043 }
2043 2044 #endif // !S390
2044 2045
2045 2046 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
2046 2047 if ( lib_arch.name!=NULL ) {
2047 2048 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
2048 2049 " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
2049 2050 lib_arch.name, arch_array[running_arch_index].name);
2050 2051 } else {
2051 2052 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
2052 2053 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
2053 2054 lib_arch.code,
2054 2055 arch_array[running_arch_index].name);
2055 2056 }
2056 2057 }
2057 2058
2058 2059 return NULL;
2059 2060 }
2060 2061
2061 2062 void * os::Linux::dlopen_helper(const char *filename, char *ebuf, int ebuflen) {
2062 2063 void * result = ::dlopen(filename, RTLD_LAZY);
2063 2064 if (result == NULL) {
2064 2065 ::strncpy(ebuf, ::dlerror(), ebuflen - 1);
2065 2066 ebuf[ebuflen-1] = '\0';
2066 2067 }
2067 2068 return result;
2068 2069 }
2069 2070
2070 2071 void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf, int ebuflen) {
2071 2072 void * result = NULL;
2072 2073 if (LoadExecStackDllInVMThread) {
2073 2074 result = dlopen_helper(filename, ebuf, ebuflen);
2074 2075 }
2075 2076
2076 2077 // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
2077 2078 // library that requires an executable stack, or which does not have this
2078 2079 // stack attribute set, dlopen changes the stack attribute to executable. The
2079 2080 // read protection of the guard pages gets lost.
2080 2081 //
2081 2082 // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
2082 2083 // may have been queued at the same time.
2083 2084
2084 2085 if (!_stack_is_executable) {
2085 2086 JavaThread *jt = Threads::first();
2086 2087
2087 2088 while (jt) {
2088 2089 if (!jt->stack_guard_zone_unused() && // Stack not yet fully initialized
2089 2090 jt->stack_yellow_zone_enabled()) { // No pending stack overflow exceptions
2090 2091 if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(),
2091 2092 jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) {
2092 2093 warning("Attempt to reguard stack yellow zone failed.");
2093 2094 }
2094 2095 }
2095 2096 jt = jt->next();
2096 2097 }
2097 2098 }
2098 2099
2099 2100 return result;
2100 2101 }
2101 2102
2102 2103 /*
2103 2104 * glibc-2.0 libdl is not MT safe. If you are building with any glibc,
2104 2105 * chances are you might want to run the generated bits against glibc-2.0
2105 2106 * libdl.so, so always use locking for any version of glibc.
2106 2107 */
2107 2108 void* os::dll_lookup(void* handle, const char* name) {
2108 2109 pthread_mutex_lock(&dl_mutex);
2109 2110 void* res = dlsym(handle, name);
2110 2111 pthread_mutex_unlock(&dl_mutex);
2111 2112 return res;
2112 2113 }
2113 2114
2114 2115
2115 2116 static bool _print_ascii_file(const char* filename, outputStream* st) {
2116 2117 int fd = ::open(filename, O_RDONLY);
2117 2118 if (fd == -1) {
2118 2119 return false;
2119 2120 }
2120 2121
2121 2122 char buf[32];
2122 2123 int bytes;
2123 2124 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
2124 2125 st->print_raw(buf, bytes);
2125 2126 }
2126 2127
2127 2128 ::close(fd);
2128 2129
2129 2130 return true;
2130 2131 }
2131 2132
2132 2133 void os::print_dll_info(outputStream *st) {
2133 2134 st->print_cr("Dynamic libraries:");
2134 2135
2135 2136 char fname[32];
2136 2137 pid_t pid = os::Linux::gettid();
2137 2138
2138 2139 jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);
2139 2140
2140 2141 if (!_print_ascii_file(fname, st)) {
2141 2142 st->print("Can not get library information for pid = %d\n", pid);
2142 2143 }
2143 2144 }
2144 2145
2145 2146 void os::print_os_info_brief(outputStream* st) {
2146 2147 os::Linux::print_distro_info(st);
2147 2148
2148 2149 os::Posix::print_uname_info(st);
2149 2150
2150 2151 os::Linux::print_libversion_info(st);
2151 2152
2152 2153 }
2153 2154
2154 2155 void os::print_os_info(outputStream* st) {
2155 2156 st->print("OS:");
2156 2157
2157 2158 os::Linux::print_distro_info(st);
2158 2159
2159 2160 os::Posix::print_uname_info(st);
2160 2161
2161 2162 // Print warning if unsafe chroot environment detected
2162 2163 if (unsafe_chroot_detected) {
2163 2164 st->print("WARNING!! ");
2164 2165 st->print_cr(unstable_chroot_error);
2165 2166 }
2166 2167
2167 2168 os::Linux::print_libversion_info(st);
2168 2169
2169 2170 os::Posix::print_rlimit_info(st);
2170 2171
2171 2172 os::Posix::print_load_average(st);
2172 2173
2173 2174 os::Linux::print_full_memory_info(st);
2174 2175 }
2175 2176
2176 2177 // Try to identify popular distros.
2177 2178 // Most Linux distributions have /etc/XXX-release file, which contains
2178 2179 // the OS version string. Some have more than one /etc/XXX-release file
2179 2180 // (e.g. Mandrake has both /etc/mandrake-release and /etc/redhat-release.),
2180 2181 // so the order is important.
2181 2182 void os::Linux::print_distro_info(outputStream* st) {
2182 2183 if (!_print_ascii_file("/etc/mandrake-release", st) &&
2183 2184 !_print_ascii_file("/etc/sun-release", st) &&
2184 2185 !_print_ascii_file("/etc/redhat-release", st) &&
2185 2186 !_print_ascii_file("/etc/SuSE-release", st) &&
2186 2187 !_print_ascii_file("/etc/turbolinux-release", st) &&
2187 2188 !_print_ascii_file("/etc/gentoo-release", st) &&
2188 2189 !_print_ascii_file("/etc/debian_version", st) &&
2189 2190 !_print_ascii_file("/etc/ltib-release", st) &&
2190 2191 !_print_ascii_file("/etc/angstrom-version", st)) {
2191 2192 st->print("Linux");
2192 2193 }
2193 2194 st->cr();
2194 2195 }
2195 2196
2196 2197 void os::Linux::print_libversion_info(outputStream* st) {
2197 2198 // libc, pthread
2198 2199 st->print("libc:");
2199 2200 st->print(os::Linux::glibc_version()); st->print(" ");
2200 2201 st->print(os::Linux::libpthread_version()); st->print(" ");
2201 2202 if (os::Linux::is_LinuxThreads()) {
2202 2203 st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed");
2203 2204 }
2204 2205 st->cr();
2205 2206 }
2206 2207
2207 2208 void os::Linux::print_full_memory_info(outputStream* st) {
2208 2209 st->print("\n/proc/meminfo:\n");
2209 2210 _print_ascii_file("/proc/meminfo", st);
2210 2211 st->cr();
2211 2212 }
2212 2213
2213 2214 void os::print_memory_info(outputStream* st) {
2214 2215
2215 2216 st->print("Memory:");
2216 2217 st->print(" %dk page", os::vm_page_size()>>10);
2217 2218
2218 2219 // values in struct sysinfo are "unsigned long"
2219 2220 struct sysinfo si;
2220 2221 sysinfo(&si);
2221 2222
2222 2223 st->print(", physical " UINT64_FORMAT "k",
2223 2224 os::physical_memory() >> 10);
2224 2225 st->print("(" UINT64_FORMAT "k free)",
2225 2226 os::available_memory() >> 10);
2226 2227 st->print(", swap " UINT64_FORMAT "k",
2227 2228 ((jlong)si.totalswap * si.mem_unit) >> 10);
2228 2229 st->print("(" UINT64_FORMAT "k free)",
2229 2230 ((jlong)si.freeswap * si.mem_unit) >> 10);
2230 2231 st->cr();
2231 2232 }
2232 2233
2233 2234 void os::pd_print_cpu_info(outputStream* st) {
2234 2235 st->print("\n/proc/cpuinfo:\n");
2235 2236 if (!_print_ascii_file("/proc/cpuinfo", st)) {
2236 2237 st->print(" <Not Available>");
2237 2238 }
2238 2239 st->cr();
2239 2240 }
2240 2241
2241 2242 // Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific
2242 2243 // but they're the same for all the linux arch that we support
2243 2244 // and they're the same for solaris but there's no common place to put this.
2244 2245 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
2245 2246 "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
2246 2247 "ILL_COPROC", "ILL_BADSTK" };
2247 2248
2248 2249 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
2249 2250 "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
2250 2251 "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
2251 2252
2252 2253 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
2253 2254
2254 2255 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
2255 2256
2256 2257 void os::print_siginfo(outputStream* st, void* siginfo) {
2257 2258 st->print("siginfo:");
2258 2259
2259 2260 const int buflen = 100;
2260 2261 char buf[buflen];
2261 2262 siginfo_t *si = (siginfo_t*)siginfo;
2262 2263 st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
2263 2264 if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
2264 2265 st->print("si_errno=%s", buf);
2265 2266 } else {
2266 2267 st->print("si_errno=%d", si->si_errno);
2267 2268 }
2268 2269 const int c = si->si_code;
2269 2270 assert(c > 0, "unexpected si_code");
2270 2271 switch (si->si_signo) {
2271 2272 case SIGILL:
2272 2273 st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
2273 2274 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
2274 2275 break;
2275 2276 case SIGFPE:
2276 2277 st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
2277 2278 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
2278 2279 break;
2279 2280 case SIGSEGV:
2280 2281 st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
2281 2282 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
2282 2283 break;
2283 2284 case SIGBUS:
2284 2285 st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
2285 2286 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
2286 2287 break;
2287 2288 default:
2288 2289 st->print(", si_code=%d", si->si_code);
2289 2290 // no si_addr
2290 2291 }
2291 2292
2292 2293 if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
2293 2294 UseSharedSpaces) {
2294 2295 FileMapInfo* mapinfo = FileMapInfo::current_info();
2295 2296 if (mapinfo->is_in_shared_space(si->si_addr)) {
2296 2297 st->print("\n\nError accessing class data sharing archive." \
2297 2298 " Mapped file inaccessible during execution, " \
2298 2299 " possible disk/network problem.");
2299 2300 }
2300 2301 }
2301 2302 st->cr();
2302 2303 }
2303 2304
2304 2305
2305 2306 static void print_signal_handler(outputStream* st, int sig,
2306 2307 char* buf, size_t buflen);
2307 2308
2308 2309 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
2309 2310 st->print_cr("Signal Handlers:");
2310 2311 print_signal_handler(st, SIGSEGV, buf, buflen);
2311 2312 print_signal_handler(st, SIGBUS , buf, buflen);
2312 2313 print_signal_handler(st, SIGFPE , buf, buflen);
2313 2314 print_signal_handler(st, SIGPIPE, buf, buflen);
2314 2315 print_signal_handler(st, SIGXFSZ, buf, buflen);
2315 2316 print_signal_handler(st, SIGILL , buf, buflen);
2316 2317 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
2317 2318 print_signal_handler(st, SR_signum, buf, buflen);
2318 2319 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
2319 2320 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
2320 2321 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
2321 2322 print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
2322 2323 }
2323 2324
2324 2325 static char saved_jvm_path[MAXPATHLEN] = {0};
2325 2326
2326 2327 // Find the full path to the current module, libjvm.so or libjvm_g.so
2327 2328 void os::jvm_path(char *buf, jint buflen) {
2328 2329 // Error checking.
2329 2330 if (buflen < MAXPATHLEN) {
2330 2331 assert(false, "must use a large-enough buffer");
2331 2332 buf[0] = '\0';
2332 2333 return;
2333 2334 }
2334 2335 // Lazy resolve the path to current module.
2335 2336 if (saved_jvm_path[0] != 0) {
2336 2337 strcpy(buf, saved_jvm_path);
2337 2338 return;
2338 2339 }
2339 2340
2340 2341 char dli_fname[MAXPATHLEN];
2341 2342 bool ret = dll_address_to_library_name(
2342 2343 CAST_FROM_FN_PTR(address, os::jvm_path),
2343 2344 dli_fname, sizeof(dli_fname), NULL);
2344 2345 assert(ret != 0, "cannot locate libjvm");
2345 2346 char *rp = realpath(dli_fname, buf);
2346 2347 if (rp == NULL)
2347 2348 return;
2348 2349
2349 2350 if (Arguments::created_by_gamma_launcher()) {
2350 2351 // Support for the gamma launcher. Typical value for buf is
2351 2352 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". If "/jre/lib/" appears at
2352 2353 // the right place in the string, then assume we are installed in a JDK and
2353 2354 // we're done. Otherwise, check for a JAVA_HOME environment variable and fix
2354 2355 // up the path so it looks like libjvm.so is installed there (append a
2355 2356 // fake suffix hotspot/libjvm.so).
2356 2357 const char *p = buf + strlen(buf) - 1;
2357 2358 for (int count = 0; p > buf && count < 5; ++count) {
2358 2359 for (--p; p > buf && *p != '/'; --p)
2359 2360 /* empty */ ;
2360 2361 }
2361 2362
2362 2363 if (strncmp(p, "/jre/lib/", 9) != 0) {
2363 2364 // Look for JAVA_HOME in the environment.
2364 2365 char* java_home_var = ::getenv("JAVA_HOME");
2365 2366 if (java_home_var != NULL && java_home_var[0] != 0) {
2366 2367 char* jrelib_p;
2367 2368 int len;
2368 2369
2369 2370 // Check the current module name "libjvm.so" or "libjvm_g.so".
2370 2371 p = strrchr(buf, '/');
2371 2372 assert(strstr(p, "/libjvm") == p, "invalid library name");
2372 2373 p = strstr(p, "_g") ? "_g" : "";
2373 2374
2374 2375 rp = realpath(java_home_var, buf);
2375 2376 if (rp == NULL)
2376 2377 return;
2377 2378
2378 2379 // determine if this is a legacy image or modules image
2379 2380 // modules image doesn't have "jre" subdirectory
2380 2381 len = strlen(buf);
2381 2382 jrelib_p = buf + len;
2382 2383 snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
2383 2384 if (0 != access(buf, F_OK)) {
2384 2385 snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);
2385 2386 }
2386 2387
2387 2388 if (0 == access(buf, F_OK)) {
2388 2389 // Use current module name "libjvm[_g].so" instead of
2389 2390 // "libjvm"debug_only("_g")".so" since for fastdebug version
2390 2391 // we should have "libjvm.so" but debug_only("_g") adds "_g"!
2391 2392 len = strlen(buf);
2392 2393 snprintf(buf + len, buflen-len, "/hotspot/libjvm%s.so", p);
2393 2394 } else {
2394 2395 // Go back to path of .so
2395 2396 rp = realpath(dli_fname, buf);
2396 2397 if (rp == NULL)
2397 2398 return;
2398 2399 }
2399 2400 }
2400 2401 }
2401 2402 }
2402 2403
2403 2404 strcpy(saved_jvm_path, buf);
2404 2405 }
2405 2406
2406 2407 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
2407 2408 // no prefix required, not even "_"
2408 2409 }
2409 2410
2410 2411 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
2411 2412 // no suffix required
2412 2413 }
2413 2414
2414 2415 ////////////////////////////////////////////////////////////////////////////////
2415 2416 // sun.misc.Signal support
2416 2417
2417 2418 static volatile jint sigint_count = 0;
2418 2419
2419 2420 static void
2420 2421 UserHandler(int sig, void *siginfo, void *context) {
2421 2422 // 4511530 - sem_post is serialized and handled by the manager thread. When
2422 2423 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
2423 2424 // don't want to flood the manager thread with sem_post requests.
2424 2425 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
2425 2426 return;
2426 2427
2427 2428 // Ctrl-C is pressed during error reporting, likely because the error
2428 2429 // handler fails to abort. Let VM die immediately.
2429 2430 if (sig == SIGINT && is_error_reported()) {
2430 2431 os::die();
2431 2432 }
2432 2433
2433 2434 os::signal_notify(sig);
2434 2435 }
2435 2436
2436 2437 void* os::user_handler() {
2437 2438 return CAST_FROM_FN_PTR(void*, UserHandler);
2438 2439 }
2439 2440
2440 2441 class Semaphore : public StackObj {
2441 2442 public:
2442 2443 Semaphore();
2443 2444 ~Semaphore();
2444 2445 void signal();
2445 2446 void wait();
2446 2447 bool trywait();
2447 2448 bool timedwait(unsigned int sec, int nsec);
2448 2449 private:
2449 2450 sem_t _semaphore;
2450 2451 };
2451 2452
2452 2453
2453 2454 Semaphore::Semaphore() {
2454 2455 sem_init(&_semaphore, 0, 0);
2455 2456 }
2456 2457
2457 2458 Semaphore::~Semaphore() {
2458 2459 sem_destroy(&_semaphore);
2459 2460 }
2460 2461
2461 2462 void Semaphore::signal() {
2462 2463 sem_post(&_semaphore);
2463 2464 }
2464 2465
2465 2466 void Semaphore::wait() {
2466 2467 sem_wait(&_semaphore);
2467 2468 }
2468 2469
2469 2470 bool Semaphore::trywait() {
2470 2471 return sem_trywait(&_semaphore) == 0;
2471 2472 }
2472 2473
2473 2474 bool Semaphore::timedwait(unsigned int sec, int nsec) {
2474 2475 struct timespec ts;
2475 2476 unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
2476 2477
2477 2478 while (1) {
2478 2479 int result = sem_timedwait(&_semaphore, &ts);
2479 2480 if (result == 0) {
2480 2481 return true;
2481 2482 } else if (errno == EINTR) {
2482 2483 continue;
2483 2484 } else if (errno == ETIMEDOUT) {
2484 2485 return false;
2485 2486 } else {
2486 2487 return false;
2487 2488 }
2488 2489 }
2489 2490 }
2490 2491
2491 2492 extern "C" {
2492 2493 typedef void (*sa_handler_t)(int);
2493 2494 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
2494 2495 }
2495 2496
2496 2497 void* os::signal(int signal_number, void* handler) {
2497 2498 struct sigaction sigAct, oldSigAct;
2498 2499
2499 2500 sigfillset(&(sigAct.sa_mask));
2500 2501 sigAct.sa_flags = SA_RESTART|SA_SIGINFO;
2501 2502 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
2502 2503
2503 2504 if (sigaction(signal_number, &sigAct, &oldSigAct)) {
2504 2505 // -1 means registration failed
2505 2506 return (void *)-1;
2506 2507 }
2507 2508
2508 2509 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
2509 2510 }
2510 2511
2511 2512 void os::signal_raise(int signal_number) {
2512 2513 ::raise(signal_number);
2513 2514 }
2514 2515
2515 2516 /*
2516 2517 * The following code is moved from os.cpp for making this
2517 2518 * code platform specific, which it is by its very nature.
2518 2519 */
2519 2520
2520 2521 // Will be modified when max signal is changed to be dynamic
2521 2522 int os::sigexitnum_pd() {
2522 2523 return NSIG;
2523 2524 }
2524 2525
2525 2526 // a counter for each possible signal value
2526 2527 static volatile jint pending_signals[NSIG+1] = { 0 };
2527 2528
2528 2529 // Linux(POSIX) specific hand shaking semaphore.
2529 2530 static sem_t sig_sem;
2530 2531 static Semaphore sr_semaphore;
2531 2532
2532 2533 void os::signal_init_pd() {
2533 2534 // Initialize signal structures
2534 2535 ::memset((void*)pending_signals, 0, sizeof(pending_signals));
2535 2536
2536 2537 // Initialize signal semaphore
2537 2538 ::sem_init(&sig_sem, 0, 0);
2538 2539 }
2539 2540
2540 2541 void os::signal_notify(int sig) {
2541 2542 Atomic::inc(&pending_signals[sig]);
2542 2543 ::sem_post(&sig_sem);
2543 2544 }
2544 2545
2545 2546 static int check_pending_signals(bool wait) {
2546 2547 Atomic::store(0, &sigint_count);
2547 2548 for (;;) {
2548 2549 for (int i = 0; i < NSIG + 1; i++) {
2549 2550 jint n = pending_signals[i];
2550 2551 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2551 2552 return i;
2552 2553 }
2553 2554 }
2554 2555 if (!wait) {
2555 2556 return -1;
2556 2557 }
2557 2558 JavaThread *thread = JavaThread::current();
2558 2559 ThreadBlockInVM tbivm(thread);
2559 2560
2560 2561 bool threadIsSuspended;
2561 2562 do {
2562 2563 thread->set_suspend_equivalent();
2563 2564 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2564 2565 ::sem_wait(&sig_sem);
2565 2566
2566 2567 // were we externally suspended while we were waiting?
2567 2568 threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2568 2569 if (threadIsSuspended) {
2569 2570 //
2570 2571 // The semaphore has been incremented, but while we were waiting
2571 2572 // another thread suspended us. We don't want to continue running
2572 2573 // while suspended because that would surprise the thread that
2573 2574 // suspended us.
2574 2575 //
2575 2576 ::sem_post(&sig_sem);
2576 2577
2577 2578 thread->java_suspend_self();
2578 2579 }
2579 2580 } while (threadIsSuspended);
2580 2581 }
2581 2582 }
2582 2583
2583 2584 int os::signal_lookup() {
2584 2585 return check_pending_signals(false);
2585 2586 }
2586 2587
2587 2588 int os::signal_wait() {
2588 2589 return check_pending_signals(true);
2589 2590 }
2590 2591
2591 2592 ////////////////////////////////////////////////////////////////////////////////
2592 2593 // Virtual Memory
2593 2594
2594 2595 int os::vm_page_size() {
2595 2596 // Seems redundant as all get out
2596 2597 assert(os::Linux::page_size() != -1, "must call os::init");
2597 2598 return os::Linux::page_size();
2598 2599 }
2599 2600
2600 2601 // Solaris allocates memory by pages.
2601 2602 int os::vm_allocation_granularity() {
2602 2603 assert(os::Linux::page_size() != -1, "must call os::init");
2603 2604 return os::Linux::page_size();
2604 2605 }
2605 2606
2606 2607 // Rationale behind this function:
2607 2608 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2608 2609 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2609 2610 // samples for JITted code. Here we create private executable mapping over the code cache
2610 2611 // and then we can use standard (well, almost, as mapping can change) way to provide
2611 2612 // info for the reporting script by storing timestamp and location of symbol
2612 2613 void linux_wrap_code(char* base, size_t size) {
2613 2614 static volatile jint cnt = 0;
2614 2615
2615 2616 if (!UseOprofile) {
2616 2617 return;
2617 2618 }
2618 2619
2619 2620 char buf[PATH_MAX+1];
2620 2621 int num = Atomic::add(1, &cnt);
2621 2622
2622 2623 snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
2623 2624 os::get_temp_directory(), os::current_process_id(), num);
2624 2625 unlink(buf);
2625 2626
2626 2627 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2627 2628
2628 2629 if (fd != -1) {
2629 2630 off_t rv = ::lseek(fd, size-2, SEEK_SET);
2630 2631 if (rv != (off_t)-1) {
2631 2632 if (::write(fd, "", 1) == 1) {
2632 2633 mmap(base, size,
2633 2634 PROT_READ|PROT_WRITE|PROT_EXEC,
2634 2635 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2635 2636 }
2636 2637 }
2637 2638 ::close(fd);
2638 2639 unlink(buf);
2639 2640 }
2640 2641 }
2641 2642
2642 2643 // NOTE: Linux kernel does not really reserve the pages for us.
2643 2644 // All it does is to check if there are enough free pages
2644 2645 // left at the time of mmap(). This could be a potential
2645 2646 // problem.
2646 2647 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2647 2648 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2648 2649 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2649 2650 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2650 2651 if (res != (uintptr_t) MAP_FAILED) {
2651 2652 if (UseNUMAInterleaving) {
2652 2653 numa_make_global(addr, size);
2653 2654 }
2654 2655 return true;
2655 2656 }
2656 2657 return false;
2657 2658 }
2658 2659
2659 2660 // Define MAP_HUGETLB here so we can build HotSpot on old systems.
2660 2661 #ifndef MAP_HUGETLB
2661 2662 #define MAP_HUGETLB 0x40000
2662 2663 #endif
2663 2664
2664 2665 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
2665 2666 #ifndef MADV_HUGEPAGE
2666 2667 #define MADV_HUGEPAGE 14
2667 2668 #endif
2668 2669
2669 2670 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2670 2671 bool exec) {
2671 2672 if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) {
2672 2673 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2673 2674 uintptr_t res =
2674 2675 (uintptr_t) ::mmap(addr, size, prot,
2675 2676 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS|MAP_HUGETLB,
2676 2677 -1, 0);
2677 2678 if (res != (uintptr_t) MAP_FAILED) {
2678 2679 if (UseNUMAInterleaving) {
2679 2680 numa_make_global(addr, size);
2680 2681 }
2681 2682 return true;
2682 2683 }
2683 2684 // Fall through and try to use small pages
2684 2685 }
2685 2686
2686 2687 if (commit_memory(addr, size, exec)) {
2687 2688 realign_memory(addr, size, alignment_hint);
2688 2689 return true;
2689 2690 }
2690 2691 return false;
2691 2692 }
2692 2693
2693 2694 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2694 2695 if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) {
2695 2696 // We don't check the return value: madvise(MADV_HUGEPAGE) may not
2696 2697 // be supported or the memory may already be backed by huge pages.
2697 2698 ::madvise(addr, bytes, MADV_HUGEPAGE);
2698 2699 }
2699 2700 }
2700 2701
2701 2702 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2702 2703 // This method works by doing an mmap over an existing mmaping and effectively discarding
2703 2704 // the existing pages. However it won't work for SHM-based large pages that cannot be
2704 2705 // uncommitted at all. We don't do anything in this case to avoid creating a segment with
2705 2706 // small pages on top of the SHM segment. This method always works for small pages, so we
2706 2707 // allow that in any case.
2707 2708 if (alignment_hint <= (size_t)os::vm_page_size() || !UseSHM) {
2708 2709 commit_memory(addr, bytes, alignment_hint, false);
2709 2710 }
2710 2711 }
2711 2712
2712 2713 void os::numa_make_global(char *addr, size_t bytes) {
2713 2714 Linux::numa_interleave_memory(addr, bytes);
2714 2715 }
2715 2716
2716 2717 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2717 2718 Linux::numa_tonode_memory(addr, bytes, lgrp_hint);
2718 2719 }
2719 2720
2720 2721 bool os::numa_topology_changed() { return false; }
2721 2722
2722 2723 size_t os::numa_get_groups_num() {
2723 2724 int max_node = Linux::numa_max_node();
2724 2725 return max_node > 0 ? max_node + 1 : 1;
2725 2726 }
2726 2727
2727 2728 int os::numa_get_group_id() {
2728 2729 int cpu_id = Linux::sched_getcpu();
2729 2730 if (cpu_id != -1) {
2730 2731 int lgrp_id = Linux::get_node_by_cpu(cpu_id);
2731 2732 if (lgrp_id != -1) {
2732 2733 return lgrp_id;
2733 2734 }
2734 2735 }
2735 2736 return 0;
2736 2737 }
2737 2738
2738 2739 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2739 2740 for (size_t i = 0; i < size; i++) {
2740 2741 ids[i] = i;
2741 2742 }
2742 2743 return size;
2743 2744 }
2744 2745
2745 2746 bool os::get_page_info(char *start, page_info* info) {
2746 2747 return false;
2747 2748 }
2748 2749
2749 2750 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2750 2751 return end;
2751 2752 }
2752 2753
2753 2754
2754 2755 int os::Linux::sched_getcpu_syscall(void) {
2755 2756 unsigned int cpu;
2756 2757 int retval = -1;
2757 2758
2758 2759 #if defined(IA32)
2759 2760 # ifndef SYS_getcpu
2760 2761 # define SYS_getcpu 318
2761 2762 # endif
2762 2763 retval = syscall(SYS_getcpu, &cpu, NULL, NULL);
2763 2764 #elif defined(AMD64)
2764 2765 // Unfortunately we have to bring all these macros here from vsyscall.h
2765 2766 // to be able to compile on old linuxes.
2766 2767 # define __NR_vgetcpu 2
2767 2768 # define VSYSCALL_START (-10UL << 20)
2768 2769 # define VSYSCALL_SIZE 1024
2769 2770 # define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))
2770 2771 typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);
2771 2772 vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);
2772 2773 retval = vgetcpu(&cpu, NULL, NULL);
2773 2774 #endif
2774 2775
2775 2776 return (retval == -1) ? retval : cpu;
2776 2777 }
2777 2778
2778 2779 // Something to do with the numa-aware allocator needs these symbols
2779 2780 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }
2780 2781 extern "C" JNIEXPORT void numa_error(char *where) { }
2781 2782 extern "C" JNIEXPORT int fork1() { return fork(); }
2782 2783
2783 2784
2784 2785 // If we are running with libnuma version > 2, then we should
2785 2786 // be trying to use symbols with versions 1.1
2786 2787 // If we are running with earlier version, which did not have symbol versions,
2787 2788 // we should use the base version.
2788 2789 void* os::Linux::libnuma_dlsym(void* handle, const char *name) {
2789 2790 void *f = dlvsym(handle, name, "libnuma_1.1");
2790 2791 if (f == NULL) {
2791 2792 f = dlsym(handle, name);
2792 2793 }
2793 2794 return f;
2794 2795 }
2795 2796
2796 2797 bool os::Linux::libnuma_init() {
2797 2798 // sched_getcpu() should be in libc.
2798 2799 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2799 2800 dlsym(RTLD_DEFAULT, "sched_getcpu")));
2800 2801
2801 2802 // If it's not, try a direct syscall.
2802 2803 if (sched_getcpu() == -1)
2803 2804 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, (void*)&sched_getcpu_syscall));
2804 2805
2805 2806 if (sched_getcpu() != -1) { // Does it work?
2806 2807 void *handle = dlopen("libnuma.so.1", RTLD_LAZY);
2807 2808 if (handle != NULL) {
2808 2809 set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,
2809 2810 libnuma_dlsym(handle, "numa_node_to_cpus")));
2810 2811 set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
2811 2812 libnuma_dlsym(handle, "numa_max_node")));
2812 2813 set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
2813 2814 libnuma_dlsym(handle, "numa_available")));
2814 2815 set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
2815 2816 libnuma_dlsym(handle, "numa_tonode_memory")));
2816 2817 set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
2817 2818 libnuma_dlsym(handle, "numa_interleave_memory")));
2818 2819
2819 2820
2820 2821 if (numa_available() != -1) {
2821 2822 set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
2822 2823 // Create a cpu -> node mapping
2823 2824 _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
2824 2825 rebuild_cpu_to_node_map();
2825 2826 return true;
2826 2827 }
2827 2828 }
2828 2829 }
2829 2830 return false;
2830 2831 }
2831 2832
2832 2833 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
2833 2834 // The table is later used in get_node_by_cpu().
2834 2835 void os::Linux::rebuild_cpu_to_node_map() {
2835 2836 const size_t NCPUS = 32768; // Since the buffer size computation is very obscure
2836 2837 // in libnuma (possible values are starting from 16,
2837 2838 // and continuing up with every other power of 2, but less
2838 2839 // than the maximum number of CPUs supported by kernel), and
2839 2840 // is a subject to change (in libnuma version 2 the requirements
2840 2841 // are more reasonable) we'll just hardcode the number they use
2841 2842 // in the library.
2842 2843 const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
2843 2844
2844 2845 size_t cpu_num = os::active_processor_count();
2845 2846 size_t cpu_map_size = NCPUS / BitsPerCLong;
2846 2847 size_t cpu_map_valid_size =
2847 2848 MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
2848 2849
2849 2850 cpu_to_node()->clear();
2850 2851 cpu_to_node()->at_grow(cpu_num - 1);
2851 2852 size_t node_num = numa_get_groups_num();
2852 2853
2853 2854 unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
2854 2855 for (size_t i = 0; i < node_num; i++) {
2855 2856 if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
2856 2857 for (size_t j = 0; j < cpu_map_valid_size; j++) {
2857 2858 if (cpu_map[j] != 0) {
2858 2859 for (size_t k = 0; k < BitsPerCLong; k++) {
2859 2860 if (cpu_map[j] & (1UL << k)) {
2860 2861 cpu_to_node()->at_put(j * BitsPerCLong + k, i);
2861 2862 }
2862 2863 }
2863 2864 }
2864 2865 }
2865 2866 }
2866 2867 }
2867 2868 FREE_C_HEAP_ARRAY(unsigned long, cpu_map, mtInternal);
2868 2869 }
2869 2870
2870 2871 int os::Linux::get_node_by_cpu(int cpu_id) {
2871 2872 if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {
2872 2873 return cpu_to_node()->at(cpu_id);
2873 2874 }
2874 2875 return -1;
2875 2876 }
2876 2877
2877 2878 GrowableArray<int>* os::Linux::_cpu_to_node;
2878 2879 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
2879 2880 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
2880 2881 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
2881 2882 os::Linux::numa_available_func_t os::Linux::_numa_available;
2882 2883 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
2883 2884 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
2884 2885 unsigned long* os::Linux::_numa_all_nodes;
2885 2886
2886 2887 bool os::pd_uncommit_memory(char* addr, size_t size) {
2887 2888 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2888 2889 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2889 2890 return res != (uintptr_t) MAP_FAILED;
2890 2891 }
2891 2892
2892 2893 // Linux uses a growable mapping for the stack, and if the mapping for
2893 2894 // the stack guard pages is not removed when we detach a thread the
2894 2895 // stack cannot grow beyond the pages where the stack guard was
2895 2896 // mapped. If at some point later in the process the stack expands to
2896 2897 // that point, the Linux kernel cannot expand the stack any further
2897 2898 // because the guard pages are in the way, and a segfault occurs.
2898 2899 //
2899 2900 // However, it's essential not to split the stack region by unmapping
2900 2901 // a region (leaving a hole) that's already part of the stack mapping,
2901 2902 // so if the stack mapping has already grown beyond the guard pages at
2902 2903 // the time we create them, we have to truncate the stack mapping.
2903 2904 // So, we need to know the extent of the stack mapping when
2904 2905 // create_stack_guard_pages() is called.
2905 2906
2906 2907 // Find the bounds of the stack mapping. Return true for success.
2907 2908 //
2908 2909 // We only need this for stacks that are growable: at the time of
2909 2910 // writing thread stacks don't use growable mappings (i.e. those
2910 2911 // creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
2911 2912 // only applies to the main thread.
2912 2913
2913 2914 static
2914 2915 bool get_stack_bounds(uintptr_t *bottom, uintptr_t *top) {
2915 2916
2916 2917 char buf[128];
2917 2918 int fd, sz;
2918 2919
2919 2920 if ((fd = ::open("/proc/self/maps", O_RDONLY)) < 0) {
2920 2921 return false;
2921 2922 }
2922 2923
2923 2924 const char kw[] = "[stack]";
2924 2925 const int kwlen = sizeof(kw)-1;
2925 2926
2926 2927 // Address part of /proc/self/maps couldn't be more than 128 bytes
2927 2928 while ((sz = os::get_line_chars(fd, buf, sizeof(buf))) > 0) {
2928 2929 if (sz > kwlen && ::memcmp(buf+sz-kwlen, kw, kwlen) == 0) {
2929 2930 // Extract addresses
2930 2931 if (sscanf(buf, "%" SCNxPTR "-%" SCNxPTR, bottom, top) == 2) {
2931 2932 uintptr_t sp = (uintptr_t) __builtin_frame_address(0);
2932 2933 if (sp >= *bottom && sp <= *top) {
2933 2934 ::close(fd);
2934 2935 return true;
2935 2936 }
2936 2937 }
2937 2938 }
2938 2939 }
2939 2940
2940 2941 ::close(fd);
2941 2942 return false;
2942 2943 }
2943 2944
2944 2945
2945 2946 // If the (growable) stack mapping already extends beyond the point
2946 2947 // where we're going to put our guard pages, truncate the mapping at
2947 2948 // that point by munmap()ping it. This ensures that when we later
2948 2949 // munmap() the guard pages we don't leave a hole in the stack
2949 2950 // mapping. This only affects the main/initial thread, but guard
2950 2951 // against future OS changes
2951 2952 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2952 2953 uintptr_t stack_extent, stack_base;
2953 2954 bool chk_bounds = NOT_DEBUG(os::Linux::is_initial_thread()) DEBUG_ONLY(true);
2954 2955 if (chk_bounds && get_stack_bounds(&stack_extent, &stack_base)) {
2955 2956 assert(os::Linux::is_initial_thread(),
2956 2957 "growable stack in non-initial thread");
2957 2958 if (stack_extent < (uintptr_t)addr)
2958 2959 ::munmap((void*)stack_extent, (uintptr_t)addr - stack_extent);
2959 2960 }
2960 2961
2961 2962 return os::commit_memory(addr, size);
2962 2963 }
2963 2964
2964 2965 // If this is a growable mapping, remove the guard pages entirely by
2965 2966 // munmap()ping them. If not, just call uncommit_memory(). This only
2966 2967 // affects the main/initial thread, but guard against future OS changes
2967 2968 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2968 2969 uintptr_t stack_extent, stack_base;
2969 2970 bool chk_bounds = NOT_DEBUG(os::Linux::is_initial_thread()) DEBUG_ONLY(true);
2970 2971 if (chk_bounds && get_stack_bounds(&stack_extent, &stack_base)) {
2971 2972 assert(os::Linux::is_initial_thread(),
2972 2973 "growable stack in non-initial thread");
2973 2974
2974 2975 return ::munmap(addr, size) == 0;
2975 2976 }
2976 2977
2977 2978 return os::uncommit_memory(addr, size);
2978 2979 }
2979 2980
2980 2981 static address _highest_vm_reserved_address = NULL;
2981 2982
2982 2983 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2983 2984 // at 'requested_addr'. If there are existing memory mappings at the same
2984 2985 // location, however, they will be overwritten. If 'fixed' is false,
2985 2986 // 'requested_addr' is only treated as a hint, the return value may or
2986 2987 // may not start from the requested address. Unlike Linux mmap(), this
2987 2988 // function returns NULL to indicate failure.
2988 2989 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2989 2990 char * addr;
2990 2991 int flags;
2991 2992
2992 2993 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2993 2994 if (fixed) {
2994 2995 assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address");
2995 2996 flags |= MAP_FIXED;
2996 2997 }
2997 2998
2998 2999 // Map uncommitted pages PROT_READ and PROT_WRITE, change access
2999 3000 // to PROT_EXEC if executable when we commit the page.
3000 3001 addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE,
3001 3002 flags, -1, 0);
3002 3003
3003 3004 if (addr != MAP_FAILED) {
3004 3005 // anon_mmap() should only get called during VM initialization,
3005 3006 // don't need lock (actually we can skip locking even it can be called
3006 3007 // from multiple threads, because _highest_vm_reserved_address is just a
3007 3008 // hint about the upper limit of non-stack memory regions.)
3008 3009 if ((address)addr + bytes > _highest_vm_reserved_address) {
3009 3010 _highest_vm_reserved_address = (address)addr + bytes;
3010 3011 }
3011 3012 }
3012 3013
3013 3014 return addr == MAP_FAILED ? NULL : addr;
3014 3015 }
3015 3016
3016 3017 // Don't update _highest_vm_reserved_address, because there might be memory
3017 3018 // regions above addr + size. If so, releasing a memory region only creates
3018 3019 // a hole in the address space, it doesn't help prevent heap-stack collision.
3019 3020 //
3020 3021 static int anon_munmap(char * addr, size_t size) {
3021 3022 return ::munmap(addr, size) == 0;
3022 3023 }
3023 3024
3024 3025 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
3025 3026 size_t alignment_hint) {
3026 3027 return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
3027 3028 }
3028 3029
3029 3030 bool os::pd_release_memory(char* addr, size_t size) {
3030 3031 return anon_munmap(addr, size);
3031 3032 }
3032 3033
3033 3034 static address highest_vm_reserved_address() {
3034 3035 return _highest_vm_reserved_address;
3035 3036 }
3036 3037
3037 3038 static bool linux_mprotect(char* addr, size_t size, int prot) {
3038 3039 // Linux wants the mprotect address argument to be page aligned.
3039 3040 char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size());
3040 3041
3041 3042 // According to SUSv3, mprotect() should only be used with mappings
3042 3043 // established by mmap(), and mmap() always maps whole pages. Unaligned
3043 3044 // 'addr' likely indicates problem in the VM (e.g. trying to change
3044 3045 // protection of malloc'ed or statically allocated memory). Check the
3045 3046 // caller if you hit this assert.
3046 3047 assert(addr == bottom, "sanity check");
3047 3048
3048 3049 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size());
3049 3050 return ::mprotect(bottom, size, prot) == 0;
3050 3051 }
3051 3052
3052 3053 // Set protections specified
3053 3054 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
3054 3055 bool is_committed) {
3055 3056 unsigned int p = 0;
3056 3057 switch (prot) {
3057 3058 case MEM_PROT_NONE: p = PROT_NONE; break;
3058 3059 case MEM_PROT_READ: p = PROT_READ; break;
3059 3060 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;
3060 3061 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
3061 3062 default:
3062 3063 ShouldNotReachHere();
3063 3064 }
3064 3065 // is_committed is unused.
3065 3066 return linux_mprotect(addr, bytes, p);
3066 3067 }
3067 3068
3068 3069 bool os::guard_memory(char* addr, size_t size) {
3069 3070 return linux_mprotect(addr, size, PROT_NONE);
3070 3071 }
3071 3072
3072 3073 bool os::unguard_memory(char* addr, size_t size) {
3073 3074 return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);
3074 3075 }
3075 3076
3076 3077 bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {
3077 3078 bool result = false;
3078 3079 void *p = mmap (NULL, page_size, PROT_READ|PROT_WRITE,
3079 3080 MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB,
3080 3081 -1, 0);
3081 3082
3082 3083 if (p != (void *) -1) {
3083 3084 // We don't know if this really is a huge page or not.
3084 3085 FILE *fp = fopen("/proc/self/maps", "r");
3085 3086 if (fp) {
3086 3087 while (!feof(fp)) {
3087 3088 char chars[257];
3088 3089 long x = 0;
3089 3090 if (fgets(chars, sizeof(chars), fp)) {
3090 3091 if (sscanf(chars, "%lx-%*x", &x) == 1
3091 3092 && x == (long)p) {
3092 3093 if (strstr (chars, "hugepage")) {
3093 3094 result = true;
3094 3095 break;
3095 3096 }
3096 3097 }
3097 3098 }
3098 3099 }
3099 3100 fclose(fp);
3100 3101 }
3101 3102 munmap (p, page_size);
3102 3103 if (result)
3103 3104 return true;
3104 3105 }
3105 3106
3106 3107 if (warn) {
3107 3108 warning("HugeTLBFS is not supported by the operating system.");
3108 3109 }
3109 3110
3110 3111 return result;
3111 3112 }
3112 3113
3113 3114 /*
3114 3115 * Set the coredump_filter bits to include largepages in core dump (bit 6)
3115 3116 *
3116 3117 * From the coredump_filter documentation:
3117 3118 *
3118 3119 * - (bit 0) anonymous private memory
3119 3120 * - (bit 1) anonymous shared memory
3120 3121 * - (bit 2) file-backed private memory
3121 3122 * - (bit 3) file-backed shared memory
3122 3123 * - (bit 4) ELF header pages in file-backed private memory areas (it is
3123 3124 * effective only if the bit 2 is cleared)
3124 3125 * - (bit 5) hugetlb private memory
3125 3126 * - (bit 6) hugetlb shared memory
3126 3127 */
3127 3128 static void set_coredump_filter(void) {
3128 3129 FILE *f;
3129 3130 long cdm;
3130 3131
3131 3132 if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
3132 3133 return;
3133 3134 }
3134 3135
3135 3136 if (fscanf(f, "%lx", &cdm) != 1) {
3136 3137 fclose(f);
3137 3138 return;
3138 3139 }
3139 3140
3140 3141 rewind(f);
3141 3142
3142 3143 if ((cdm & LARGEPAGES_BIT) == 0) {
3143 3144 cdm |= LARGEPAGES_BIT;
3144 3145 fprintf(f, "%#lx", cdm);
3145 3146 }
3146 3147
3147 3148 fclose(f);
3148 3149 }
3149 3150
3150 3151 // Large page support
3151 3152
3152 3153 static size_t _large_page_size = 0;
3153 3154
3154 3155 void os::large_page_init() {
3155 3156 if (!UseLargePages) {
3156 3157 UseHugeTLBFS = false;
3157 3158 UseSHM = false;
3158 3159 return;
3159 3160 }
3160 3161
3161 3162 if (FLAG_IS_DEFAULT(UseHugeTLBFS) && FLAG_IS_DEFAULT(UseSHM)) {
3162 3163 // If UseLargePages is specified on the command line try both methods,
3163 3164 // if it's default, then try only HugeTLBFS.
3164 3165 if (FLAG_IS_DEFAULT(UseLargePages)) {
3165 3166 UseHugeTLBFS = true;
3166 3167 } else {
3167 3168 UseHugeTLBFS = UseSHM = true;
3168 3169 }
3169 3170 }
3170 3171
3171 3172 if (LargePageSizeInBytes) {
3172 3173 _large_page_size = LargePageSizeInBytes;
3173 3174 } else {
3174 3175 // large_page_size on Linux is used to round up heap size. x86 uses either
3175 3176 // 2M or 4M page, depending on whether PAE (Physical Address Extensions)
3176 3177 // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use
3177 3178 // page as large as 256M.
3178 3179 //
3179 3180 // Here we try to figure out page size by parsing /proc/meminfo and looking
3180 3181 // for a line with the following format:
3181 3182 // Hugepagesize: 2048 kB
3182 3183 //
3183 3184 // If we can't determine the value (e.g. /proc is not mounted, or the text
3184 3185 // format has been changed), we'll use the largest page size supported by
3185 3186 // the processor.
3186 3187
3187 3188 #ifndef ZERO
3188 3189 _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M)
3189 3190 ARM_ONLY(2 * M) PPC_ONLY(4 * M);
3190 3191 #endif // ZERO
3191 3192
3192 3193 FILE *fp = fopen("/proc/meminfo", "r");
3193 3194 if (fp) {
3194 3195 while (!feof(fp)) {
3195 3196 int x = 0;
3196 3197 char buf[16];
3197 3198 if (fscanf(fp, "Hugepagesize: %d", &x) == 1) {
3198 3199 if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) {
3199 3200 _large_page_size = x * K;
3200 3201 break;
3201 3202 }
3202 3203 } else {
3203 3204 // skip to next line
3204 3205 for (;;) {
3205 3206 int ch = fgetc(fp);
3206 3207 if (ch == EOF || ch == (int)'\n') break;
3207 3208 }
3208 3209 }
3209 3210 }
3210 3211 fclose(fp);
3211 3212 }
3212 3213 }
3213 3214
3214 3215 // print a warning if any large page related flag is specified on command line
3215 3216 bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);
3216 3217
3217 3218 const size_t default_page_size = (size_t)Linux::page_size();
3218 3219 if (_large_page_size > default_page_size) {
3219 3220 _page_sizes[0] = _large_page_size;
3220 3221 _page_sizes[1] = default_page_size;
3221 3222 _page_sizes[2] = 0;
3222 3223 }
3223 3224 UseHugeTLBFS = UseHugeTLBFS &&
3224 3225 Linux::hugetlbfs_sanity_check(warn_on_failure, _large_page_size);
3225 3226
3226 3227 if (UseHugeTLBFS)
3227 3228 UseSHM = false;
3228 3229
3229 3230 UseLargePages = UseHugeTLBFS || UseSHM;
3230 3231
3231 3232 set_coredump_filter();
3232 3233 }
3233 3234
3234 3235 #ifndef SHM_HUGETLB
3235 3236 #define SHM_HUGETLB 04000
3236 3237 #endif
3237 3238
3238 3239 char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
3239 3240 // "exec" is passed in but not used. Creating the shared image for
3240 3241 // the code cache doesn't have an SHM_X executable permission to check.
3241 3242 assert(UseLargePages && UseSHM, "only for SHM large pages");
3242 3243
3243 3244 key_t key = IPC_PRIVATE;
3244 3245 char *addr;
3245 3246
3246 3247 bool warn_on_failure = UseLargePages &&
3247 3248 (!FLAG_IS_DEFAULT(UseLargePages) ||
3248 3249 !FLAG_IS_DEFAULT(LargePageSizeInBytes)
3249 3250 );
3250 3251 char msg[128];
3251 3252
3252 3253 // Create a large shared memory region to attach to based on size.
3253 3254 // Currently, size is the total size of the heap
3254 3255 int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
3255 3256 if (shmid == -1) {
3256 3257 // Possible reasons for shmget failure:
3257 3258 // 1. shmmax is too small for Java heap.
3258 3259 // > check shmmax value: cat /proc/sys/kernel/shmmax
3259 3260 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
3260 3261 // 2. not enough large page memory.
3261 3262 // > check available large pages: cat /proc/meminfo
3262 3263 // > increase amount of large pages:
3263 3264 // echo new_value > /proc/sys/vm/nr_hugepages
3264 3265 // Note 1: different Linux may use different name for this property,
3265 3266 // e.g. on Redhat AS-3 it is "hugetlb_pool".
3266 3267 // Note 2: it's possible there's enough physical memory available but
3267 3268 // they are so fragmented after a long run that they can't
3268 3269 // coalesce into large pages. Try to reserve large pages when
3269 3270 // the system is still "fresh".
3270 3271 if (warn_on_failure) {
3271 3272 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
3272 3273 warning(msg);
3273 3274 }
3274 3275 return NULL;
3275 3276 }
3276 3277
3277 3278 // attach to the region
3278 3279 addr = (char*)shmat(shmid, req_addr, 0);
3279 3280 int err = errno;
3280 3281
3281 3282 // Remove shmid. If shmat() is successful, the actual shared memory segment
3282 3283 // will be deleted when it's detached by shmdt() or when the process
3283 3284 // terminates. If shmat() is not successful this will remove the shared
3284 3285 // segment immediately.
3285 3286 shmctl(shmid, IPC_RMID, NULL);
3286 3287
3287 3288 if ((intptr_t)addr == -1) {
3288 3289 if (warn_on_failure) {
3289 3290 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
3290 3291 warning(msg);
3291 3292 }
3292 3293 return NULL;
3293 3294 }
3294 3295
3295 3296 if ((addr != NULL) && UseNUMAInterleaving) {
3296 3297 numa_make_global(addr, bytes);
3297 3298 }
3298 3299
3299 3300 // The memory is committed
3300 3301 address pc = CALLER_PC;
3301 3302 MemTracker::record_virtual_memory_reserve((address)addr, bytes, pc);
3302 3303 MemTracker::record_virtual_memory_commit((address)addr, bytes, pc);
3303 3304
3304 3305 return addr;
3305 3306 }
3306 3307
3307 3308 bool os::release_memory_special(char* base, size_t bytes) {
3308 3309 // detaching the SHM segment will also delete it, see reserve_memory_special()
3309 3310 int rslt = shmdt(base);
3310 3311 if (rslt == 0) {
3311 3312 MemTracker::record_virtual_memory_uncommit((address)base, bytes);
3312 3313 MemTracker::record_virtual_memory_release((address)base, bytes);
3313 3314 return true;
3314 3315 } else {
3315 3316 return false;
3316 3317 }
3317 3318 }
3318 3319
3319 3320 size_t os::large_page_size() {
3320 3321 return _large_page_size;
3321 3322 }
3322 3323
3323 3324 // HugeTLBFS allows application to commit large page memory on demand;
3324 3325 // with SysV SHM the entire memory region must be allocated as shared
3325 3326 // memory.
3326 3327 bool os::can_commit_large_page_memory() {
3327 3328 return UseHugeTLBFS;
3328 3329 }
3329 3330
3330 3331 bool os::can_execute_large_page_memory() {
3331 3332 return UseHugeTLBFS;
3332 3333 }
3333 3334
3334 3335 // Reserve memory at an arbitrary address, only if that area is
3335 3336 // available (and not reserved for something else).
3336 3337
3337 3338 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
3338 3339 const int max_tries = 10;
3339 3340 char* base[max_tries];
3340 3341 size_t size[max_tries];
3341 3342 const size_t gap = 0x000000;
3342 3343
3343 3344 // Assert only that the size is a multiple of the page size, since
3344 3345 // that's all that mmap requires, and since that's all we really know
3345 3346 // about at this low abstraction level. If we need higher alignment,
3346 3347 // we can either pass an alignment to this method or verify alignment
3347 3348 // in one of the methods further up the call chain. See bug 5044738.
3348 3349 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
3349 3350
3350 3351 // Repeatedly allocate blocks until the block is allocated at the
3351 3352 // right spot. Give up after max_tries. Note that reserve_memory() will
3352 3353 // automatically update _highest_vm_reserved_address if the call is
3353 3354 // successful. The variable tracks the highest memory address every reserved
3354 3355 // by JVM. It is used to detect heap-stack collision if running with
3355 3356 // fixed-stack LinuxThreads. Because here we may attempt to reserve more
3356 3357 // space than needed, it could confuse the collision detecting code. To
3357 3358 // solve the problem, save current _highest_vm_reserved_address and
3358 3359 // calculate the correct value before return.
3359 3360 address old_highest = _highest_vm_reserved_address;
3360 3361
3361 3362 // Linux mmap allows caller to pass an address as hint; give it a try first,
3362 3363 // if kernel honors the hint then we can return immediately.
3363 3364 char * addr = anon_mmap(requested_addr, bytes, false);
3364 3365 if (addr == requested_addr) {
3365 3366 return requested_addr;
3366 3367 }
3367 3368
3368 3369 if (addr != NULL) {
3369 3370 // mmap() is successful but it fails to reserve at the requested address
3370 3371 anon_munmap(addr, bytes);
3371 3372 }
3372 3373
3373 3374 int i;
3374 3375 for (i = 0; i < max_tries; ++i) {
3375 3376 base[i] = reserve_memory(bytes);
3376 3377
3377 3378 if (base[i] != NULL) {
3378 3379 // Is this the block we wanted?
3379 3380 if (base[i] == requested_addr) {
3380 3381 size[i] = bytes;
3381 3382 break;
3382 3383 }
3383 3384
3384 3385 // Does this overlap the block we wanted? Give back the overlapped
3385 3386 // parts and try again.
3386 3387
3387 3388 size_t top_overlap = requested_addr + (bytes + gap) - base[i];
3388 3389 if (top_overlap >= 0 && top_overlap < bytes) {
3389 3390 unmap_memory(base[i], top_overlap);
3390 3391 base[i] += top_overlap;
3391 3392 size[i] = bytes - top_overlap;
3392 3393 } else {
3393 3394 size_t bottom_overlap = base[i] + bytes - requested_addr;
3394 3395 if (bottom_overlap >= 0 && bottom_overlap < bytes) {
3395 3396 unmap_memory(requested_addr, bottom_overlap);
3396 3397 size[i] = bytes - bottom_overlap;
3397 3398 } else {
3398 3399 size[i] = bytes;
3399 3400 }
3400 3401 }
3401 3402 }
3402 3403 }
3403 3404
3404 3405 // Give back the unused reserved pieces.
3405 3406
3406 3407 for (int j = 0; j < i; ++j) {
3407 3408 if (base[j] != NULL) {
3408 3409 unmap_memory(base[j], size[j]);
3409 3410 }
3410 3411 }
3411 3412
3412 3413 if (i < max_tries) {
3413 3414 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
3414 3415 return requested_addr;
3415 3416 } else {
3416 3417 _highest_vm_reserved_address = old_highest;
3417 3418 return NULL;
3418 3419 }
3419 3420 }
3420 3421
3421 3422 size_t os::read(int fd, void *buf, unsigned int nBytes) {
3422 3423 return ::read(fd, buf, nBytes);
3423 3424 }
3424 3425
3425 3426 // TODO-FIXME: reconcile Solaris' os::sleep with the linux variation.
3426 3427 // Solaris uses poll(), linux uses park().
3427 3428 // Poll() is likely a better choice, assuming that Thread.interrupt()
3428 3429 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
3429 3430 // SIGSEGV, see 4355769.
3430 3431
3431 3432 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
3432 3433 assert(thread == Thread::current(), "thread consistency check");
3433 3434
3434 3435 ParkEvent * const slp = thread->_SleepEvent ;
3435 3436 slp->reset() ;
3436 3437 OrderAccess::fence() ;
3437 3438
3438 3439 if (interruptible) {
3439 3440 jlong prevtime = javaTimeNanos();
3440 3441
3441 3442 for (;;) {
3442 3443 if (os::is_interrupted(thread, true)) {
3443 3444 return OS_INTRPT;
3444 3445 }
3445 3446
3446 3447 jlong newtime = javaTimeNanos();
3447 3448
3448 3449 if (newtime - prevtime < 0) {
3449 3450 // time moving backwards, should only happen if no monotonic clock
3450 3451 // not a guarantee() because JVM should not abort on kernel/glibc bugs
3451 3452 assert(!Linux::supports_monotonic_clock(), "time moving backwards");
3452 3453 } else {
3453 3454 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
3454 3455 }
3455 3456
3456 3457 if(millis <= 0) {
3457 3458 return OS_OK;
3458 3459 }
3459 3460
3460 3461 prevtime = newtime;
3461 3462
3462 3463 {
3463 3464 assert(thread->is_Java_thread(), "sanity check");
3464 3465 JavaThread *jt = (JavaThread *) thread;
3465 3466 ThreadBlockInVM tbivm(jt);
3466 3467 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
3467 3468
3468 3469 jt->set_suspend_equivalent();
3469 3470 // cleared by handle_special_suspend_equivalent_condition() or
3470 3471 // java_suspend_self() via check_and_wait_while_suspended()
3471 3472
3472 3473 slp->park(millis);
3473 3474
3474 3475 // were we externally suspended while we were waiting?
3475 3476 jt->check_and_wait_while_suspended();
3476 3477 }
3477 3478 }
3478 3479 } else {
3479 3480 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
3480 3481 jlong prevtime = javaTimeNanos();
3481 3482
3482 3483 for (;;) {
3483 3484 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
3484 3485 // the 1st iteration ...
3485 3486 jlong newtime = javaTimeNanos();
3486 3487
3487 3488 if (newtime - prevtime < 0) {
3488 3489 // time moving backwards, should only happen if no monotonic clock
3489 3490 // not a guarantee() because JVM should not abort on kernel/glibc bugs
3490 3491 assert(!Linux::supports_monotonic_clock(), "time moving backwards");
3491 3492 } else {
3492 3493 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
3493 3494 }
3494 3495
3495 3496 if(millis <= 0) break ;
3496 3497
3497 3498 prevtime = newtime;
3498 3499 slp->park(millis);
3499 3500 }
3500 3501 return OS_OK ;
3501 3502 }
3502 3503 }
3503 3504
3504 3505 int os::naked_sleep() {
3505 3506 // %% make the sleep time an integer flag. for now use 1 millisec.
3506 3507 return os::sleep(Thread::current(), 1, false);
3507 3508 }
3508 3509
3509 3510 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
3510 3511 void os::infinite_sleep() {
3511 3512 while (true) { // sleep forever ...
3512 3513 ::sleep(100); // ... 100 seconds at a time
3513 3514 }
3514 3515 }
3515 3516
3516 3517 // Used to convert frequent JVM_Yield() to nops
3517 3518 bool os::dont_yield() {
3518 3519 return DontYieldALot;
3519 3520 }
3520 3521
3521 3522 void os::yield() {
3522 3523 sched_yield();
3523 3524 }
3524 3525
3525 3526 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
3526 3527
3527 3528 void os::yield_all(int attempts) {
3528 3529 // Yields to all threads, including threads with lower priorities
3529 3530 // Threads on Linux are all with same priority. The Solaris style
3530 3531 // os::yield_all() with nanosleep(1ms) is not necessary.
3531 3532 sched_yield();
3532 3533 }
3533 3534
3534 3535 // Called from the tight loops to possibly influence time-sharing heuristics
3535 3536 void os::loop_breaker(int attempts) {
3536 3537 os::yield_all(attempts);
3537 3538 }
3538 3539
3539 3540 ////////////////////////////////////////////////////////////////////////////////
3540 3541 // thread priority support
3541 3542
3542 3543 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
3543 3544 // only supports dynamic priority, static priority must be zero. For real-time
3544 3545 // applications, Linux supports SCHED_RR which allows static priority (1-99).
3545 3546 // However, for large multi-threaded applications, SCHED_RR is not only slower
3546 3547 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
3547 3548 // of 5 runs - Sep 2005).
3548 3549 //
3549 3550 // The following code actually changes the niceness of kernel-thread/LWP. It
3550 3551 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
3551 3552 // not the entire user process, and user level threads are 1:1 mapped to kernel
3552 3553 // threads. It has always been the case, but could change in the future. For
3553 3554 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
3554 3555 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
3555 3556
3556 3557 int os::java_to_os_priority[CriticalPriority + 1] = {
3557 3558 19, // 0 Entry should never be used
3558 3559
3559 3560 4, // 1 MinPriority
3560 3561 3, // 2
3561 3562 2, // 3
3562 3563
3563 3564 1, // 4
3564 3565 0, // 5 NormPriority
3565 3566 -1, // 6
3566 3567
3567 3568 -2, // 7
3568 3569 -3, // 8
3569 3570 -4, // 9 NearMaxPriority
3570 3571
3571 3572 -5, // 10 MaxPriority
3572 3573
3573 3574 -5 // 11 CriticalPriority
3574 3575 };
3575 3576
3576 3577 static int prio_init() {
3577 3578 if (ThreadPriorityPolicy == 1) {
3578 3579 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
3579 3580 // if effective uid is not root. Perhaps, a more elegant way of doing
3580 3581 // this is to test CAP_SYS_NICE capability, but that will require libcap.so
3581 3582 if (geteuid() != 0) {
3582 3583 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
3583 3584 warning("-XX:ThreadPriorityPolicy requires root privilege on Linux");
3584 3585 }
3585 3586 ThreadPriorityPolicy = 0;
3586 3587 }
3587 3588 }
3588 3589 if (UseCriticalJavaThreadPriority) {
3589 3590 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
3590 3591 }
3591 3592 return 0;
3592 3593 }
3593 3594
3594 3595 OSReturn os::set_native_priority(Thread* thread, int newpri) {
3595 3596 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
3596 3597
3597 3598 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
3598 3599 return (ret == 0) ? OS_OK : OS_ERR;
3599 3600 }
3600 3601
3601 3602 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
3602 3603 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
3603 3604 *priority_ptr = java_to_os_priority[NormPriority];
3604 3605 return OS_OK;
3605 3606 }
3606 3607
3607 3608 errno = 0;
3608 3609 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
3609 3610 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
3610 3611 }
3611 3612
3612 3613 // Hint to the underlying OS that a task switch would not be good.
3613 3614 // Void return because it's a hint and can fail.
3614 3615 void os::hint_no_preempt() {}
3615 3616
3616 3617 ////////////////////////////////////////////////////////////////////////////////
3617 3618 // suspend/resume support
3618 3619
3619 3620 // the low-level signal-based suspend/resume support is a remnant from the
3620 3621 // old VM-suspension that used to be for java-suspension, safepoints etc,
3621 3622 // within hotspot. Now there is a single use-case for this:
3622 3623 // - calling get_thread_pc() on the VMThread by the flat-profiler task
3623 3624 // that runs in the watcher thread.
3624 3625 // The remaining code is greatly simplified from the more general suspension
3625 3626 // code that used to be used.
3626 3627 //
3627 3628 // The protocol is quite simple:
3628 3629 // - suspend:
3629 3630 // - sends a signal to the target thread
3630 3631 // - polls the suspend state of the osthread using a yield loop
3631 3632 // - target thread signal handler (SR_handler) sets suspend state
3632 3633 // and blocks in sigsuspend until continued
3633 3634 // - resume:
3634 3635 // - sets target osthread state to continue
3635 3636 // - sends signal to end the sigsuspend loop in the SR_handler
3636 3637 //
3637 3638 // Note that the SR_lock plays no role in this suspend/resume protocol.
3638 3639 //
3639 3640
3640 3641 static void resume_clear_context(OSThread *osthread) {
3641 3642 osthread->set_ucontext(NULL);
3642 3643 osthread->set_siginfo(NULL);
3643 3644 }
3644 3645
3645 3646 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
3646 3647 osthread->set_ucontext(context);
3647 3648 osthread->set_siginfo(siginfo);
3648 3649 }
3649 3650
3650 3651 //
3651 3652 // Handler function invoked when a thread's execution is suspended or
3652 3653 // resumed. We have to be careful that only async-safe functions are
3653 3654 // called here (Note: most pthread functions are not async safe and
3654 3655 // should be avoided.)
3655 3656 //
3656 3657 // Note: sigwait() is a more natural fit than sigsuspend() from an
3657 3658 // interface point of view, but sigwait() prevents the signal hander
3658 3659 // from being run. libpthread would get very confused by not having
3659 3660 // its signal handlers run and prevents sigwait()'s use with the
3660 3661 // mutex granting granting signal.
3661 3662 //
3662 3663 // Currently only ever called on the VMThread and JavaThreads (PC sampling)
3663 3664 //
3664 3665 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
3665 3666 // Save and restore errno to avoid confusing native code with EINTR
3666 3667 // after sigsuspend.
3667 3668 int old_errno = errno;
3668 3669
3669 3670 Thread* thread = Thread::current();
3670 3671 OSThread* osthread = thread->osthread();
3671 3672 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
3672 3673
3673 3674 os::SuspendResume::State current = osthread->sr.state();
3674 3675 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
3675 3676 suspend_save_context(osthread, siginfo, context);
3676 3677
3677 3678 // attempt to switch the state, we assume we had a SUSPEND_REQUEST
3678 3679 os::SuspendResume::State state = osthread->sr.suspended();
3679 3680 if (state == os::SuspendResume::SR_SUSPENDED) {
3680 3681 sigset_t suspend_set; // signals for sigsuspend()
3681 3682
3682 3683 // get current set of blocked signals and unblock resume signal
3683 3684 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
3684 3685 sigdelset(&suspend_set, SR_signum);
3685 3686
3686 3687 sr_semaphore.signal();
3687 3688 // wait here until we are resumed
3688 3689 while (1) {
3689 3690 sigsuspend(&suspend_set);
3690 3691
3691 3692 os::SuspendResume::State result = osthread->sr.running();
3692 3693 if (result == os::SuspendResume::SR_RUNNING) {
3693 3694 sr_semaphore.signal();
3694 3695 break;
3695 3696 }
3696 3697 }
3697 3698
3698 3699 } else if (state == os::SuspendResume::SR_RUNNING) {
3699 3700 // request was cancelled, continue
3700 3701 } else {
3701 3702 ShouldNotReachHere();
3702 3703 }
3703 3704
3704 3705 resume_clear_context(osthread);
3705 3706 } else if (current == os::SuspendResume::SR_RUNNING) {
3706 3707 // request was cancelled, continue
3707 3708 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
3708 3709 // ignore
3709 3710 } else {
3710 3711 // ignore
3711 3712 }
3712 3713
3713 3714 errno = old_errno;
3714 3715 }
3715 3716
3716 3717
3717 3718 static int SR_initialize() {
3718 3719 struct sigaction act;
3719 3720 char *s;
3720 3721 /* Get signal number to use for suspend/resume */
3721 3722 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
3722 3723 int sig = ::strtol(s, 0, 10);
3723 3724 if (sig > 0 || sig < _NSIG) {
3724 3725 SR_signum = sig;
3725 3726 }
3726 3727 }
3727 3728
3728 3729 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
3729 3730 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
3730 3731
3731 3732 sigemptyset(&SR_sigset);
3732 3733 sigaddset(&SR_sigset, SR_signum);
3733 3734
3734 3735 /* Set up signal handler for suspend/resume */
3735 3736 act.sa_flags = SA_RESTART|SA_SIGINFO;
3736 3737 act.sa_handler = (void (*)(int)) SR_handler;
3737 3738
3738 3739 // SR_signum is blocked by default.
3739 3740 // 4528190 - We also need to block pthread restart signal (32 on all
3740 3741 // supported Linux platforms). Note that LinuxThreads need to block
3741 3742 // this signal for all threads to work properly. So we don't have
3742 3743 // to use hard-coded signal number when setting up the mask.
3743 3744 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
3744 3745
3745 3746 if (sigaction(SR_signum, &act, 0) == -1) {
3746 3747 return -1;
3747 3748 }
3748 3749
3749 3750 // Save signal flag
3750 3751 os::Linux::set_our_sigflags(SR_signum, act.sa_flags);
3751 3752 return 0;
3752 3753 }
3753 3754
3754 3755 static int SR_finalize() {
3755 3756 return 0;
3756 3757 }
3757 3758
3758 3759 static int sr_notify(OSThread* osthread) {
3759 3760 int status = pthread_kill(osthread->pthread_id(), SR_signum);
3760 3761 assert_status(status == 0, status, "pthread_kill");
3761 3762 return status;
3762 3763 }
3763 3764
3764 3765 // "Randomly" selected value for how long we want to spin
3765 3766 // before bailing out on suspending a thread, also how often
3766 3767 // we send a signal to a thread we want to resume
3767 3768 static const int RANDOMLY_LARGE_INTEGER = 1000000;
3768 3769 static const int RANDOMLY_LARGE_INTEGER2 = 100;
3769 3770
3770 3771 // returns true on success and false on error - really an error is fatal
3771 3772 // but this seems the normal response to library errors
3772 3773 static bool do_suspend(OSThread* osthread) {
3773 3774 assert(osthread->sr.is_running(), "thread should be running");
3774 3775 assert(!sr_semaphore.trywait(), "semaphore has invalid state");
3775 3776
3776 3777 // mark as suspended and send signal
3777 3778 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
3778 3779 // failed to switch, state wasn't running?
3779 3780 ShouldNotReachHere();
3780 3781 return false;
3781 3782 }
3782 3783
3783 3784 if (sr_notify(osthread) != 0) {
3784 3785 ShouldNotReachHere();
3785 3786 }
3786 3787
3787 3788 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
3788 3789 while (true) {
3789 3790 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
3790 3791 break;
3791 3792 } else {
3792 3793 // timeout
3793 3794 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
3794 3795 if (cancelled == os::SuspendResume::SR_RUNNING) {
3795 3796 return false;
3796 3797 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
3797 3798 // make sure that we consume the signal on the semaphore as well
3798 3799 sr_semaphore.wait();
3799 3800 break;
3800 3801 } else {
3801 3802 ShouldNotReachHere();
3802 3803 return false;
3803 3804 }
3804 3805 }
3805 3806 }
3806 3807
3807 3808 guarantee(osthread->sr.is_suspended(), "Must be suspended");
3808 3809 return true;
3809 3810 }
3810 3811
3811 3812 static void do_resume(OSThread* osthread) {
3812 3813 assert(osthread->sr.is_suspended(), "thread should be suspended");
3813 3814 assert(!sr_semaphore.trywait(), "invalid semaphore state");
3814 3815
3815 3816 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
3816 3817 // failed to switch to WAKEUP_REQUEST
3817 3818 ShouldNotReachHere();
3818 3819 return;
3819 3820 }
3820 3821
3821 3822 while (true) {
3822 3823 if (sr_notify(osthread) == 0) {
3823 3824 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
3824 3825 if (osthread->sr.is_running()) {
3825 3826 return;
3826 3827 }
3827 3828 }
3828 3829 } else {
3829 3830 ShouldNotReachHere();
3830 3831 }
3831 3832 }
3832 3833
3833 3834 guarantee(osthread->sr.is_running(), "Must be running!");
3834 3835 }
3835 3836
3836 3837 ////////////////////////////////////////////////////////////////////////////////
3837 3838 // interrupt support
3838 3839
3839 3840 void os::interrupt(Thread* thread) {
3840 3841 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
3841 3842 "possibility of dangling Thread pointer");
3842 3843
3843 3844 OSThread* osthread = thread->osthread();
3844 3845
3845 3846 if (!osthread->interrupted()) {
3846 3847 osthread->set_interrupted(true);
3847 3848 // More than one thread can get here with the same value of osthread,
3848 3849 // resulting in multiple notifications. We do, however, want the store
3849 3850 // to interrupted() to be visible to other threads before we execute unpark().
3850 3851 OrderAccess::fence();
3851 3852 ParkEvent * const slp = thread->_SleepEvent ;
3852 3853 if (slp != NULL) slp->unpark() ;
3853 3854 }
3854 3855
3855 3856 // For JSR166. Unpark even if interrupt status already was set
3856 3857 if (thread->is_Java_thread())
3857 3858 ((JavaThread*)thread)->parker()->unpark();
3858 3859
3859 3860 ParkEvent * ev = thread->_ParkEvent ;
3860 3861 if (ev != NULL) ev->unpark() ;
3861 3862
3862 3863 }
3863 3864
3864 3865 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
3865 3866 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
3866 3867 "possibility of dangling Thread pointer");
3867 3868
3868 3869 OSThread* osthread = thread->osthread();
3869 3870
3870 3871 bool interrupted = osthread->interrupted();
3871 3872
3872 3873 if (interrupted && clear_interrupted) {
3873 3874 osthread->set_interrupted(false);
3874 3875 // consider thread->_SleepEvent->reset() ... optional optimization
3875 3876 }
3876 3877
3877 3878 return interrupted;
3878 3879 }
3879 3880
3880 3881 ///////////////////////////////////////////////////////////////////////////////////
3881 3882 // signal handling (except suspend/resume)
3882 3883
3883 3884 // This routine may be used by user applications as a "hook" to catch signals.
3884 3885 // The user-defined signal handler must pass unrecognized signals to this
3885 3886 // routine, and if it returns true (non-zero), then the signal handler must
3886 3887 // return immediately. If the flag "abort_if_unrecognized" is true, then this
3887 3888 // routine will never retun false (zero), but instead will execute a VM panic
3888 3889 // routine kill the process.
3889 3890 //
3890 3891 // If this routine returns false, it is OK to call it again. This allows
3891 3892 // the user-defined signal handler to perform checks either before or after
3892 3893 // the VM performs its own checks. Naturally, the user code would be making
3893 3894 // a serious error if it tried to handle an exception (such as a null check
3894 3895 // or breakpoint) that the VM was generating for its own correct operation.
3895 3896 //
3896 3897 // This routine may recognize any of the following kinds of signals:
3897 3898 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
3898 3899 // It should be consulted by handlers for any of those signals.
3899 3900 //
3900 3901 // The caller of this routine must pass in the three arguments supplied
3901 3902 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
3902 3903 // field of the structure passed to sigaction(). This routine assumes that
3903 3904 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
3904 3905 //
3905 3906 // Note that the VM will print warnings if it detects conflicting signal
3906 3907 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
3907 3908 //
3908 3909 extern "C" JNIEXPORT int
3909 3910 JVM_handle_linux_signal(int signo, siginfo_t* siginfo,
3910 3911 void* ucontext, int abort_if_unrecognized);
3911 3912
3912 3913 void signalHandler(int sig, siginfo_t* info, void* uc) {
3913 3914 assert(info != NULL && uc != NULL, "it must be old kernel");
3914 3915 JVM_handle_linux_signal(sig, info, uc, true);
3915 3916 }
3916 3917
3917 3918
3918 3919 // This boolean allows users to forward their own non-matching signals
3919 3920 // to JVM_handle_linux_signal, harmlessly.
3920 3921 bool os::Linux::signal_handlers_are_installed = false;
3921 3922
3922 3923 // For signal-chaining
3923 3924 struct sigaction os::Linux::sigact[MAXSIGNUM];
3924 3925 unsigned int os::Linux::sigs = 0;
3925 3926 bool os::Linux::libjsig_is_loaded = false;
3926 3927 typedef struct sigaction *(*get_signal_t)(int);
3927 3928 get_signal_t os::Linux::get_signal_action = NULL;
3928 3929
3929 3930 struct sigaction* os::Linux::get_chained_signal_action(int sig) {
3930 3931 struct sigaction *actp = NULL;
3931 3932
3932 3933 if (libjsig_is_loaded) {
3933 3934 // Retrieve the old signal handler from libjsig
3934 3935 actp = (*get_signal_action)(sig);
3935 3936 }
3936 3937 if (actp == NULL) {
3937 3938 // Retrieve the preinstalled signal handler from jvm
3938 3939 actp = get_preinstalled_handler(sig);
3939 3940 }
3940 3941
3941 3942 return actp;
3942 3943 }
3943 3944
3944 3945 static bool call_chained_handler(struct sigaction *actp, int sig,
3945 3946 siginfo_t *siginfo, void *context) {
3946 3947 // Call the old signal handler
3947 3948 if (actp->sa_handler == SIG_DFL) {
3948 3949 // It's more reasonable to let jvm treat it as an unexpected exception
3949 3950 // instead of taking the default action.
3950 3951 return false;
3951 3952 } else if (actp->sa_handler != SIG_IGN) {
3952 3953 if ((actp->sa_flags & SA_NODEFER) == 0) {
3953 3954 // automaticlly block the signal
3954 3955 sigaddset(&(actp->sa_mask), sig);
3955 3956 }
3956 3957
3957 3958 sa_handler_t hand;
3958 3959 sa_sigaction_t sa;
3959 3960 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3960 3961 // retrieve the chained handler
3961 3962 if (siginfo_flag_set) {
3962 3963 sa = actp->sa_sigaction;
3963 3964 } else {
3964 3965 hand = actp->sa_handler;
3965 3966 }
3966 3967
3967 3968 if ((actp->sa_flags & SA_RESETHAND) != 0) {
3968 3969 actp->sa_handler = SIG_DFL;
3969 3970 }
3970 3971
3971 3972 // try to honor the signal mask
3972 3973 sigset_t oset;
3973 3974 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3974 3975
3975 3976 // call into the chained handler
3976 3977 if (siginfo_flag_set) {
3977 3978 (*sa)(sig, siginfo, context);
3978 3979 } else {
3979 3980 (*hand)(sig);
3980 3981 }
3981 3982
3982 3983 // restore the signal mask
3983 3984 pthread_sigmask(SIG_SETMASK, &oset, 0);
3984 3985 }
3985 3986 // Tell jvm's signal handler the signal is taken care of.
3986 3987 return true;
3987 3988 }
3988 3989
3989 3990 bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3990 3991 bool chained = false;
3991 3992 // signal-chaining
3992 3993 if (UseSignalChaining) {
3993 3994 struct sigaction *actp = get_chained_signal_action(sig);
3994 3995 if (actp != NULL) {
3995 3996 chained = call_chained_handler(actp, sig, siginfo, context);
3996 3997 }
3997 3998 }
3998 3999 return chained;
3999 4000 }
4000 4001
4001 4002 struct sigaction* os::Linux::get_preinstalled_handler(int sig) {
4002 4003 if ((( (unsigned int)1 << sig ) & sigs) != 0) {
4003 4004 return &sigact[sig];
4004 4005 }
4005 4006 return NULL;
4006 4007 }
4007 4008
4008 4009 void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
4009 4010 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4010 4011 sigact[sig] = oldAct;
4011 4012 sigs |= (unsigned int)1 << sig;
4012 4013 }
4013 4014
4014 4015 // for diagnostic
4015 4016 int os::Linux::sigflags[MAXSIGNUM];
4016 4017
4017 4018 int os::Linux::get_our_sigflags(int sig) {
4018 4019 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4019 4020 return sigflags[sig];
4020 4021 }
4021 4022
4022 4023 void os::Linux::set_our_sigflags(int sig, int flags) {
4023 4024 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4024 4025 sigflags[sig] = flags;
4025 4026 }
4026 4027
4027 4028 void os::Linux::set_signal_handler(int sig, bool set_installed) {
4028 4029 // Check for overwrite.
4029 4030 struct sigaction oldAct;
4030 4031 sigaction(sig, (struct sigaction*)NULL, &oldAct);
4031 4032
4032 4033 void* oldhand = oldAct.sa_sigaction
4033 4034 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
4034 4035 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
4035 4036 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
4036 4037 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
4037 4038 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
4038 4039 if (AllowUserSignalHandlers || !set_installed) {
4039 4040 // Do not overwrite; user takes responsibility to forward to us.
4040 4041 return;
4041 4042 } else if (UseSignalChaining) {
4042 4043 // save the old handler in jvm
4043 4044 save_preinstalled_handler(sig, oldAct);
4044 4045 // libjsig also interposes the sigaction() call below and saves the
4045 4046 // old sigaction on it own.
4046 4047 } else {
4047 4048 fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
4048 4049 "%#lx for signal %d.", (long)oldhand, sig));
4049 4050 }
4050 4051 }
4051 4052
4052 4053 struct sigaction sigAct;
4053 4054 sigfillset(&(sigAct.sa_mask));
4054 4055 sigAct.sa_handler = SIG_DFL;
4055 4056 if (!set_installed) {
4056 4057 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4057 4058 } else {
4058 4059 sigAct.sa_sigaction = signalHandler;
4059 4060 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4060 4061 }
4061 4062 // Save flags, which are set by ours
4062 4063 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4063 4064 sigflags[sig] = sigAct.sa_flags;
4064 4065
4065 4066 int ret = sigaction(sig, &sigAct, &oldAct);
4066 4067 assert(ret == 0, "check");
4067 4068
4068 4069 void* oldhand2 = oldAct.sa_sigaction
4069 4070 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
4070 4071 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
4071 4072 assert(oldhand2 == oldhand, "no concurrent signal handler installation");
4072 4073 }
4073 4074
4074 4075 // install signal handlers for signals that HotSpot needs to
4075 4076 // handle in order to support Java-level exception handling.
4076 4077
4077 4078 void os::Linux::install_signal_handlers() {
4078 4079 if (!signal_handlers_are_installed) {
4079 4080 signal_handlers_are_installed = true;
4080 4081
4081 4082 // signal-chaining
4082 4083 typedef void (*signal_setting_t)();
4083 4084 signal_setting_t begin_signal_setting = NULL;
4084 4085 signal_setting_t end_signal_setting = NULL;
4085 4086 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4086 4087 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
4087 4088 if (begin_signal_setting != NULL) {
4088 4089 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4089 4090 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
4090 4091 get_signal_action = CAST_TO_FN_PTR(get_signal_t,
4091 4092 dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
4092 4093 libjsig_is_loaded = true;
4093 4094 assert(UseSignalChaining, "should enable signal-chaining");
4094 4095 }
4095 4096 if (libjsig_is_loaded) {
4096 4097 // Tell libjsig jvm is setting signal handlers
4097 4098 (*begin_signal_setting)();
4098 4099 }
4099 4100
4100 4101 set_signal_handler(SIGSEGV, true);
4101 4102 set_signal_handler(SIGPIPE, true);
4102 4103 set_signal_handler(SIGBUS, true);
4103 4104 set_signal_handler(SIGILL, true);
4104 4105 set_signal_handler(SIGFPE, true);
4105 4106 set_signal_handler(SIGXFSZ, true);
4106 4107
4107 4108 if (libjsig_is_loaded) {
4108 4109 // Tell libjsig jvm finishes setting signal handlers
4109 4110 (*end_signal_setting)();
4110 4111 }
4111 4112
4112 4113 // We don't activate signal checker if libjsig is in place, we trust ourselves
4113 4114 // and if UserSignalHandler is installed all bets are off.
4114 4115 // Log that signal checking is off only if -verbose:jni is specified.
4115 4116 if (CheckJNICalls) {
4116 4117 if (libjsig_is_loaded) {
4117 4118 if (PrintJNIResolving) {
4118 4119 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
4119 4120 }
4120 4121 check_signals = false;
4121 4122 }
4122 4123 if (AllowUserSignalHandlers) {
4123 4124 if (PrintJNIResolving) {
4124 4125 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
4125 4126 }
4126 4127 check_signals = false;
4127 4128 }
4128 4129 }
4129 4130 }
4130 4131 }
4131 4132
4132 4133 // This is the fastest way to get thread cpu time on Linux.
4133 4134 // Returns cpu time (user+sys) for any thread, not only for current.
4134 4135 // POSIX compliant clocks are implemented in the kernels 2.6.16+.
4135 4136 // It might work on 2.6.10+ with a special kernel/glibc patch.
4136 4137 // For reference, please, see IEEE Std 1003.1-2004:
4137 4138 // http://www.unix.org/single_unix_specification
4138 4139
4139 4140 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {
4140 4141 struct timespec tp;
4141 4142 int rc = os::Linux::clock_gettime(clockid, &tp);
4142 4143 assert(rc == 0, "clock_gettime is expected to return 0 code");
4143 4144
4144 4145 return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
4145 4146 }
4146 4147
4147 4148 /////
4148 4149 // glibc on Linux platform uses non-documented flag
4149 4150 // to indicate, that some special sort of signal
4150 4151 // trampoline is used.
4151 4152 // We will never set this flag, and we should
4152 4153 // ignore this flag in our diagnostic
4153 4154 #ifdef SIGNIFICANT_SIGNAL_MASK
4154 4155 #undef SIGNIFICANT_SIGNAL_MASK
4155 4156 #endif
4156 4157 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
4157 4158
4158 4159 static const char* get_signal_handler_name(address handler,
4159 4160 char* buf, int buflen) {
4160 4161 int offset;
4161 4162 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
4162 4163 if (found) {
4163 4164 // skip directory names
4164 4165 const char *p1, *p2;
4165 4166 p1 = buf;
4166 4167 size_t len = strlen(os::file_separator());
4167 4168 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
4168 4169 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
4169 4170 } else {
4170 4171 jio_snprintf(buf, buflen, PTR_FORMAT, handler);
4171 4172 }
4172 4173 return buf;
4173 4174 }
4174 4175
4175 4176 static void print_signal_handler(outputStream* st, int sig,
4176 4177 char* buf, size_t buflen) {
4177 4178 struct sigaction sa;
4178 4179
4179 4180 sigaction(sig, NULL, &sa);
4180 4181
4181 4182 // See comment for SIGNIFICANT_SIGNAL_MASK define
4182 4183 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4183 4184
4184 4185 st->print("%s: ", os::exception_name(sig, buf, buflen));
4185 4186
4186 4187 address handler = (sa.sa_flags & SA_SIGINFO)
4187 4188 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
4188 4189 : CAST_FROM_FN_PTR(address, sa.sa_handler);
4189 4190
4190 4191 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
4191 4192 st->print("SIG_DFL");
4192 4193 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
4193 4194 st->print("SIG_IGN");
4194 4195 } else {
4195 4196 st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
4196 4197 }
4197 4198
4198 4199 st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
4199 4200
4200 4201 address rh = VMError::get_resetted_sighandler(sig);
4201 4202 // May be, handler was resetted by VMError?
4202 4203 if(rh != NULL) {
4203 4204 handler = rh;
4204 4205 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
4205 4206 }
4206 4207
4207 4208 st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags);
4208 4209
4209 4210 // Check: is it our handler?
4210 4211 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
4211 4212 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
4212 4213 // It is our signal handler
4213 4214 // check for flags, reset system-used one!
4214 4215 if((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) {
4215 4216 st->print(
4216 4217 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
4217 4218 os::Linux::get_our_sigflags(sig));
4218 4219 }
4219 4220 }
4220 4221 st->cr();
4221 4222 }
4222 4223
4223 4224
4224 4225 #define DO_SIGNAL_CHECK(sig) \
4225 4226 if (!sigismember(&check_signal_done, sig)) \
4226 4227 os::Linux::check_signal_handler(sig)
4227 4228
4228 4229 // This method is a periodic task to check for misbehaving JNI applications
4229 4230 // under CheckJNI, we can add any periodic checks here
4230 4231
4231 4232 void os::run_periodic_checks() {
4232 4233
4233 4234 if (check_signals == false) return;
4234 4235
4235 4236 // SEGV and BUS if overridden could potentially prevent
4236 4237 // generation of hs*.log in the event of a crash, debugging
4237 4238 // such a case can be very challenging, so we absolutely
4238 4239 // check the following for a good measure:
4239 4240 DO_SIGNAL_CHECK(SIGSEGV);
4240 4241 DO_SIGNAL_CHECK(SIGILL);
4241 4242 DO_SIGNAL_CHECK(SIGFPE);
4242 4243 DO_SIGNAL_CHECK(SIGBUS);
4243 4244 DO_SIGNAL_CHECK(SIGPIPE);
4244 4245 DO_SIGNAL_CHECK(SIGXFSZ);
4245 4246
4246 4247
4247 4248 // ReduceSignalUsage allows the user to override these handlers
4248 4249 // see comments at the very top and jvm_solaris.h
4249 4250 if (!ReduceSignalUsage) {
4250 4251 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
4251 4252 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
4252 4253 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
4253 4254 DO_SIGNAL_CHECK(BREAK_SIGNAL);
4254 4255 }
4255 4256
4256 4257 DO_SIGNAL_CHECK(SR_signum);
4257 4258 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
4258 4259 }
4259 4260
4260 4261 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
4261 4262
4262 4263 static os_sigaction_t os_sigaction = NULL;
4263 4264
4264 4265 void os::Linux::check_signal_handler(int sig) {
4265 4266 char buf[O_BUFLEN];
4266 4267 address jvmHandler = NULL;
4267 4268
4268 4269
4269 4270 struct sigaction act;
4270 4271 if (os_sigaction == NULL) {
4271 4272 // only trust the default sigaction, in case it has been interposed
4272 4273 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
4273 4274 if (os_sigaction == NULL) return;
4274 4275 }
4275 4276
4276 4277 os_sigaction(sig, (struct sigaction*)NULL, &act);
4277 4278
4278 4279
4279 4280 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4280 4281
4281 4282 address thisHandler = (act.sa_flags & SA_SIGINFO)
4282 4283 ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
4283 4284 : CAST_FROM_FN_PTR(address, act.sa_handler) ;
4284 4285
4285 4286
4286 4287 switch(sig) {
4287 4288 case SIGSEGV:
4288 4289 case SIGBUS:
4289 4290 case SIGFPE:
4290 4291 case SIGPIPE:
4291 4292 case SIGILL:
4292 4293 case SIGXFSZ:
4293 4294 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
4294 4295 break;
4295 4296
4296 4297 case SHUTDOWN1_SIGNAL:
4297 4298 case SHUTDOWN2_SIGNAL:
4298 4299 case SHUTDOWN3_SIGNAL:
4299 4300 case BREAK_SIGNAL:
4300 4301 jvmHandler = (address)user_handler();
4301 4302 break;
4302 4303
4303 4304 case INTERRUPT_SIGNAL:
4304 4305 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
4305 4306 break;
4306 4307
4307 4308 default:
4308 4309 if (sig == SR_signum) {
4309 4310 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
4310 4311 } else {
4311 4312 return;
4312 4313 }
4313 4314 break;
4314 4315 }
4315 4316
4316 4317 if (thisHandler != jvmHandler) {
4317 4318 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
4318 4319 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
4319 4320 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
4320 4321 // No need to check this sig any longer
4321 4322 sigaddset(&check_signal_done, sig);
4322 4323 } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) {
4323 4324 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
4324 4325 tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig));
4325 4326 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);
4326 4327 // No need to check this sig any longer
4327 4328 sigaddset(&check_signal_done, sig);
4328 4329 }
4329 4330
4330 4331 // Dump all the signal
4331 4332 if (sigismember(&check_signal_done, sig)) {
4332 4333 print_signal_handlers(tty, buf, O_BUFLEN);
4333 4334 }
4334 4335 }
4335 4336
4336 4337 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
4337 4338
4338 4339 extern bool signal_name(int signo, char* buf, size_t len);
4339 4340
4340 4341 const char* os::exception_name(int exception_code, char* buf, size_t size) {
4341 4342 if (0 < exception_code && exception_code <= SIGRTMAX) {
4342 4343 // signal
4343 4344 if (!signal_name(exception_code, buf, size)) {
4344 4345 jio_snprintf(buf, size, "SIG%d", exception_code);
4345 4346 }
4346 4347 return buf;
4347 4348 } else {
4348 4349 return NULL;
4349 4350 }
4350 4351 }
4351 4352
4352 4353 // this is called _before_ the most of global arguments have been parsed
4353 4354 void os::init(void) {
4354 4355 char dummy; /* used to get a guess on initial stack address */
4355 4356 // first_hrtime = gethrtime();
4356 4357
4357 4358 // With LinuxThreads the JavaMain thread pid (primordial thread)
4358 4359 // is different than the pid of the java launcher thread.
4359 4360 // So, on Linux, the launcher thread pid is passed to the VM
4360 4361 // via the sun.java.launcher.pid property.
4361 4362 // Use this property instead of getpid() if it was correctly passed.
4362 4363 // See bug 6351349.
4363 4364 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
4364 4365
4365 4366 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
4366 4367
4367 4368 clock_tics_per_sec = sysconf(_SC_CLK_TCK);
4368 4369
4369 4370 init_random(1234567);
4370 4371
4371 4372 ThreadCritical::initialize();
4372 4373
4373 4374 Linux::set_page_size(sysconf(_SC_PAGESIZE));
4374 4375 if (Linux::page_size() == -1) {
4375 4376 fatal(err_msg("os_linux.cpp: os::init: sysconf failed (%s)",
4376 4377 strerror(errno)));
4377 4378 }
↓ open down ↓ |
4227 lines elided |
↑ open up ↑ |
4378 4379 init_page_sizes((size_t) Linux::page_size());
4379 4380
4380 4381 Linux::initialize_system_info();
4381 4382
4382 4383 // main_thread points to the aboriginal thread
4383 4384 Linux::_main_thread = pthread_self();
4384 4385
4385 4386 Linux::clock_init();
4386 4387 initial_time_count = os::elapsed_counter();
4387 4388 pthread_mutex_init(&dl_mutex, NULL);
4389 +
4390 + // If the pagesize of the VM is greater than 8K determine the appropriate
4391 + // number of initial guard pages. The user can change this with the
4392 + // command line arguments, if needed.
4393 + if (vm_page_size() > (int)Linux::vm_default_page_size()) {
4394 + StackYellowPages = 1;
4395 + StackRedPages = 1;
4396 + StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size();
4397 + }
4388 4398 }
4389 4399
4390 4400 // To install functions for atexit system call
4391 4401 extern "C" {
4392 4402 static void perfMemory_exit_helper() {
4393 4403 perfMemory_exit();
4394 4404 }
4395 4405 }
4396 4406
4397 4407 // this is called _after_ the global arguments have been parsed
4398 4408 jint os::init_2(void)
4399 4409 {
4400 4410 Linux::fast_thread_clock_init();
4401 4411
4402 4412 // Allocate a single page and mark it as readable for safepoint polling
4403 4413 address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4404 4414 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
4405 4415
4406 4416 os::set_polling_page( polling_page );
4407 4417
4408 4418 #ifndef PRODUCT
4409 4419 if(Verbose && PrintMiscellaneous)
4410 4420 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
4411 4421 #endif
4412 4422
4413 4423 if (!UseMembar) {
4414 4424 address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4415 4425 guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");
4416 4426 os::set_memory_serialize_page( mem_serialize_page );
4417 4427
4418 4428 #ifndef PRODUCT
4419 4429 if(Verbose && PrintMiscellaneous)
4420 4430 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
4421 4431 #endif
4422 4432 }
4423 4433
4424 4434 os::large_page_init();
4425 4435
4426 4436 // initialize suspend/resume support - must do this before signal_sets_init()
4427 4437 if (SR_initialize() != 0) {
4428 4438 perror("SR_initialize failed");
4429 4439 return JNI_ERR;
4430 4440 }
↓ open down ↓ |
33 lines elided |
↑ open up ↑ |
4431 4441
4432 4442 Linux::signal_sets_init();
4433 4443 Linux::install_signal_handlers();
4434 4444
4435 4445 // Check minimum allowable stack size for thread creation and to initialize
4436 4446 // the java system classes, including StackOverflowError - depends on page
4437 4447 // size. Add a page for compiler2 recursion in main thread.
4438 4448 // Add in 2*BytesPerWord times page size to account for VM stack during
4439 4449 // class initialization depending on 32 or 64 bit VM.
4440 4450 os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed,
4441 - (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
4442 - 2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::page_size());
4451 + (size_t)(StackYellowPages+StackRedPages+StackShadowPages) * Linux::page_size() +
4452 + (2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::vm_default_page_size());
4443 4453
4444 4454 size_t threadStackSizeInBytes = ThreadStackSize * K;
4445 4455 if (threadStackSizeInBytes != 0 &&
4446 4456 threadStackSizeInBytes < os::Linux::min_stack_allowed) {
4447 4457 tty->print_cr("\nThe stack size specified is too small, "
4448 4458 "Specify at least %dk",
4449 4459 os::Linux::min_stack_allowed/ K);
4450 4460 return JNI_ERR;
4451 4461 }
4452 4462
4453 4463 // Make the stack size a multiple of the page size so that
4454 4464 // the yellow/red zones can be guarded.
4455 4465 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
4456 4466 vm_page_size()));
4457 4467
4458 4468 Linux::capture_initial_stack(JavaThread::stack_size_at_create());
4459 4469
4460 4470 Linux::libpthread_init();
4461 4471 if (PrintMiscellaneous && (Verbose || WizardMode)) {
4462 4472 tty->print_cr("[HotSpot is running with %s, %s(%s)]\n",
4463 4473 Linux::glibc_version(), Linux::libpthread_version(),
4464 4474 Linux::is_floating_stack() ? "floating stack" : "fixed stack");
4465 4475 }
4466 4476
4467 4477 if (UseNUMA) {
4468 4478 if (!Linux::libnuma_init()) {
4469 4479 UseNUMA = false;
4470 4480 } else {
4471 4481 if ((Linux::numa_max_node() < 1)) {
4472 4482 // There's only one node(they start from 0), disable NUMA.
4473 4483 UseNUMA = false;
4474 4484 }
4475 4485 }
4476 4486 // With SHM large pages we cannot uncommit a page, so there's not way
4477 4487 // we can make the adaptive lgrp chunk resizing work. If the user specified
4478 4488 // both UseNUMA and UseLargePages (or UseSHM) on the command line - warn and
4479 4489 // disable adaptive resizing.
4480 4490 if (UseNUMA && UseLargePages && UseSHM) {
4481 4491 if (!FLAG_IS_DEFAULT(UseNUMA)) {
4482 4492 if (FLAG_IS_DEFAULT(UseLargePages) && FLAG_IS_DEFAULT(UseSHM)) {
4483 4493 UseLargePages = false;
4484 4494 } else {
4485 4495 warning("UseNUMA is not fully compatible with SHM large pages, disabling adaptive resizing");
4486 4496 UseAdaptiveSizePolicy = false;
4487 4497 UseAdaptiveNUMAChunkSizing = false;
4488 4498 }
4489 4499 } else {
4490 4500 UseNUMA = false;
4491 4501 }
4492 4502 }
4493 4503 if (!UseNUMA && ForceNUMA) {
4494 4504 UseNUMA = true;
4495 4505 }
4496 4506 }
4497 4507
4498 4508 if (MaxFDLimit) {
4499 4509 // set the number of file descriptors to max. print out error
4500 4510 // if getrlimit/setrlimit fails but continue regardless.
4501 4511 struct rlimit nbr_files;
4502 4512 int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4503 4513 if (status != 0) {
4504 4514 if (PrintMiscellaneous && (Verbose || WizardMode))
4505 4515 perror("os::init_2 getrlimit failed");
4506 4516 } else {
4507 4517 nbr_files.rlim_cur = nbr_files.rlim_max;
4508 4518 status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4509 4519 if (status != 0) {
4510 4520 if (PrintMiscellaneous && (Verbose || WizardMode))
4511 4521 perror("os::init_2 setrlimit failed");
4512 4522 }
4513 4523 }
4514 4524 }
4515 4525
4516 4526 // Initialize lock used to serialize thread creation (see os::create_thread)
4517 4527 Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false));
4518 4528
4519 4529 // at-exit methods are called in the reverse order of their registration.
4520 4530 // atexit functions are called on return from main or as a result of a
4521 4531 // call to exit(3C). There can be only 32 of these functions registered
4522 4532 // and atexit() does not set errno.
4523 4533
4524 4534 if (PerfAllowAtExitRegistration) {
4525 4535 // only register atexit functions if PerfAllowAtExitRegistration is set.
4526 4536 // atexit functions can be delayed until process exit time, which
4527 4537 // can be problematic for embedded VM situations. Embedded VMs should
4528 4538 // call DestroyJavaVM() to assure that VM resources are released.
4529 4539
4530 4540 // note: perfMemory_exit_helper atexit function may be removed in
4531 4541 // the future if the appropriate cleanup code can be added to the
4532 4542 // VM_Exit VMOperation's doit method.
4533 4543 if (atexit(perfMemory_exit_helper) != 0) {
4534 4544 warning("os::init2 atexit(perfMemory_exit_helper) failed");
4535 4545 }
4536 4546 }
4537 4547
4538 4548 // initialize thread priority policy
4539 4549 prio_init();
4540 4550
4541 4551 return JNI_OK;
4542 4552 }
4543 4553
4544 4554 // this is called at the end of vm_initialization
4545 4555 void os::init_3(void)
4546 4556 {
4547 4557 #ifdef JAVASE_EMBEDDED
4548 4558 // Start the MemNotifyThread
4549 4559 if (LowMemoryProtection) {
4550 4560 MemNotifyThread::start();
4551 4561 }
4552 4562 return;
4553 4563 #endif
4554 4564 }
4555 4565
4556 4566 // Mark the polling page as unreadable
4557 4567 void os::make_polling_page_unreadable(void) {
4558 4568 if( !guard_memory((char*)_polling_page, Linux::page_size()) )
4559 4569 fatal("Could not disable polling page");
4560 4570 };
4561 4571
4562 4572 // Mark the polling page as readable
4563 4573 void os::make_polling_page_readable(void) {
4564 4574 if( !linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) {
4565 4575 fatal("Could not enable polling page");
4566 4576 }
4567 4577 };
4568 4578
4569 4579 int os::active_processor_count() {
4570 4580 // Linux doesn't yet have a (official) notion of processor sets,
4571 4581 // so just return the number of online processors.
4572 4582 int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
4573 4583 assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
4574 4584 return online_cpus;
4575 4585 }
4576 4586
4577 4587 void os::set_native_thread_name(const char *name) {
4578 4588 // Not yet implemented.
4579 4589 return;
4580 4590 }
4581 4591
4582 4592 bool os::distribute_processes(uint length, uint* distribution) {
4583 4593 // Not yet implemented.
4584 4594 return false;
4585 4595 }
4586 4596
4587 4597 bool os::bind_to_processor(uint processor_id) {
4588 4598 // Not yet implemented.
4589 4599 return false;
4590 4600 }
4591 4601
4592 4602 ///
4593 4603
4594 4604 void os::SuspendedThreadTask::internal_do_task() {
4595 4605 if (do_suspend(_thread->osthread())) {
4596 4606 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
4597 4607 do_task(context);
4598 4608 do_resume(_thread->osthread());
4599 4609 }
4600 4610 }
4601 4611
4602 4612 class PcFetcher : public os::SuspendedThreadTask {
4603 4613 public:
4604 4614 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
4605 4615 ExtendedPC result();
4606 4616 protected:
4607 4617 void do_task(const os::SuspendedThreadTaskContext& context);
4608 4618 private:
4609 4619 ExtendedPC _epc;
4610 4620 };
4611 4621
4612 4622 ExtendedPC PcFetcher::result() {
4613 4623 guarantee(is_done(), "task is not done yet.");
4614 4624 return _epc;
4615 4625 }
4616 4626
4617 4627 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
4618 4628 Thread* thread = context.thread();
4619 4629 OSThread* osthread = thread->osthread();
4620 4630 if (osthread->ucontext() != NULL) {
4621 4631 _epc = os::Linux::ucontext_get_pc((ucontext_t *) context.ucontext());
4622 4632 } else {
4623 4633 // NULL context is unexpected, double-check this is the VMThread
4624 4634 guarantee(thread->is_VM_thread(), "can only be called for VMThread");
4625 4635 }
4626 4636 }
4627 4637
4628 4638 // Suspends the target using the signal mechanism and then grabs the PC before
4629 4639 // resuming the target. Used by the flat-profiler only
4630 4640 ExtendedPC os::get_thread_pc(Thread* thread) {
4631 4641 // Make sure that it is called by the watcher for the VMThread
4632 4642 assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
4633 4643 assert(thread->is_VM_thread(), "Can only be called for VMThread");
4634 4644
4635 4645 PcFetcher fetcher(thread);
4636 4646 fetcher.run();
4637 4647 return fetcher.result();
4638 4648 }
4639 4649
4640 4650 int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
4641 4651 {
4642 4652 if (is_NPTL()) {
4643 4653 return pthread_cond_timedwait(_cond, _mutex, _abstime);
4644 4654 } else {
4645 4655 #ifndef IA64
4646 4656 // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control
4647 4657 // word back to default 64bit precision if condvar is signaled. Java
4648 4658 // wants 53bit precision. Save and restore current value.
4649 4659 int fpu = get_fpu_control_word();
4650 4660 #endif // IA64
4651 4661 int status = pthread_cond_timedwait(_cond, _mutex, _abstime);
4652 4662 #ifndef IA64
4653 4663 set_fpu_control_word(fpu);
4654 4664 #endif // IA64
4655 4665 return status;
4656 4666 }
4657 4667 }
4658 4668
4659 4669 ////////////////////////////////////////////////////////////////////////////////
4660 4670 // debug support
4661 4671
4662 4672 static address same_page(address x, address y) {
4663 4673 int page_bits = -os::vm_page_size();
4664 4674 if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
4665 4675 return x;
4666 4676 else if (x > y)
4667 4677 return (address)(intptr_t(y) | ~page_bits) + 1;
4668 4678 else
4669 4679 return (address)(intptr_t(y) & page_bits);
4670 4680 }
4671 4681
4672 4682 bool os::find(address addr, outputStream* st) {
4673 4683 Dl_info dlinfo;
4674 4684 memset(&dlinfo, 0, sizeof(dlinfo));
4675 4685 if (dladdr(addr, &dlinfo)) {
4676 4686 st->print(PTR_FORMAT ": ", addr);
4677 4687 if (dlinfo.dli_sname != NULL) {
4678 4688 st->print("%s+%#x", dlinfo.dli_sname,
4679 4689 addr - (intptr_t)dlinfo.dli_saddr);
4680 4690 } else if (dlinfo.dli_fname) {
4681 4691 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
4682 4692 } else {
4683 4693 st->print("<absolute address>");
4684 4694 }
4685 4695 if (dlinfo.dli_fname) {
4686 4696 st->print(" in %s", dlinfo.dli_fname);
4687 4697 }
4688 4698 if (dlinfo.dli_fbase) {
4689 4699 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
4690 4700 }
4691 4701 st->cr();
4692 4702
4693 4703 if (Verbose) {
4694 4704 // decode some bytes around the PC
4695 4705 address begin = same_page(addr-40, addr);
4696 4706 address end = same_page(addr+40, addr);
4697 4707 address lowest = (address) dlinfo.dli_sname;
4698 4708 if (!lowest) lowest = (address) dlinfo.dli_fbase;
4699 4709 if (begin < lowest) begin = lowest;
4700 4710 Dl_info dlinfo2;
4701 4711 if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr
4702 4712 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
4703 4713 end = (address) dlinfo2.dli_saddr;
4704 4714 Disassembler::decode(begin, end, st);
4705 4715 }
4706 4716 return true;
4707 4717 }
4708 4718 return false;
4709 4719 }
4710 4720
4711 4721 ////////////////////////////////////////////////////////////////////////////////
4712 4722 // misc
4713 4723
4714 4724 // This does not do anything on Linux. This is basically a hook for being
4715 4725 // able to use structured exception handling (thread-local exception filters)
4716 4726 // on, e.g., Win32.
4717 4727 void
4718 4728 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
4719 4729 JavaCallArguments* args, Thread* thread) {
4720 4730 f(value, method, args, thread);
4721 4731 }
4722 4732
4723 4733 void os::print_statistics() {
4724 4734 }
4725 4735
4726 4736 int os::message_box(const char* title, const char* message) {
4727 4737 int i;
4728 4738 fdStream err(defaultStream::error_fd());
4729 4739 for (i = 0; i < 78; i++) err.print_raw("=");
4730 4740 err.cr();
4731 4741 err.print_raw_cr(title);
4732 4742 for (i = 0; i < 78; i++) err.print_raw("-");
4733 4743 err.cr();
4734 4744 err.print_raw_cr(message);
4735 4745 for (i = 0; i < 78; i++) err.print_raw("=");
4736 4746 err.cr();
4737 4747
4738 4748 char buf[16];
4739 4749 // Prevent process from exiting upon "read error" without consuming all CPU
4740 4750 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
4741 4751
4742 4752 return buf[0] == 'y' || buf[0] == 'Y';
4743 4753 }
4744 4754
4745 4755 int os::stat(const char *path, struct stat *sbuf) {
4746 4756 char pathbuf[MAX_PATH];
4747 4757 if (strlen(path) > MAX_PATH - 1) {
4748 4758 errno = ENAMETOOLONG;
4749 4759 return -1;
4750 4760 }
4751 4761 os::native_path(strcpy(pathbuf, path));
4752 4762 return ::stat(pathbuf, sbuf);
4753 4763 }
4754 4764
4755 4765 bool os::check_heap(bool force) {
4756 4766 return true;
4757 4767 }
4758 4768
4759 4769 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
4760 4770 return ::vsnprintf(buf, count, format, args);
4761 4771 }
4762 4772
4763 4773 // Is a (classpath) directory empty?
4764 4774 bool os::dir_is_empty(const char* path) {
4765 4775 DIR *dir = NULL;
4766 4776 struct dirent *ptr;
4767 4777
4768 4778 dir = opendir(path);
4769 4779 if (dir == NULL) return true;
4770 4780
4771 4781 /* Scan the directory */
4772 4782 bool result = true;
4773 4783 char buf[sizeof(struct dirent) + MAX_PATH];
4774 4784 while (result && (ptr = ::readdir(dir)) != NULL) {
4775 4785 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
4776 4786 result = false;
4777 4787 }
4778 4788 }
4779 4789 closedir(dir);
4780 4790 return result;
4781 4791 }
4782 4792
4783 4793 // This code originates from JDK's sysOpen and open64_w
4784 4794 // from src/solaris/hpi/src/system_md.c
4785 4795
4786 4796 #ifndef O_DELETE
4787 4797 #define O_DELETE 0x10000
4788 4798 #endif
4789 4799
4790 4800 // Open a file. Unlink the file immediately after open returns
4791 4801 // if the specified oflag has the O_DELETE flag set.
4792 4802 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
4793 4803
4794 4804 int os::open(const char *path, int oflag, int mode) {
4795 4805
4796 4806 if (strlen(path) > MAX_PATH - 1) {
4797 4807 errno = ENAMETOOLONG;
4798 4808 return -1;
4799 4809 }
4800 4810 int fd;
4801 4811 int o_delete = (oflag & O_DELETE);
4802 4812 oflag = oflag & ~O_DELETE;
4803 4813
4804 4814 fd = ::open64(path, oflag, mode);
4805 4815 if (fd == -1) return -1;
4806 4816
4807 4817 //If the open succeeded, the file might still be a directory
4808 4818 {
4809 4819 struct stat64 buf64;
4810 4820 int ret = ::fstat64(fd, &buf64);
4811 4821 int st_mode = buf64.st_mode;
4812 4822
4813 4823 if (ret != -1) {
4814 4824 if ((st_mode & S_IFMT) == S_IFDIR) {
4815 4825 errno = EISDIR;
4816 4826 ::close(fd);
4817 4827 return -1;
4818 4828 }
4819 4829 } else {
4820 4830 ::close(fd);
4821 4831 return -1;
4822 4832 }
4823 4833 }
4824 4834
4825 4835 /*
4826 4836 * All file descriptors that are opened in the JVM and not
4827 4837 * specifically destined for a subprocess should have the
4828 4838 * close-on-exec flag set. If we don't set it, then careless 3rd
4829 4839 * party native code might fork and exec without closing all
4830 4840 * appropriate file descriptors (e.g. as we do in closeDescriptors in
4831 4841 * UNIXProcess.c), and this in turn might:
4832 4842 *
4833 4843 * - cause end-of-file to fail to be detected on some file
4834 4844 * descriptors, resulting in mysterious hangs, or
4835 4845 *
4836 4846 * - might cause an fopen in the subprocess to fail on a system
4837 4847 * suffering from bug 1085341.
4838 4848 *
4839 4849 * (Yes, the default setting of the close-on-exec flag is a Unix
4840 4850 * design flaw)
4841 4851 *
4842 4852 * See:
4843 4853 * 1085341: 32-bit stdio routines should support file descriptors >255
4844 4854 * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
4845 4855 * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
4846 4856 */
4847 4857 #ifdef FD_CLOEXEC
4848 4858 {
4849 4859 int flags = ::fcntl(fd, F_GETFD);
4850 4860 if (flags != -1)
4851 4861 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4852 4862 }
4853 4863 #endif
4854 4864
4855 4865 if (o_delete != 0) {
4856 4866 ::unlink(path);
4857 4867 }
4858 4868 return fd;
4859 4869 }
4860 4870
4861 4871
4862 4872 // create binary file, rewriting existing file if required
4863 4873 int os::create_binary_file(const char* path, bool rewrite_existing) {
4864 4874 int oflags = O_WRONLY | O_CREAT;
4865 4875 if (!rewrite_existing) {
4866 4876 oflags |= O_EXCL;
4867 4877 }
4868 4878 return ::open64(path, oflags, S_IREAD | S_IWRITE);
4869 4879 }
4870 4880
4871 4881 // return current position of file pointer
4872 4882 jlong os::current_file_offset(int fd) {
4873 4883 return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
4874 4884 }
4875 4885
4876 4886 // move file pointer to the specified offset
4877 4887 jlong os::seek_to_file_offset(int fd, jlong offset) {
4878 4888 return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
4879 4889 }
4880 4890
4881 4891 // This code originates from JDK's sysAvailable
4882 4892 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
4883 4893
4884 4894 int os::available(int fd, jlong *bytes) {
4885 4895 jlong cur, end;
4886 4896 int mode;
4887 4897 struct stat64 buf64;
4888 4898
4889 4899 if (::fstat64(fd, &buf64) >= 0) {
4890 4900 mode = buf64.st_mode;
4891 4901 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4892 4902 /*
4893 4903 * XXX: is the following call interruptible? If so, this might
4894 4904 * need to go through the INTERRUPT_IO() wrapper as for other
4895 4905 * blocking, interruptible calls in this file.
4896 4906 */
4897 4907 int n;
4898 4908 if (::ioctl(fd, FIONREAD, &n) >= 0) {
4899 4909 *bytes = n;
4900 4910 return 1;
4901 4911 }
4902 4912 }
4903 4913 }
4904 4914 if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
4905 4915 return 0;
4906 4916 } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
4907 4917 return 0;
4908 4918 } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
4909 4919 return 0;
4910 4920 }
4911 4921 *bytes = end - cur;
4912 4922 return 1;
4913 4923 }
4914 4924
4915 4925 int os::socket_available(int fd, jint *pbytes) {
4916 4926 // Linux doc says EINTR not returned, unlike Solaris
4917 4927 int ret = ::ioctl(fd, FIONREAD, pbytes);
4918 4928
4919 4929 //%% note ioctl can return 0 when successful, JVM_SocketAvailable
4920 4930 // is expected to return 0 on failure and 1 on success to the jdk.
4921 4931 return (ret < 0) ? 0 : 1;
4922 4932 }
4923 4933
4924 4934 // Map a block of memory.
4925 4935 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4926 4936 char *addr, size_t bytes, bool read_only,
4927 4937 bool allow_exec) {
4928 4938 int prot;
4929 4939 int flags = MAP_PRIVATE;
4930 4940
4931 4941 if (read_only) {
4932 4942 prot = PROT_READ;
4933 4943 } else {
4934 4944 prot = PROT_READ | PROT_WRITE;
4935 4945 }
4936 4946
4937 4947 if (allow_exec) {
4938 4948 prot |= PROT_EXEC;
4939 4949 }
4940 4950
4941 4951 if (addr != NULL) {
4942 4952 flags |= MAP_FIXED;
4943 4953 }
4944 4954
4945 4955 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4946 4956 fd, file_offset);
4947 4957 if (mapped_address == MAP_FAILED) {
4948 4958 return NULL;
4949 4959 }
4950 4960 return mapped_address;
4951 4961 }
4952 4962
4953 4963
4954 4964 // Remap a block of memory.
4955 4965 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4956 4966 char *addr, size_t bytes, bool read_only,
4957 4967 bool allow_exec) {
4958 4968 // same as map_memory() on this OS
4959 4969 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4960 4970 allow_exec);
4961 4971 }
4962 4972
4963 4973
4964 4974 // Unmap a block of memory.
4965 4975 bool os::pd_unmap_memory(char* addr, size_t bytes) {
4966 4976 return munmap(addr, bytes) == 0;
4967 4977 }
4968 4978
4969 4979 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
4970 4980
4971 4981 static clockid_t thread_cpu_clockid(Thread* thread) {
4972 4982 pthread_t tid = thread->osthread()->pthread_id();
4973 4983 clockid_t clockid;
4974 4984
4975 4985 // Get thread clockid
4976 4986 int rc = os::Linux::pthread_getcpuclockid(tid, &clockid);
4977 4987 assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code");
4978 4988 return clockid;
4979 4989 }
4980 4990
4981 4991 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
4982 4992 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
4983 4993 // of a thread.
4984 4994 //
4985 4995 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
4986 4996 // the fast estimate available on the platform.
4987 4997
4988 4998 jlong os::current_thread_cpu_time() {
4989 4999 if (os::Linux::supports_fast_thread_cpu_time()) {
4990 5000 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
4991 5001 } else {
4992 5002 // return user + sys since the cost is the same
4993 5003 return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
4994 5004 }
4995 5005 }
4996 5006
4997 5007 jlong os::thread_cpu_time(Thread* thread) {
4998 5008 // consistent with what current_thread_cpu_time() returns
4999 5009 if (os::Linux::supports_fast_thread_cpu_time()) {
5000 5010 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5001 5011 } else {
5002 5012 return slow_thread_cpu_time(thread, true /* user + sys */);
5003 5013 }
5004 5014 }
5005 5015
5006 5016 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5007 5017 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5008 5018 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5009 5019 } else {
5010 5020 return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
5011 5021 }
5012 5022 }
5013 5023
5014 5024 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5015 5025 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5016 5026 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5017 5027 } else {
5018 5028 return slow_thread_cpu_time(thread, user_sys_cpu_time);
5019 5029 }
5020 5030 }
5021 5031
5022 5032 //
5023 5033 // -1 on error.
5024 5034 //
5025 5035
5026 5036 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5027 5037 static bool proc_pid_cpu_avail = true;
5028 5038 static bool proc_task_unchecked = true;
5029 5039 static const char *proc_stat_path = "/proc/%d/stat";
5030 5040 pid_t tid = thread->osthread()->thread_id();
5031 5041 int i;
5032 5042 char *s;
5033 5043 char stat[2048];
5034 5044 int statlen;
5035 5045 char proc_name[64];
5036 5046 int count;
5037 5047 long sys_time, user_time;
5038 5048 char string[64];
5039 5049 char cdummy;
5040 5050 int idummy;
5041 5051 long ldummy;
5042 5052 FILE *fp;
5043 5053
5044 5054 // We first try accessing /proc/<pid>/cpu since this is faster to
5045 5055 // process. If this file is not present (linux kernels 2.5 and above)
5046 5056 // then we open /proc/<pid>/stat.
5047 5057 if ( proc_pid_cpu_avail ) {
5048 5058 sprintf(proc_name, "/proc/%d/cpu", tid);
5049 5059 fp = fopen(proc_name, "r");
5050 5060 if ( fp != NULL ) {
5051 5061 count = fscanf( fp, "%s %lu %lu\n", string, &user_time, &sys_time);
5052 5062 fclose(fp);
5053 5063 if ( count != 3 ) return -1;
5054 5064
5055 5065 if (user_sys_cpu_time) {
5056 5066 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5057 5067 } else {
5058 5068 return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5059 5069 }
5060 5070 }
5061 5071 else proc_pid_cpu_avail = false;
5062 5072 }
5063 5073
5064 5074 // The /proc/<tid>/stat aggregates per-process usage on
5065 5075 // new Linux kernels 2.6+ where NPTL is supported.
5066 5076 // The /proc/self/task/<tid>/stat still has the per-thread usage.
5067 5077 // See bug 6328462.
5068 5078 // There can be no directory /proc/self/task on kernels 2.4 with NPTL
5069 5079 // and possibly in some other cases, so we check its availability.
5070 5080 if (proc_task_unchecked && os::Linux::is_NPTL()) {
5071 5081 // This is executed only once
5072 5082 proc_task_unchecked = false;
5073 5083 fp = fopen("/proc/self/task", "r");
5074 5084 if (fp != NULL) {
5075 5085 proc_stat_path = "/proc/self/task/%d/stat";
5076 5086 fclose(fp);
5077 5087 }
5078 5088 }
5079 5089
5080 5090 sprintf(proc_name, proc_stat_path, tid);
5081 5091 fp = fopen(proc_name, "r");
5082 5092 if ( fp == NULL ) return -1;
5083 5093 statlen = fread(stat, 1, 2047, fp);
5084 5094 stat[statlen] = '\0';
5085 5095 fclose(fp);
5086 5096
5087 5097 // Skip pid and the command string. Note that we could be dealing with
5088 5098 // weird command names, e.g. user could decide to rename java launcher
5089 5099 // to "java 1.4.2 :)", then the stat file would look like
5090 5100 // 1234 (java 1.4.2 :)) R ... ...
5091 5101 // We don't really need to know the command string, just find the last
5092 5102 // occurrence of ")" and then start parsing from there. See bug 4726580.
5093 5103 s = strrchr(stat, ')');
5094 5104 i = 0;
5095 5105 if (s == NULL ) return -1;
5096 5106
5097 5107 // Skip blank chars
5098 5108 do s++; while (isspace(*s));
5099 5109
5100 5110 count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
5101 5111 &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
5102 5112 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
5103 5113 &user_time, &sys_time);
5104 5114 if ( count != 13 ) return -1;
5105 5115 if (user_sys_cpu_time) {
5106 5116 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5107 5117 } else {
5108 5118 return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5109 5119 }
5110 5120 }
5111 5121
5112 5122 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5113 5123 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
5114 5124 info_ptr->may_skip_backward = false; // elapsed time not wall time
5115 5125 info_ptr->may_skip_forward = false; // elapsed time not wall time
5116 5126 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
5117 5127 }
5118 5128
5119 5129 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5120 5130 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
5121 5131 info_ptr->may_skip_backward = false; // elapsed time not wall time
5122 5132 info_ptr->may_skip_forward = false; // elapsed time not wall time
5123 5133 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
5124 5134 }
5125 5135
5126 5136 bool os::is_thread_cpu_time_supported() {
5127 5137 return true;
5128 5138 }
5129 5139
5130 5140 // System loadavg support. Returns -1 if load average cannot be obtained.
5131 5141 // Linux doesn't yet have a (official) notion of processor sets,
5132 5142 // so just return the system wide load average.
5133 5143 int os::loadavg(double loadavg[], int nelem) {
5134 5144 return ::getloadavg(loadavg, nelem);
5135 5145 }
5136 5146
5137 5147 void os::pause() {
5138 5148 char filename[MAX_PATH];
5139 5149 if (PauseAtStartupFile && PauseAtStartupFile[0]) {
5140 5150 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
5141 5151 } else {
5142 5152 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
5143 5153 }
5144 5154
5145 5155 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
5146 5156 if (fd != -1) {
5147 5157 struct stat buf;
5148 5158 ::close(fd);
5149 5159 while (::stat(filename, &buf) == 0) {
5150 5160 (void)::poll(NULL, 0, 100);
5151 5161 }
5152 5162 } else {
5153 5163 jio_fprintf(stderr,
5154 5164 "Could not open pause file '%s', continuing immediately.\n", filename);
5155 5165 }
5156 5166 }
5157 5167
5158 5168
5159 5169 // Refer to the comments in os_solaris.cpp park-unpark.
5160 5170 //
5161 5171 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
5162 5172 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
5163 5173 // For specifics regarding the bug see GLIBC BUGID 261237 :
5164 5174 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
5165 5175 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
5166 5176 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
5167 5177 // is used. (The simple C test-case provided in the GLIBC bug report manifests the
5168 5178 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
5169 5179 // and monitorenter when we're using 1-0 locking. All those operations may result in
5170 5180 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version
5171 5181 // of libpthread avoids the problem, but isn't practical.
5172 5182 //
5173 5183 // Possible remedies:
5174 5184 //
5175 5185 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.
5176 5186 // This is palliative and probabilistic, however. If the thread is preempted
5177 5187 // between the call to compute_abstime() and pthread_cond_timedwait(), more
5178 5188 // than the minimum period may have passed, and the abstime may be stale (in the
5179 5189 // past) resultin in a hang. Using this technique reduces the odds of a hang
5180 5190 // but the JVM is still vulnerable, particularly on heavily loaded systems.
5181 5191 //
5182 5192 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
5183 5193 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set
5184 5194 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
5185 5195 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant
5186 5196 // thread.
5187 5197 //
5188 5198 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread
5189 5199 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing
5190 5200 // a timeout request to the chron thread and then blocking via pthread_cond_wait().
5191 5201 // This also works well. In fact it avoids kernel-level scalability impediments
5192 5202 // on certain platforms that don't handle lots of active pthread_cond_timedwait()
5193 5203 // timers in a graceful fashion.
5194 5204 //
5195 5205 // 4. When the abstime value is in the past it appears that control returns
5196 5206 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
5197 5207 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we
5198 5208 // can avoid the problem by reinitializing the condvar -- by cond_destroy()
5199 5209 // followed by cond_init() -- after all calls to pthread_cond_timedwait().
5200 5210 // It may be possible to avoid reinitialization by checking the return
5201 5211 // value from pthread_cond_timedwait(). In addition to reinitializing the
5202 5212 // condvar we must establish the invariant that cond_signal() is only called
5203 5213 // within critical sections protected by the adjunct mutex. This prevents
5204 5214 // cond_signal() from "seeing" a condvar that's in the midst of being
5205 5215 // reinitialized or that is corrupt. Sadly, this invariant obviates the
5206 5216 // desirable signal-after-unlock optimization that avoids futile context switching.
5207 5217 //
5208 5218 // I'm also concerned that some versions of NTPL might allocate an auxilliary
5209 5219 // structure when a condvar is used or initialized. cond_destroy() would
5210 5220 // release the helper structure. Our reinitialize-after-timedwait fix
5211 5221 // put excessive stress on malloc/free and locks protecting the c-heap.
5212 5222 //
5213 5223 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.
5214 5224 // It may be possible to refine (4) by checking the kernel and NTPL verisons
5215 5225 // and only enabling the work-around for vulnerable environments.
5216 5226
5217 5227 // utility to compute the abstime argument to timedwait:
5218 5228 // millis is the relative timeout time
5219 5229 // abstime will be the absolute timeout time
5220 5230 // TODO: replace compute_abstime() with unpackTime()
5221 5231
5222 5232 static struct timespec* compute_abstime(timespec* abstime, jlong millis) {
5223 5233 if (millis < 0) millis = 0;
5224 5234 struct timeval now;
5225 5235 int status = gettimeofday(&now, NULL);
5226 5236 assert(status == 0, "gettimeofday");
5227 5237 jlong seconds = millis / 1000;
5228 5238 millis %= 1000;
5229 5239 if (seconds > 50000000) { // see man cond_timedwait(3T)
5230 5240 seconds = 50000000;
5231 5241 }
5232 5242 abstime->tv_sec = now.tv_sec + seconds;
5233 5243 long usec = now.tv_usec + millis * 1000;
5234 5244 if (usec >= 1000000) {
5235 5245 abstime->tv_sec += 1;
5236 5246 usec -= 1000000;
5237 5247 }
5238 5248 abstime->tv_nsec = usec * 1000;
5239 5249 return abstime;
5240 5250 }
5241 5251
5242 5252
5243 5253 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
5244 5254 // Conceptually TryPark() should be equivalent to park(0).
5245 5255
5246 5256 int os::PlatformEvent::TryPark() {
5247 5257 for (;;) {
5248 5258 const int v = _Event ;
5249 5259 guarantee ((v == 0) || (v == 1), "invariant") ;
5250 5260 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;
5251 5261 }
5252 5262 }
5253 5263
5254 5264 void os::PlatformEvent::park() { // AKA "down()"
5255 5265 // Invariant: Only the thread associated with the Event/PlatformEvent
5256 5266 // may call park().
5257 5267 // TODO: assert that _Assoc != NULL or _Assoc == Self
5258 5268 int v ;
5259 5269 for (;;) {
5260 5270 v = _Event ;
5261 5271 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
5262 5272 }
5263 5273 guarantee (v >= 0, "invariant") ;
5264 5274 if (v == 0) {
5265 5275 // Do this the hard way by blocking ...
5266 5276 int status = pthread_mutex_lock(_mutex);
5267 5277 assert_status(status == 0, status, "mutex_lock");
5268 5278 guarantee (_nParked == 0, "invariant") ;
5269 5279 ++ _nParked ;
5270 5280 while (_Event < 0) {
5271 5281 status = pthread_cond_wait(_cond, _mutex);
5272 5282 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
5273 5283 // Treat this the same as if the wait was interrupted
5274 5284 if (status == ETIME) { status = EINTR; }
5275 5285 assert_status(status == 0 || status == EINTR, status, "cond_wait");
5276 5286 }
5277 5287 -- _nParked ;
5278 5288
5279 5289 _Event = 0 ;
5280 5290 status = pthread_mutex_unlock(_mutex);
5281 5291 assert_status(status == 0, status, "mutex_unlock");
5282 5292 // Paranoia to ensure our locked and lock-free paths interact
5283 5293 // correctly with each other.
5284 5294 OrderAccess::fence();
5285 5295 }
5286 5296 guarantee (_Event >= 0, "invariant") ;
5287 5297 }
5288 5298
5289 5299 int os::PlatformEvent::park(jlong millis) {
5290 5300 guarantee (_nParked == 0, "invariant") ;
5291 5301
5292 5302 int v ;
5293 5303 for (;;) {
5294 5304 v = _Event ;
5295 5305 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
5296 5306 }
5297 5307 guarantee (v >= 0, "invariant") ;
5298 5308 if (v != 0) return OS_OK ;
5299 5309
5300 5310 // We do this the hard way, by blocking the thread.
5301 5311 // Consider enforcing a minimum timeout value.
5302 5312 struct timespec abst;
5303 5313 compute_abstime(&abst, millis);
5304 5314
5305 5315 int ret = OS_TIMEOUT;
5306 5316 int status = pthread_mutex_lock(_mutex);
5307 5317 assert_status(status == 0, status, "mutex_lock");
5308 5318 guarantee (_nParked == 0, "invariant") ;
5309 5319 ++_nParked ;
5310 5320
5311 5321 // Object.wait(timo) will return because of
5312 5322 // (a) notification
5313 5323 // (b) timeout
5314 5324 // (c) thread.interrupt
5315 5325 //
5316 5326 // Thread.interrupt and object.notify{All} both call Event::set.
5317 5327 // That is, we treat thread.interrupt as a special case of notification.
5318 5328 // The underlying Solaris implementation, cond_timedwait, admits
5319 5329 // spurious/premature wakeups, but the JLS/JVM spec prevents the
5320 5330 // JVM from making those visible to Java code. As such, we must
5321 5331 // filter out spurious wakeups. We assume all ETIME returns are valid.
5322 5332 //
5323 5333 // TODO: properly differentiate simultaneous notify+interrupt.
5324 5334 // In that case, we should propagate the notify to another waiter.
5325 5335
5326 5336 while (_Event < 0) {
5327 5337 status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst);
5328 5338 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
5329 5339 pthread_cond_destroy (_cond);
5330 5340 pthread_cond_init (_cond, NULL) ;
5331 5341 }
5332 5342 assert_status(status == 0 || status == EINTR ||
5333 5343 status == ETIME || status == ETIMEDOUT,
5334 5344 status, "cond_timedwait");
5335 5345 if (!FilterSpuriousWakeups) break ; // previous semantics
5336 5346 if (status == ETIME || status == ETIMEDOUT) break ;
5337 5347 // We consume and ignore EINTR and spurious wakeups.
5338 5348 }
5339 5349 --_nParked ;
5340 5350 if (_Event >= 0) {
5341 5351 ret = OS_OK;
5342 5352 }
5343 5353 _Event = 0 ;
5344 5354 status = pthread_mutex_unlock(_mutex);
5345 5355 assert_status(status == 0, status, "mutex_unlock");
5346 5356 assert (_nParked == 0, "invariant") ;
5347 5357 // Paranoia to ensure our locked and lock-free paths interact
5348 5358 // correctly with each other.
5349 5359 OrderAccess::fence();
5350 5360 return ret;
5351 5361 }
5352 5362
5353 5363 void os::PlatformEvent::unpark() {
5354 5364 // Transitions for _Event:
5355 5365 // 0 :=> 1
5356 5366 // 1 :=> 1
5357 5367 // -1 :=> either 0 or 1; must signal target thread
5358 5368 // That is, we can safely transition _Event from -1 to either
5359 5369 // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
5360 5370 // unpark() calls.
5361 5371 // See also: "Semaphores in Plan 9" by Mullender & Cox
5362 5372 //
5363 5373 // Note: Forcing a transition from "-1" to "1" on an unpark() means
5364 5374 // that it will take two back-to-back park() calls for the owning
5365 5375 // thread to block. This has the benefit of forcing a spurious return
5366 5376 // from the first park() call after an unpark() call which will help
5367 5377 // shake out uses of park() and unpark() without condition variables.
5368 5378
5369 5379 if (Atomic::xchg(1, &_Event) >= 0) return;
5370 5380
5371 5381 // Wait for the thread associated with the event to vacate
5372 5382 int status = pthread_mutex_lock(_mutex);
5373 5383 assert_status(status == 0, status, "mutex_lock");
5374 5384 int AnyWaiters = _nParked;
5375 5385 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
5376 5386 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
5377 5387 AnyWaiters = 0;
5378 5388 pthread_cond_signal(_cond);
5379 5389 }
5380 5390 status = pthread_mutex_unlock(_mutex);
5381 5391 assert_status(status == 0, status, "mutex_unlock");
5382 5392 if (AnyWaiters != 0) {
5383 5393 status = pthread_cond_signal(_cond);
5384 5394 assert_status(status == 0, status, "cond_signal");
5385 5395 }
5386 5396
5387 5397 // Note that we signal() _after dropping the lock for "immortal" Events.
5388 5398 // This is safe and avoids a common class of futile wakeups. In rare
5389 5399 // circumstances this can cause a thread to return prematurely from
5390 5400 // cond_{timed}wait() but the spurious wakeup is benign and the victim will
5391 5401 // simply re-test the condition and re-park itself.
5392 5402 }
5393 5403
5394 5404
5395 5405 // JSR166
5396 5406 // -------------------------------------------------------
5397 5407
5398 5408 /*
5399 5409 * The solaris and linux implementations of park/unpark are fairly
5400 5410 * conservative for now, but can be improved. They currently use a
5401 5411 * mutex/condvar pair, plus a a count.
5402 5412 * Park decrements count if > 0, else does a condvar wait. Unpark
5403 5413 * sets count to 1 and signals condvar. Only one thread ever waits
5404 5414 * on the condvar. Contention seen when trying to park implies that someone
5405 5415 * is unparking you, so don't wait. And spurious returns are fine, so there
5406 5416 * is no need to track notifications.
5407 5417 */
5408 5418
5409 5419 #define MAX_SECS 100000000
5410 5420 /*
5411 5421 * This code is common to linux and solaris and will be moved to a
5412 5422 * common place in dolphin.
5413 5423 *
5414 5424 * The passed in time value is either a relative time in nanoseconds
5415 5425 * or an absolute time in milliseconds. Either way it has to be unpacked
5416 5426 * into suitable seconds and nanoseconds components and stored in the
5417 5427 * given timespec structure.
5418 5428 * Given time is a 64-bit value and the time_t used in the timespec is only
5419 5429 * a signed-32-bit value (except on 64-bit Linux) we have to watch for
5420 5430 * overflow if times way in the future are given. Further on Solaris versions
5421 5431 * prior to 10 there is a restriction (see cond_timedwait) that the specified
5422 5432 * number of seconds, in abstime, is less than current_time + 100,000,000.
5423 5433 * As it will be 28 years before "now + 100000000" will overflow we can
5424 5434 * ignore overflow and just impose a hard-limit on seconds using the value
5425 5435 * of "now + 100,000,000". This places a limit on the timeout of about 3.17
5426 5436 * years from "now".
5427 5437 */
5428 5438
5429 5439 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
5430 5440 assert (time > 0, "convertTime");
5431 5441
5432 5442 struct timeval now;
5433 5443 int status = gettimeofday(&now, NULL);
5434 5444 assert(status == 0, "gettimeofday");
5435 5445
5436 5446 time_t max_secs = now.tv_sec + MAX_SECS;
5437 5447
5438 5448 if (isAbsolute) {
5439 5449 jlong secs = time / 1000;
5440 5450 if (secs > max_secs) {
5441 5451 absTime->tv_sec = max_secs;
5442 5452 }
5443 5453 else {
5444 5454 absTime->tv_sec = secs;
5445 5455 }
5446 5456 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
5447 5457 }
5448 5458 else {
5449 5459 jlong secs = time / NANOSECS_PER_SEC;
5450 5460 if (secs >= MAX_SECS) {
5451 5461 absTime->tv_sec = max_secs;
5452 5462 absTime->tv_nsec = 0;
5453 5463 }
5454 5464 else {
5455 5465 absTime->tv_sec = now.tv_sec + secs;
5456 5466 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
5457 5467 if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5458 5468 absTime->tv_nsec -= NANOSECS_PER_SEC;
5459 5469 ++absTime->tv_sec; // note: this must be <= max_secs
5460 5470 }
5461 5471 }
5462 5472 }
5463 5473 assert(absTime->tv_sec >= 0, "tv_sec < 0");
5464 5474 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
5465 5475 assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
5466 5476 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
5467 5477 }
5468 5478
5469 5479 void Parker::park(bool isAbsolute, jlong time) {
5470 5480 // Ideally we'd do something useful while spinning, such
5471 5481 // as calling unpackTime().
5472 5482
5473 5483 // Optional fast-path check:
5474 5484 // Return immediately if a permit is available.
5475 5485 // We depend on Atomic::xchg() having full barrier semantics
5476 5486 // since we are doing a lock-free update to _counter.
5477 5487 if (Atomic::xchg(0, &_counter) > 0) return;
5478 5488
5479 5489 Thread* thread = Thread::current();
5480 5490 assert(thread->is_Java_thread(), "Must be JavaThread");
5481 5491 JavaThread *jt = (JavaThread *)thread;
5482 5492
5483 5493 // Optional optimization -- avoid state transitions if there's an interrupt pending.
5484 5494 // Check interrupt before trying to wait
5485 5495 if (Thread::is_interrupted(thread, false)) {
5486 5496 return;
5487 5497 }
5488 5498
5489 5499 // Next, demultiplex/decode time arguments
5490 5500 timespec absTime;
5491 5501 if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
5492 5502 return;
5493 5503 }
5494 5504 if (time > 0) {
5495 5505 unpackTime(&absTime, isAbsolute, time);
5496 5506 }
5497 5507
5498 5508
5499 5509 // Enter safepoint region
5500 5510 // Beware of deadlocks such as 6317397.
5501 5511 // The per-thread Parker:: mutex is a classic leaf-lock.
5502 5512 // In particular a thread must never block on the Threads_lock while
5503 5513 // holding the Parker:: mutex. If safepoints are pending both the
5504 5514 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
5505 5515 ThreadBlockInVM tbivm(jt);
5506 5516
5507 5517 // Don't wait if cannot get lock since interference arises from
5508 5518 // unblocking. Also. check interrupt before trying wait
5509 5519 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
5510 5520 return;
5511 5521 }
5512 5522
5513 5523 int status ;
5514 5524 if (_counter > 0) { // no wait needed
5515 5525 _counter = 0;
5516 5526 status = pthread_mutex_unlock(_mutex);
5517 5527 assert (status == 0, "invariant") ;
5518 5528 // Paranoia to ensure our locked and lock-free paths interact
5519 5529 // correctly with each other and Java-level accesses.
5520 5530 OrderAccess::fence();
5521 5531 return;
5522 5532 }
5523 5533
5524 5534 #ifdef ASSERT
5525 5535 // Don't catch signals while blocked; let the running threads have the signals.
5526 5536 // (This allows a debugger to break into the running thread.)
5527 5537 sigset_t oldsigs;
5528 5538 sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals();
5529 5539 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
5530 5540 #endif
5531 5541
5532 5542 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5533 5543 jt->set_suspend_equivalent();
5534 5544 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
5535 5545
5536 5546 if (time == 0) {
5537 5547 status = pthread_cond_wait (_cond, _mutex) ;
5538 5548 } else {
5539 5549 status = os::Linux::safe_cond_timedwait (_cond, _mutex, &absTime) ;
5540 5550 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
5541 5551 pthread_cond_destroy (_cond) ;
5542 5552 pthread_cond_init (_cond, NULL);
5543 5553 }
5544 5554 }
5545 5555 assert_status(status == 0 || status == EINTR ||
5546 5556 status == ETIME || status == ETIMEDOUT,
5547 5557 status, "cond_timedwait");
5548 5558
5549 5559 #ifdef ASSERT
5550 5560 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
5551 5561 #endif
5552 5562
5553 5563 _counter = 0 ;
5554 5564 status = pthread_mutex_unlock(_mutex) ;
5555 5565 assert_status(status == 0, status, "invariant") ;
5556 5566 // Paranoia to ensure our locked and lock-free paths interact
5557 5567 // correctly with each other and Java-level accesses.
5558 5568 OrderAccess::fence();
5559 5569
5560 5570 // If externally suspended while waiting, re-suspend
5561 5571 if (jt->handle_special_suspend_equivalent_condition()) {
5562 5572 jt->java_suspend_self();
5563 5573 }
5564 5574 }
5565 5575
5566 5576 void Parker::unpark() {
5567 5577 int s, status ;
5568 5578 status = pthread_mutex_lock(_mutex);
5569 5579 assert (status == 0, "invariant") ;
5570 5580 s = _counter;
5571 5581 _counter = 1;
5572 5582 if (s < 1) {
5573 5583 if (WorkAroundNPTLTimedWaitHang) {
5574 5584 status = pthread_cond_signal (_cond) ;
5575 5585 assert (status == 0, "invariant") ;
5576 5586 status = pthread_mutex_unlock(_mutex);
5577 5587 assert (status == 0, "invariant") ;
5578 5588 } else {
5579 5589 status = pthread_mutex_unlock(_mutex);
5580 5590 assert (status == 0, "invariant") ;
5581 5591 status = pthread_cond_signal (_cond) ;
5582 5592 assert (status == 0, "invariant") ;
5583 5593 }
5584 5594 } else {
5585 5595 pthread_mutex_unlock(_mutex);
5586 5596 assert (status == 0, "invariant") ;
5587 5597 }
5588 5598 }
5589 5599
5590 5600
5591 5601 extern char** environ;
5592 5602
5593 5603 #ifndef __NR_fork
5594 5604 #define __NR_fork IA32_ONLY(2) IA64_ONLY(not defined) AMD64_ONLY(57)
5595 5605 #endif
5596 5606
5597 5607 #ifndef __NR_execve
5598 5608 #define __NR_execve IA32_ONLY(11) IA64_ONLY(1033) AMD64_ONLY(59)
5599 5609 #endif
5600 5610
5601 5611 // Run the specified command in a separate process. Return its exit value,
5602 5612 // or -1 on failure (e.g. can't fork a new process).
5603 5613 // Unlike system(), this function can be called from signal handler. It
5604 5614 // doesn't block SIGINT et al.
5605 5615 int os::fork_and_exec(char* cmd) {
5606 5616 const char * argv[4] = {"sh", "-c", cmd, NULL};
5607 5617
5608 5618 // fork() in LinuxThreads/NPTL is not async-safe. It needs to run
5609 5619 // pthread_atfork handlers and reset pthread library. All we need is a
5610 5620 // separate process to execve. Make a direct syscall to fork process.
5611 5621 // On IA64 there's no fork syscall, we have to use fork() and hope for
5612 5622 // the best...
5613 5623 pid_t pid = NOT_IA64(syscall(__NR_fork);)
5614 5624 IA64_ONLY(fork();)
5615 5625
5616 5626 if (pid < 0) {
5617 5627 // fork failed
5618 5628 return -1;
5619 5629
5620 5630 } else if (pid == 0) {
5621 5631 // child process
5622 5632
5623 5633 // execve() in LinuxThreads will call pthread_kill_other_threads_np()
5624 5634 // first to kill every thread on the thread list. Because this list is
5625 5635 // not reset by fork() (see notes above), execve() will instead kill
5626 5636 // every thread in the parent process. We know this is the only thread
5627 5637 // in the new process, so make a system call directly.
5628 5638 // IA64 should use normal execve() from glibc to match the glibc fork()
5629 5639 // above.
5630 5640 NOT_IA64(syscall(__NR_execve, "/bin/sh", argv, environ);)
5631 5641 IA64_ONLY(execve("/bin/sh", (char* const*)argv, environ);)
5632 5642
5633 5643 // execve failed
5634 5644 _exit(-1);
5635 5645
5636 5646 } else {
5637 5647 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5638 5648 // care about the actual exit code, for now.
5639 5649
5640 5650 int status;
5641 5651
5642 5652 // Wait for the child process to exit. This returns immediately if
5643 5653 // the child has already exited. */
5644 5654 while (waitpid(pid, &status, 0) < 0) {
5645 5655 switch (errno) {
5646 5656 case ECHILD: return 0;
5647 5657 case EINTR: break;
5648 5658 default: return -1;
5649 5659 }
5650 5660 }
5651 5661
5652 5662 if (WIFEXITED(status)) {
5653 5663 // The child exited normally; get its exit code.
5654 5664 return WEXITSTATUS(status);
5655 5665 } else if (WIFSIGNALED(status)) {
5656 5666 // The child exited because of a signal
5657 5667 // The best value to return is 0x80 + signal number,
5658 5668 // because that is what all Unix shells do, and because
5659 5669 // it allows callers to distinguish between process exit and
5660 5670 // process death by signal.
5661 5671 return 0x80 + WTERMSIG(status);
5662 5672 } else {
5663 5673 // Unknown exit code; pass it through
5664 5674 return status;
5665 5675 }
5666 5676 }
5667 5677 }
5668 5678
5669 5679 // is_headless_jre()
5670 5680 //
5671 5681 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
5672 5682 // in order to report if we are running in a headless jre
5673 5683 //
5674 5684 // Since JDK8 xawt/libmawt.so was moved into the same directory
5675 5685 // as libawt.so, and renamed libawt_xawt.so
5676 5686 //
5677 5687 bool os::is_headless_jre() {
5678 5688 struct stat statbuf;
5679 5689 char buf[MAXPATHLEN];
5680 5690 char libmawtpath[MAXPATHLEN];
5681 5691 const char *xawtstr = "/xawt/libmawt.so";
5682 5692 const char *new_xawtstr = "/libawt_xawt.so";
5683 5693 char *p;
5684 5694
5685 5695 // Get path to libjvm.so
5686 5696 os::jvm_path(buf, sizeof(buf));
5687 5697
5688 5698 // Get rid of libjvm.so
5689 5699 p = strrchr(buf, '/');
5690 5700 if (p == NULL) return false;
5691 5701 else *p = '\0';
5692 5702
5693 5703 // Get rid of client or server
5694 5704 p = strrchr(buf, '/');
5695 5705 if (p == NULL) return false;
5696 5706 else *p = '\0';
5697 5707
5698 5708 // check xawt/libmawt.so
5699 5709 strcpy(libmawtpath, buf);
5700 5710 strcat(libmawtpath, xawtstr);
5701 5711 if (::stat(libmawtpath, &statbuf) == 0) return false;
5702 5712
5703 5713 // check libawt_xawt.so
5704 5714 strcpy(libmawtpath, buf);
5705 5715 strcat(libmawtpath, new_xawtstr);
5706 5716 if (::stat(libmawtpath, &statbuf) == 0) return false;
5707 5717
5708 5718 return true;
5709 5719 }
5710 5720
5711 5721 // Get the default path to the core file
5712 5722 // Returns the length of the string
5713 5723 int os::get_core_path(char* buffer, size_t bufferSize) {
5714 5724 const char* p = get_current_directory(buffer, bufferSize);
5715 5725
5716 5726 if (p == NULL) {
5717 5727 assert(p != NULL, "failed to get current directory");
5718 5728 return 0;
5719 5729 }
5720 5730
5721 5731 return strlen(buffer);
5722 5732 }
5723 5733
5724 5734 #ifdef JAVASE_EMBEDDED
5725 5735 //
5726 5736 // A thread to watch the '/dev/mem_notify' device, which will tell us when the OS is running low on memory.
5727 5737 //
5728 5738 MemNotifyThread* MemNotifyThread::_memnotify_thread = NULL;
5729 5739
5730 5740 // ctor
5731 5741 //
5732 5742 MemNotifyThread::MemNotifyThread(int fd): Thread() {
5733 5743 assert(memnotify_thread() == NULL, "we can only allocate one MemNotifyThread");
5734 5744 _fd = fd;
5735 5745
5736 5746 if (os::create_thread(this, os::os_thread)) {
5737 5747 _memnotify_thread = this;
5738 5748 os::set_priority(this, NearMaxPriority);
5739 5749 os::start_thread(this);
5740 5750 }
5741 5751 }
5742 5752
5743 5753 // Where all the work gets done
5744 5754 //
5745 5755 void MemNotifyThread::run() {
5746 5756 assert(this == memnotify_thread(), "expected the singleton MemNotifyThread");
5747 5757
5748 5758 // Set up the select arguments
5749 5759 fd_set rfds;
5750 5760 if (_fd != -1) {
5751 5761 FD_ZERO(&rfds);
5752 5762 FD_SET(_fd, &rfds);
5753 5763 }
5754 5764
5755 5765 // Now wait for the mem_notify device to wake up
5756 5766 while (1) {
5757 5767 // Wait for the mem_notify device to signal us..
5758 5768 int rc = select(_fd+1, _fd != -1 ? &rfds : NULL, NULL, NULL, NULL);
5759 5769 if (rc == -1) {
5760 5770 perror("select!\n");
5761 5771 break;
5762 5772 } else if (rc) {
5763 5773 //ssize_t free_before = os::available_memory();
5764 5774 //tty->print ("Notified: Free: %dK \n",os::available_memory()/1024);
5765 5775
5766 5776 // The kernel is telling us there is not much memory left...
5767 5777 // try to do something about that
5768 5778
5769 5779 // If we are not already in a GC, try one.
5770 5780 if (!Universe::heap()->is_gc_active()) {
5771 5781 Universe::heap()->collect(GCCause::_allocation_failure);
5772 5782
5773 5783 //ssize_t free_after = os::available_memory();
5774 5784 //tty->print ("Post-Notify: Free: %dK\n",free_after/1024);
5775 5785 //tty->print ("GC freed: %dK\n", (free_after - free_before)/1024);
5776 5786 }
5777 5787 // We might want to do something like the following if we find the GC's are not helping...
5778 5788 // Universe::heap()->size_policy()->set_gc_time_limit_exceeded(true);
5779 5789 }
5780 5790 }
5781 5791 }
5782 5792
5783 5793 //
5784 5794 // See if the /dev/mem_notify device exists, and if so, start a thread to monitor it.
5785 5795 //
5786 5796 void MemNotifyThread::start() {
5787 5797 int fd;
5788 5798 fd = open ("/dev/mem_notify", O_RDONLY, 0);
5789 5799 if (fd < 0) {
5790 5800 return;
5791 5801 }
5792 5802
5793 5803 if (memnotify_thread() == NULL) {
5794 5804 new MemNotifyThread(fd);
5795 5805 }
5796 5806 }
5797 5807
5798 5808 #endif // JAVASE_EMBEDDED
↓ open down ↓ |
1346 lines elided |
↑ open up ↑ |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX