changeset 11989:dd344d3c057b

Merge
author mockner
date Tue, 13 Sep 2016 18:19:05 +0200
parents 6c2a44eb27ac cd2c49a02a4c
children 0d0aa1b2d676 8e57662104a1
files src/share/vm/gc/g1/g1Predictions.cpp src/share/vm/gc/shared/memset_with_concurrent_readers.cpp test/runtime/RedefineTests/RedefineCount.java
diffstat 149 files changed, 3222 insertions(+), 1432 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Tue Sep 13 11:04:29 2016 -0400
+++ b/.hgtags	Tue Sep 13 18:19:05 2016 +0200
@@ -536,3 +536,5 @@
 943bf73b49c33c2d7cbd796f6a4ae3c7a00ae932 jdk-9+131
 713951c08aa26813375175c2ab6cc99ff2a56903 jdk-9+132
 a25e0fb6033245ab075136e744d362ce765464cd jdk-9+133
+b8b694c6b4d2ab0939aed7adaf0eec1ac321a085 jdk-9+134
+3b1c4562953db47e36b237a500f368d5c9746d47 jdk-9+135
--- a/src/cpu/sparc/vm/globals_sparc.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/cpu/sparc/vm/globals_sparc.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -57,10 +57,12 @@
 
 #ifdef _LP64
 // Stack slots are 2X larger in LP64 than in the 32 bit VM.
+define_pd_global(intx, CompilerThreadStackSize, 1024);
 define_pd_global(intx, ThreadStackSize,       1024);
 define_pd_global(intx, VMThreadStackSize,     1024);
 #define DEFAULT_STACK_SHADOW_PAGES (20 DEBUG_ONLY(+2))
 #else
+define_pd_global(intx, CompilerThreadStackSize, 512);
 define_pd_global(intx, ThreadStackSize,       512);
 define_pd_global(intx, VMThreadStackSize,     512);
 #define DEFAULT_STACK_SHADOW_PAGES (6 DEBUG_ONLY(+2))
--- a/src/cpu/sparc/vm/sparc.ad	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/cpu/sparc/vm/sparc.ad	Tue Sep 13 18:19:05 2016 +0200
@@ -2921,6 +2921,26 @@
     __ cmp( Rold, O7 );
   %}
 
+  // raw int cas without using tmp register for compareAndExchange
+  enc_class enc_casi_exch( iRegP mem, iRegL old, iRegL new) %{
+    Register Rmem = reg_to_register_object($mem$$reg);
+    Register Rold = reg_to_register_object($old$$reg);
+    Register Rnew = reg_to_register_object($new$$reg);
+
+    MacroAssembler _masm(&cbuf);
+    __ cas(Rmem, Rold, Rnew);
+  %}
+
+  // 64-bit cas without using tmp register for compareAndExchange
+  enc_class enc_casx_exch( iRegP mem, iRegL old, iRegL new) %{
+    Register Rmem = reg_to_register_object($mem$$reg);
+    Register Rold = reg_to_register_object($old$$reg);
+    Register Rnew = reg_to_register_object($new$$reg);
+
+    MacroAssembler _masm(&cbuf);
+    __ casx(Rmem, Rold, Rnew);
+  %}
+
   enc_class enc_lflags_ne_to_boolean( iRegI res ) %{
     Register Rres = reg_to_register_object($res$$reg);
 
@@ -7105,6 +7125,7 @@
 instruct compareAndSwapL_bool(iRegP mem_ptr, iRegL oldval, iRegL newval, iRegI res, o7RegI tmp1, flagsReg ccr ) %{
   predicate(VM_Version::supports_cx8());
   match(Set res (CompareAndSwapL mem_ptr (Binary oldval newval)));
+  match(Set res (WeakCompareAndSwapL mem_ptr (Binary oldval newval)));
   effect( USE mem_ptr, KILL ccr, KILL tmp1);
   format %{
             "MOV    $newval,O7\n\t"
@@ -7121,6 +7142,7 @@
 
 instruct compareAndSwapI_bool(iRegP mem_ptr, iRegI oldval, iRegI newval, iRegI res, o7RegI tmp1, flagsReg ccr ) %{
   match(Set res (CompareAndSwapI mem_ptr (Binary oldval newval)));
+  match(Set res (WeakCompareAndSwapI mem_ptr (Binary oldval newval)));
   effect( USE mem_ptr, KILL ccr, KILL tmp1);
   format %{
             "MOV    $newval,O7\n\t"
@@ -7139,6 +7161,7 @@
   predicate(VM_Version::supports_cx8());
 #endif
   match(Set res (CompareAndSwapP mem_ptr (Binary oldval newval)));
+  match(Set res (WeakCompareAndSwapP mem_ptr (Binary oldval newval)));
   effect( USE mem_ptr, KILL ccr, KILL tmp1);
   format %{
             "MOV    $newval,O7\n\t"
@@ -7159,6 +7182,7 @@
 
 instruct compareAndSwapN_bool(iRegP mem_ptr, iRegN oldval, iRegN newval, iRegI res, o7RegI tmp1, flagsReg ccr ) %{
   match(Set res (CompareAndSwapN mem_ptr (Binary oldval newval)));
+  match(Set res (WeakCompareAndSwapN mem_ptr (Binary oldval newval)));
   effect( USE mem_ptr, KILL ccr, KILL tmp1);
   format %{
             "MOV    $newval,O7\n\t"
@@ -7172,6 +7196,54 @@
   ins_pipe( long_memory_op );
 %}
 
+instruct compareAndExchangeI(iRegP mem_ptr, iRegI oldval, iRegI newval)
+%{
+  match(Set newval (CompareAndExchangeI mem_ptr (Binary oldval newval)));
+  effect( USE mem_ptr );
+
+  format %{
+            "CASA   [$mem_ptr],$oldval,$newval\t! If $oldval==[$mem_ptr] Then store $newval into [$mem_ptr] and set $newval=[$mem_ptr]\n\t"
+  %}
+  ins_encode( enc_casi_exch(mem_ptr, oldval, newval) );
+  ins_pipe( long_memory_op );
+%}
+
+instruct compareAndExchangeL(iRegP mem_ptr, iRegL oldval, iRegL newval)
+%{
+  match(Set newval (CompareAndExchangeL mem_ptr (Binary oldval newval)));
+  effect( USE mem_ptr );
+
+  format %{
+            "CASXA  [$mem_ptr],$oldval,$newval\t! If $oldval==[$mem_ptr] Then store $newval into [$mem_ptr] and set $newval=[$mem_ptr]\n\t"
+  %}
+  ins_encode( enc_casx_exch(mem_ptr, oldval, newval) );
+  ins_pipe( long_memory_op );
+%}
+
+instruct compareAndExchangeP(iRegP mem_ptr, iRegP oldval, iRegP newval)
+%{
+  match(Set newval (CompareAndExchangeP mem_ptr (Binary oldval newval)));
+  effect( USE mem_ptr );
+
+  format %{
+            "CASXA  [$mem_ptr],$oldval,$newval\t! If $oldval==[$mem_ptr] Then store $newval into [$mem_ptr] and set $newval=[$mem_ptr]\n\t"
+  %}
+  ins_encode( enc_casx_exch(mem_ptr, oldval, newval) );
+  ins_pipe( long_memory_op );
+%}
+
+instruct compareAndExchangeN(iRegP mem_ptr, iRegN oldval, iRegN newval)
+%{
+  match(Set newval (CompareAndExchangeN mem_ptr (Binary oldval newval)));
+  effect( USE mem_ptr );
+
+  format %{
+            "CASA   [$mem_ptr],$oldval,$newval\t! If $oldval==[$mem_ptr] Then store $newval into [$mem_ptr] and set $newval=[$mem_ptr]\n\t"
+  %}
+  ins_encode( enc_casi_exch(mem_ptr, oldval, newval) );
+  ins_pipe( long_memory_op );
+%}
+
 instruct xchgI( memory mem, iRegI newval) %{
   match(Set newval (GetAndSetI mem newval));
   format %{ "SWAP  [$mem],$newval" %}
--- a/src/cpu/x86/vm/globals_x86.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/cpu/x86/vm/globals_x86.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -65,10 +65,10 @@
 #ifdef AMD64
 // Very large C++ stack frames using solaris-amd64 optimized builds
 // due to lack of optimization caused by C++ compiler bugs
-#define DEFAULT_STACK_SHADOW_PAGES (NOT_WIN64(20) WIN64_ONLY(6) DEBUG_ONLY(+2))
+#define DEFAULT_STACK_SHADOW_PAGES (NOT_WIN64(20) WIN64_ONLY(7) DEBUG_ONLY(+2))
 // For those clients that do not use write socket, we allow
 // the min range value to be below that of the default
-#define MIN_STACK_SHADOW_PAGES (NOT_WIN64(10) WIN64_ONLY(6) DEBUG_ONLY(+2))
+#define MIN_STACK_SHADOW_PAGES (NOT_WIN64(10) WIN64_ONLY(7) DEBUG_ONLY(+2))
 #else
 #define DEFAULT_STACK_SHADOW_PAGES (4 DEBUG_ONLY(+5))
 #define MIN_STACK_SHADOW_PAGES DEFAULT_STACK_SHADOW_PAGES
--- a/src/cpu/x86/vm/macroAssembler_x86.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/cpu/x86/vm/macroAssembler_x86.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -8131,8 +8131,7 @@
     jmp(FALSE_LABEL);
 
     clear_vector_masking();   // closing of the stub context for programming mask registers
-  }
-  else {
+  } else {
     movl(result, len); // copy
 
     if (UseAVX == 2 && UseSSE >= 2) {
@@ -8169,8 +8168,7 @@
       bind(COMPARE_TAIL); // len is zero
       movl(len, result);
       // Fallthru to tail compare
-    }
-    else if (UseSSE42Intrinsics) {
+    } else if (UseSSE42Intrinsics) {
       // With SSE4.2, use double quad vector compare
       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
 
@@ -10748,7 +10746,10 @@
   // save length for return
   push(len);
 
+  // 8165287: EVEX version disabled for now, needs to be refactored as
+  // it is returning incorrect results.
   if ((UseAVX > 2) && // AVX512
+    0 &&
     VM_Version::supports_avx512vlbw() &&
     VM_Version::supports_bmi2()) {
 
@@ -11067,10 +11068,11 @@
 
       bind(below_threshold);
       bind(copy_new_tail);
-      if (UseAVX > 2) {
+      if ((UseAVX > 2) &&
+        VM_Version::supports_avx512vlbw() &&
+        VM_Version::supports_bmi2()) {
         movl(tmp2, len);
-      }
-      else {
+      } else {
         movl(len, tmp2);
       }
       andl(tmp2, 0x00000007);
--- a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/utilities/GrowableArray.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/utilities/GrowableArray.java	Tue Sep 13 18:19:05 2016 +0200
@@ -65,4 +65,7 @@
     super(addr);
     virtualConstructor = v;
   }
+  public Address getData() {
+    return dataField.getValue(getAddress());
+  }
 }
--- a/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/CompilerToVM.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/CompilerToVM.java	Tue Sep 13 18:19:05 2016 +0200
@@ -366,8 +366,8 @@
      * {@code exactReceiver}.
      *
      * @param caller the caller or context type used to perform access checks
-     * @return the link-time resolved method (might be abstract) or {@code 0} if it can not be
-     *         linked
+     * @return the link-time resolved method (might be abstract) or {@code null} if it is either a
+     *         signature polymorphic method or can not be linked.
      */
     native HotSpotResolvedJavaMethodImpl resolveMethod(HotSpotResolvedObjectTypeImpl exactReceiver, HotSpotResolvedJavaMethodImpl method, HotSpotResolvedObjectTypeImpl caller);
 
--- a/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotConstantPool.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotConstantPool.java	Tue Sep 13 18:19:05 2016 +0200
@@ -722,7 +722,7 @@
     /**
      * Determines if {@code type} contains signature polymorphic methods.
      */
-    private static boolean isSignaturePolymorphicHolder(final HotSpotResolvedObjectTypeImpl type) {
+    static boolean isSignaturePolymorphicHolder(final ResolvedJavaType type) {
         String name = type.getName();
         if (signaturePolymorphicHolders == null) {
             signaturePolymorphicHolders = compilerToVM().getSignaturePolymorphicHolders();
--- a/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl.java	Tue Sep 13 18:19:05 2016 +0200
@@ -24,6 +24,7 @@
 
 import static java.util.Objects.requireNonNull;
 import static jdk.vm.ci.hotspot.CompilerToVM.compilerToVM;
+import static jdk.vm.ci.hotspot.HotSpotConstantPool.isSignaturePolymorphicHolder;
 import static jdk.vm.ci.hotspot.HotSpotJVMCIRuntime.runtime;
 import static jdk.vm.ci.hotspot.HotSpotVMConfig.config;
 import static jdk.vm.ci.hotspot.UnsafeAccess.UNSAFE;
@@ -426,7 +427,7 @@
             // Methods can only be resolved against concrete types
             return null;
         }
-        if (method.isConcrete() && method.getDeclaringClass().equals(this) && method.isPublic()) {
+        if (method.isConcrete() && method.getDeclaringClass().equals(this) && method.isPublic() && !isSignaturePolymorphicHolder(method.getDeclaringClass())) {
             return method;
         }
         if (!method.getDeclaringClass().isAssignableFrom(this)) {
--- a/src/jdk.vm.ci/share/classes/jdk.vm.ci.meta/src/jdk/vm/ci/meta/ResolvedJavaType.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/jdk.vm.ci/share/classes/jdk.vm.ci.meta/src/jdk/vm/ci/meta/ResolvedJavaType.java	Tue Sep 13 18:19:05 2016 +0200
@@ -209,8 +209,8 @@
      *
      * @param method the method to select the implementation of
      * @param callerType the caller or context type used to perform access checks
-     * @return the method that would be selected at runtime (might be abstract) or {@code null} if
-     *         it can not be resolved
+     * @return the link-time resolved method (might be abstract) or {@code null} if it is either a
+     *         signature polymorphic method or can not be linked.
      */
     ResolvedJavaMethod resolveMethod(ResolvedJavaMethod method, ResolvedJavaType callerType);
 
--- a/src/os/aix/vm/os_aix.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/aix/vm/os_aix.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -847,7 +847,8 @@
   return 0;
 }
 
-bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
+bool os::create_thread(Thread* thread, ThreadType thr_type,
+                       size_t req_stack_size) {
 
   assert(thread->osthread() == NULL, "caller responsible");
 
@@ -880,37 +881,12 @@
   guarantee(pthread_attr_setsuspendstate_np(&attr, PTHREAD_CREATE_SUSPENDED_NP) == 0, "???");
 
   // calculate stack size if it's not specified by caller
-  if (stack_size == 0) {
-    stack_size = os::Aix::default_stack_size(thr_type);
-
-    switch (thr_type) {
-    case os::java_thread:
-      // Java threads use ThreadStackSize whose default value can be changed with the flag -Xss.
-      assert(JavaThread::stack_size_at_create() > 0, "this should be set");
-      stack_size = JavaThread::stack_size_at_create();
-      break;
-    case os::compiler_thread:
-      if (CompilerThreadStackSize > 0) {
-        stack_size = (size_t)(CompilerThreadStackSize * K);
-        break;
-      } // else fall through:
-        // use VMThreadStackSize if CompilerThreadStackSize is not defined
-    case os::vm_thread:
-    case os::pgc_thread:
-    case os::cgc_thread:
-    case os::watcher_thread:
-      if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
-      break;
-    }
-  }
-
-  stack_size = MAX2(stack_size, os::Aix::min_stack_allowed);
+  size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
   pthread_attr_setstacksize(&attr, stack_size);
 
   pthread_t tid;
   int ret = pthread_create(&tid, &attr, (void* (*)(void*)) thread_native_entry, thread);
 
-
   char buf[64];
   if (ret == 0) {
     log_info(os, thread)("Thread started (pthread id: " UINTX_FORMAT ", attributes: %s). ",
@@ -3593,32 +3569,11 @@
   Aix::signal_sets_init();
   Aix::install_signal_handlers();
 
-  // Check minimum allowable stack size for thread creation and to initialize
-  // the java system classes, including StackOverflowError - depends on page
-  // size. Add two 4K pages for compiler2 recursion in main thread.
-  // Add in 4*BytesPerWord 4K pages to account for VM stack during
-  // class initialization depending on 32 or 64 bit VM.
-  os::Aix::min_stack_allowed = MAX2(os::Aix::min_stack_allowed,
-                                    JavaThread::stack_guard_zone_size() +
-                                    JavaThread::stack_shadow_zone_size() +
-                                    (4*BytesPerWord COMPILER2_PRESENT(+2)) * 4 * K);
-
-  os::Aix::min_stack_allowed = align_size_up(os::Aix::min_stack_allowed, os::vm_page_size());
-
-  size_t threadStackSizeInBytes = ThreadStackSize * K;
-  if (threadStackSizeInBytes != 0 &&
-      threadStackSizeInBytes < os::Aix::min_stack_allowed) {
-    tty->print_cr("\nThe stack size specified is too small, "
-                  "Specify at least %dk",
-                  os::Aix::min_stack_allowed / K);
+  // Check and sets minimum stack sizes against command line options
+  if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
     return JNI_ERR;
   }
 
-  // Make the stack size a multiple of the page size so that
-  // the yellow/red zones can be guarded.
-  // Note that this can be 0, if no default stacksize was set.
-  JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, vm_page_size()));
-
   if (UseNUMA) {
     UseNUMA = false;
     warning("NUMA optimizations are not available on this OS.");
--- a/src/os/aix/vm/os_aix.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/aix/vm/os_aix.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2013, 2016 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -140,14 +140,6 @@
   // libpthread version string
   static void libpthread_init();
 
-  // Minimum stack size a thread can be created with (allowing
-  // the VM to completely create the thread and enter user code)
-  static size_t min_stack_allowed;
-
-  // Return default stack size or guard size for the specified thread type
-  static size_t default_stack_size(os::ThreadType thr_type);
-  static size_t default_guard_size(os::ThreadType thr_type);
-
   // Function returns true if we run on OS/400 (pase), false if we run
   // on AIX.
   static bool on_pase() {
--- a/src/os/bsd/vm/os_bsd.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/bsd/vm/os_bsd.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -734,7 +734,8 @@
   return 0;
 }
 
-bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
+bool os::create_thread(Thread* thread, ThreadType thr_type,
+                       size_t req_stack_size) {
   assert(thread->osthread() == NULL, "caller responsible");
 
   // Allocate the OSThread object
@@ -757,32 +758,7 @@
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 
   // calculate stack size if it's not specified by caller
-  if (stack_size == 0) {
-    stack_size = os::Bsd::default_stack_size(thr_type);
-
-    switch (thr_type) {
-    case os::java_thread:
-      // Java threads use ThreadStackSize which default value can be
-      // changed with the flag -Xss
-      assert(JavaThread::stack_size_at_create() > 0, "this should be set");
-      stack_size = JavaThread::stack_size_at_create();
-      break;
-    case os::compiler_thread:
-      if (CompilerThreadStackSize > 0) {
-        stack_size = (size_t)(CompilerThreadStackSize * K);
-        break;
-      } // else fall through:
-        // use VMThreadStackSize if CompilerThreadStackSize is not defined
-    case os::vm_thread:
-    case os::pgc_thread:
-    case os::cgc_thread:
-    case os::watcher_thread:
-      if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
-      break;
-    }
-  }
-
-  stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
+  size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
   pthread_attr_setstacksize(&attr, stack_size);
 
   ThreadState state;
@@ -3502,32 +3478,11 @@
   Bsd::signal_sets_init();
   Bsd::install_signal_handlers();
 
-  // Check minimum allowable stack size for thread creation and to initialize
-  // the java system classes, including StackOverflowError - depends on page
-  // size.  Add two 4K pages for compiler2 recursion in main thread.
-  // Add in 4*BytesPerWord 4K pages to account for VM stack during
-  // class initialization depending on 32 or 64 bit VM.
-  os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
-                                    JavaThread::stack_guard_zone_size() +
-                                    JavaThread::stack_shadow_zone_size() +
-                                    (4*BytesPerWord COMPILER2_PRESENT(+2)) * 4 * K);
-
-  os::Bsd::min_stack_allowed = align_size_up(os::Bsd::min_stack_allowed, os::vm_page_size());
-
-  size_t threadStackSizeInBytes = ThreadStackSize * K;
-  if (threadStackSizeInBytes != 0 &&
-      threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
-    tty->print_cr("\nThe stack size specified is too small, "
-                  "Specify at least %dk",
-                  os::Bsd::min_stack_allowed/ K);
+  // Check and sets minimum stack sizes against command line options
+  if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
     return JNI_ERR;
   }
 
-  // Make the stack size a multiple of the page size so that
-  // the yellow/red zones can be guarded.
-  JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
-                                                vm_page_size()));
-
   if (MaxFDLimit) {
     // set the number of file descriptors to max. print out error
     // if getrlimit/setrlimit fails but continue regardless.
--- a/src/os/bsd/vm/os_bsd.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/bsd/vm/os_bsd.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -120,14 +120,6 @@
   static struct sigaction *get_chained_signal_action(int sig);
   static bool chained_handler(int sig, siginfo_t* siginfo, void* context);
 
-  // Minimum stack size a thread can be created with (allowing
-  // the VM to completely create the thread and enter user code)
-  static size_t min_stack_allowed;
-
-  // Return default stack size or guard size for the specified thread type
-  static size_t default_stack_size(os::ThreadType thr_type);
-  static size_t default_guard_size(os::ThreadType thr_type);
-
   // Real-time clock functions
   static void clock_init(void);
 
--- a/src/os/linux/vm/os_linux.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/linux/vm/os_linux.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -701,7 +701,7 @@
 }
 
 bool os::create_thread(Thread* thread, ThreadType thr_type,
-                       size_t stack_size) {
+                       size_t req_stack_size) {
   assert(thread->osthread() == NULL, "caller responsible");
 
   // Allocate the OSThread object
@@ -723,34 +723,8 @@
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 
-  // stack size
   // calculate stack size if it's not specified by caller
-  if (stack_size == 0) {
-    stack_size = os::Linux::default_stack_size(thr_type);
-
-    switch (thr_type) {
-    case os::java_thread:
-      // Java threads use ThreadStackSize which default value can be
-      // changed with the flag -Xss
-      assert(JavaThread::stack_size_at_create() > 0, "this should be set");
-      stack_size = JavaThread::stack_size_at_create();
-      break;
-    case os::compiler_thread:
-      if (CompilerThreadStackSize > 0) {
-        stack_size = (size_t)(CompilerThreadStackSize * K);
-        break;
-      } // else fall through:
-        // use VMThreadStackSize if CompilerThreadStackSize is not defined
-    case os::vm_thread:
-    case os::pgc_thread:
-    case os::cgc_thread:
-    case os::watcher_thread:
-      if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
-      break;
-    }
-  }
-
-  stack_size = MAX2(stack_size, os::Linux::min_stack_allowed);
+  size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
   pthread_attr_setstacksize(&attr, stack_size);
 
   // glibc guard page
@@ -956,10 +930,9 @@
 // bogus value for initial thread.
 void os::Linux::capture_initial_stack(size_t max_size) {
   // stack size is the easy part, get it from RLIMIT_STACK
-  size_t stack_size;
   struct rlimit rlim;
   getrlimit(RLIMIT_STACK, &rlim);
-  stack_size = rlim.rlim_cur;
+  size_t stack_size = rlim.rlim_cur;
 
   // 6308388: a bug in ld.so will relocate its own .data section to the
   //   lower end of primordial stack; reduce ulimit -s value a little bit
@@ -2875,7 +2848,7 @@
                               // in the library.
   const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
 
-  size_t cpu_num = os::active_processor_count();
+  size_t cpu_num = processor_count();
   size_t cpu_map_size = NCPUS / BitsPerCLong;
   size_t cpu_map_valid_size =
     MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
@@ -4793,32 +4766,10 @@
   Linux::signal_sets_init();
   Linux::install_signal_handlers();
 
-  // Check minimum allowable stack size for thread creation and to initialize
-  // the java system classes, including StackOverflowError - depends on page
-  // size.  Add two 4K pages for compiler2 recursion in main thread.
-  // Add in 4*BytesPerWord 4K pages to account for VM stack during
-  // class initialization depending on 32 or 64 bit VM.
-  os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed,
-                                      JavaThread::stack_guard_zone_size() +
-                                      JavaThread::stack_shadow_zone_size() +
-                                      (4*BytesPerWord COMPILER2_PRESENT(+2)) * 4 * K);
-
-  os::Linux::min_stack_allowed = align_size_up(os::Linux::min_stack_allowed, os::vm_page_size());
-
-  size_t threadStackSizeInBytes = ThreadStackSize * K;
-  if (threadStackSizeInBytes != 0 &&
-      threadStackSizeInBytes < os::Linux::min_stack_allowed) {
-    tty->print_cr("\nThe stack size specified is too small, "
-                  "Specify at least " SIZE_FORMAT "k",
-                  os::Linux::min_stack_allowed/ K);
+  // Check and sets minimum stack sizes against command line options
+  if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
     return JNI_ERR;
   }
-
-  // Make the stack size a multiple of the page size so that
-  // the yellow/red zones can be guarded.
-  JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
-                                                vm_page_size()));
-
   Linux::capture_initial_stack(JavaThread::stack_size_at_create());
 
 #if defined(IA32)
--- a/src/os/linux/vm/os_linux.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/linux/vm/os_linux.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -170,12 +170,8 @@
   static void libpthread_init();
   static bool libnuma_init();
   static void* libnuma_dlsym(void* handle, const char* name);
-  // Minimum stack size a thread can be created with (allowing
-  // the VM to completely create the thread and enter user code)
-  static size_t min_stack_allowed;
 
-  // Return default stack size or guard size for the specified thread type
-  static size_t default_stack_size(os::ThreadType thr_type);
+  // Return default guard size for the specified thread type
   static size_t default_guard_size(os::ThreadType thr_type);
 
   static void capture_initial_stack(size_t max_size);
--- a/src/os/posix/vm/os_posix.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/posix/vm/os_posix.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1099,6 +1099,123 @@
   return buf;
 }
 
+// Check minimum allowable stack sizes for thread creation and to initialize
+// the java system classes, including StackOverflowError - depends on page
+// size.  Add two 4K pages for compiler2 recursion in main thread.
+// Add in 4*BytesPerWord 4K pages to account for VM stack during
+// class initialization depending on 32 or 64 bit VM.
+jint os::Posix::set_minimum_stack_sizes() {
+  _java_thread_min_stack_allowed = MAX2(_java_thread_min_stack_allowed,
+                                        JavaThread::stack_guard_zone_size() +
+                                        JavaThread::stack_shadow_zone_size() +
+                                        (4 * BytesPerWord COMPILER2_PRESENT(+ 2)) * 4 * K);
+
+  _java_thread_min_stack_allowed = align_size_up(_java_thread_min_stack_allowed, vm_page_size());
+
+  size_t stack_size_in_bytes = ThreadStackSize * K;
+  if (stack_size_in_bytes != 0 &&
+      stack_size_in_bytes < _java_thread_min_stack_allowed) {
+    // The '-Xss' and '-XX:ThreadStackSize=N' options both set
+    // ThreadStackSize so we go with "Java thread stack size" instead
+    // of "ThreadStackSize" to be more friendly.
+    tty->print_cr("\nThe Java thread stack size specified is too small. "
+                  "Specify at least " SIZE_FORMAT "k",
+                  _java_thread_min_stack_allowed / K);
+    return JNI_ERR;
+  }
+
+#ifdef SOLARIS
+  // For 64kbps there will be a 64kb page size, which makes
+  // the usable default stack size quite a bit less.  Increase the
+  // stack for 64kb (or any > than 8kb) pages, this increases
+  // virtual memory fragmentation (since we're not creating the
+  // stack on a power of 2 boundary.  The real fix for this
+  // should be to fix the guard page mechanism.
+
+  if (vm_page_size() > 8*K) {
+    stack_size_in_bytes = (stack_size_in_bytes != 0)
+       ? stack_size_in_bytes +
+         JavaThread::stack_red_zone_size() +
+         JavaThread::stack_yellow_zone_size()
+       : 0;
+    ThreadStackSize = stack_size_in_bytes/K;
+  }
+#endif // SOLARIS
+
+  // Make the stack size a multiple of the page size so that
+  // the yellow/red zones can be guarded.
+  JavaThread::set_stack_size_at_create(round_to(stack_size_in_bytes,
+                                                vm_page_size()));
+
+  _compiler_thread_min_stack_allowed = align_size_up(_compiler_thread_min_stack_allowed, vm_page_size());
+
+  stack_size_in_bytes = CompilerThreadStackSize * K;
+  if (stack_size_in_bytes != 0 &&
+      stack_size_in_bytes < _compiler_thread_min_stack_allowed) {
+    tty->print_cr("\nThe CompilerThreadStackSize specified is too small. "
+                  "Specify at least " SIZE_FORMAT "k",
+                  _compiler_thread_min_stack_allowed / K);
+    return JNI_ERR;
+  }
+
+  _vm_internal_thread_min_stack_allowed = align_size_up(_vm_internal_thread_min_stack_allowed, vm_page_size());
+
+  stack_size_in_bytes = VMThreadStackSize * K;
+  if (stack_size_in_bytes != 0 &&
+      stack_size_in_bytes < _vm_internal_thread_min_stack_allowed) {
+    tty->print_cr("\nThe VMThreadStackSize specified is too small. "
+                  "Specify at least " SIZE_FORMAT "k",
+                  _vm_internal_thread_min_stack_allowed / K);
+    return JNI_ERR;
+  }
+  return JNI_OK;
+}
+
+// Called when creating the thread.  The minimum stack sizes have already been calculated
+size_t os::Posix::get_initial_stack_size(ThreadType thr_type, size_t req_stack_size) {
+  size_t stack_size;
+  if (req_stack_size == 0) {
+    stack_size = default_stack_size(thr_type);
+  } else {
+    stack_size = req_stack_size;
+  }
+
+  switch (thr_type) {
+  case os::java_thread:
+    // Java threads use ThreadStackSize which default value can be
+    // changed with the flag -Xss
+    if (req_stack_size == 0 && JavaThread::stack_size_at_create() > 0) {
+      // no requested size and we have a more specific default value
+      stack_size = JavaThread::stack_size_at_create();
+    }
+    stack_size = MAX2(stack_size,
+                      _java_thread_min_stack_allowed);
+    break;
+  case os::compiler_thread:
+    if (req_stack_size == 0 && CompilerThreadStackSize > 0) {
+      // no requested size and we have a more specific default value
+      stack_size = (size_t)(CompilerThreadStackSize * K);
+    }
+    stack_size = MAX2(stack_size,
+                      _compiler_thread_min_stack_allowed);
+    break;
+  case os::vm_thread:
+  case os::pgc_thread:
+  case os::cgc_thread:
+  case os::watcher_thread:
+  default:  // presume the unknown thr_type is a VM internal
+    if (req_stack_size == 0 && VMThreadStackSize > 0) {
+      // no requested size and we have a more specific default value
+      stack_size = (size_t)(VMThreadStackSize * K);
+    }
+
+    stack_size = MAX2(stack_size,
+                      _vm_internal_thread_min_stack_allowed);
+    break;
+  }
+
+  return stack_size;
+}
 
 os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
   assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
--- a/src/os/posix/vm/os_posix.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/posix/vm/os_posix.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,18 @@
   static void print_libversion_info(outputStream* st);
   static void print_load_average(outputStream* st);
 
+  // Minimum stack size a thread can be created with (allowing
+  // the VM to completely create the thread and enter user code)
+  static size_t _compiler_thread_min_stack_allowed;
+  static size_t _java_thread_min_stack_allowed;
+  static size_t _vm_internal_thread_min_stack_allowed;
+
 public:
+  // Return default stack size for the specified thread type
+  static size_t default_stack_size(os::ThreadType thr_type);
+  // Check and sets minimum stack sizes
+  static jint set_minimum_stack_sizes();
+  static size_t get_initial_stack_size(ThreadType thr_type, size_t req_stack_size);
 
   // Returns true if signal is valid.
   static bool is_valid_signal(int sig);
--- a/src/os/solaris/vm/os_solaris.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/solaris/vm/os_solaris.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -917,8 +917,15 @@
   return buf;
 }
 
+// return default stack size for thr_type
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
+  // default stack size when not specified by caller is 1M (2M for LP64)
+  size_t s = (BytesPerWord >> 2) * K * K;
+  return s;
+}
+
 bool os::create_thread(Thread* thread, ThreadType thr_type,
-                       size_t stack_size) {
+                       size_t req_stack_size) {
   // Allocate the OSThread object
   OSThread* osthread = new OSThread(NULL, NULL);
   if (osthread == NULL) {
@@ -953,31 +960,8 @@
     tty->print_cr("In create_thread, creating a %s thread\n", thrtyp);
   }
 
-  // Calculate stack size if it's not specified by caller.
-  if (stack_size == 0) {
-    // The default stack size 1M (2M for LP64).
-    stack_size = (BytesPerWord >> 2) * K * K;
-
-    switch (thr_type) {
-    case os::java_thread:
-      // Java threads use ThreadStackSize which default value can be changed with the flag -Xss
-      if (JavaThread::stack_size_at_create() > 0) stack_size = JavaThread::stack_size_at_create();
-      break;
-    case os::compiler_thread:
-      if (CompilerThreadStackSize > 0) {
-        stack_size = (size_t)(CompilerThreadStackSize * K);
-        break;
-      } // else fall through:
-        // use VMThreadStackSize if CompilerThreadStackSize is not defined
-    case os::vm_thread:
-    case os::pgc_thread:
-    case os::cgc_thread:
-    case os::watcher_thread:
-      if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
-      break;
-    }
-  }
-  stack_size = MAX2(stack_size, os::Solaris::min_stack_allowed);
+  // calculate stack size if it's not specified by caller
+  size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
 
   // Initial state is ALLOCATED but not INITIALIZED
   osthread->set_state(ALLOCATED);
@@ -4400,7 +4384,12 @@
   // Constant minimum stack size allowed. It must be at least
   // the minimum of what the OS supports (thr_min_stack()), and
   // enough to allow the thread to get to user bytecode execution.
-  Solaris::min_stack_allowed = MAX2(thr_min_stack(), Solaris::min_stack_allowed);
+  Posix::_compiler_thread_min_stack_allowed = MAX2(thr_min_stack(),
+                                                   Posix::_compiler_thread_min_stack_allowed);
+  Posix::_java_thread_min_stack_allowed = MAX2(thr_min_stack(),
+                                               Posix::_java_thread_min_stack_allowed);
+  Posix::_vm_internal_thread_min_stack_allowed = MAX2(thr_min_stack(),
+                                                      Posix::_vm_internal_thread_min_stack_allowed);
 
   // dynamic lookup of functions that may not be available in our lowest
   // supported Solaris release
@@ -4445,47 +4434,11 @@
     log_info(os)("Memory Serialize Page address: " INTPTR_FORMAT, p2i(mem_serialize_page));
   }
 
-  // Check minimum allowable stack size for thread creation and to initialize
-  // the java system classes, including StackOverflowError - depends on page
-  // size.  Add two 4K pages for compiler2 recursion in main thread.
-  // Add in 4*BytesPerWord 4K pages to account for VM stack during
-  // class initialization depending on 32 or 64 bit VM.
-  os::Solaris::min_stack_allowed = MAX2(os::Solaris::min_stack_allowed,
-                                        JavaThread::stack_guard_zone_size() +
-                                        JavaThread::stack_shadow_zone_size() +
-                                        (4*BytesPerWord COMPILER2_PRESENT(+2)) * 4 * K);
-
-  os::Solaris::min_stack_allowed = align_size_up(os::Solaris::min_stack_allowed, os::vm_page_size());
-
-  size_t threadStackSizeInBytes = ThreadStackSize * K;
-  if (threadStackSizeInBytes != 0 &&
-      threadStackSizeInBytes < os::Solaris::min_stack_allowed) {
-    tty->print_cr("\nThe stack size specified is too small, Specify at least %dk",
-                  os::Solaris::min_stack_allowed/K);
+  // Check and sets minimum stack sizes against command line options
+  if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
     return JNI_ERR;
   }
 
-  // For 64kbps there will be a 64kb page size, which makes
-  // the usable default stack size quite a bit less.  Increase the
-  // stack for 64kb (or any > than 8kb) pages, this increases
-  // virtual memory fragmentation (since we're not creating the
-  // stack on a power of 2 boundary.  The real fix for this
-  // should be to fix the guard page mechanism.
-
-  if (vm_page_size() > 8*K) {
-    threadStackSizeInBytes = (threadStackSizeInBytes != 0)
-       ? threadStackSizeInBytes +
-         JavaThread::stack_red_zone_size() +
-         JavaThread::stack_yellow_zone_size()
-       : 0;
-    ThreadStackSize = threadStackSizeInBytes/K;
-  }
-
-  // Make the stack size a multiple of the page size so that
-  // the yellow/red zones can be guarded.
-  JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
-                                                vm_page_size()));
-
   Solaris::libthread_init();
 
   if (UseNUMA) {
--- a/src/os/solaris/vm/os_solaris.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/solaris/vm/os_solaris.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -292,10 +292,6 @@
   static          jint  _os_thread_limit;
   static volatile jint  _os_thread_count;
 
-  // Minimum stack size a thread can be created with (allowing
-  // the VM to completely create the thread and enter user code)
-
-  static size_t min_stack_allowed;
 
   // Stack overflow handling
 
--- a/src/os/windows/vm/os_windows.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os/windows/vm/os_windows.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -2504,13 +2504,15 @@
   // It write enables the page immediately after protecting it
   // so just return.
   if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
-    JavaThread* thread = (JavaThread*) t;
-    PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
-    address addr = (address) exceptionRecord->ExceptionInformation[1];
-    if (os::is_memory_serialize_page(thread, addr)) {
-      // Block current thread until the memory serialize page permission restored.
-      os::block_on_serialize_page_trap();
-      return EXCEPTION_CONTINUE_EXECUTION;
+    if (t != NULL && t->is_Java_thread()) {
+      JavaThread* thread = (JavaThread*) t;
+      PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
+      address addr = (address) exceptionRecord->ExceptionInformation[1];
+      if (os::is_memory_serialize_page(thread, addr)) {
+        // Block current thread until the memory serialize page permission restored.
+        os::block_on_serialize_page_trap();
+        return EXCEPTION_CONTINUE_EXECUTION;
+      }
     }
   }
 
@@ -2564,7 +2566,7 @@
       }
 #endif
       if (thread->stack_guards_enabled()) {
-        if (_thread_in_Java) {
+        if (in_java) {
           frame fr;
           PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
           address addr = (address) exceptionRecord->ExceptionInformation[1];
@@ -2576,6 +2578,7 @@
         // Yellow zone violation.  The o/s has unprotected the first yellow
         // zone page for us.  Note:  must call disable_stack_yellow_zone to
         // update the enabled status, even if the zone contains only one page.
+        assert(thread->thread_state() != _thread_in_vm, "Undersized StackShadowPages");
         thread->disable_stack_yellow_reserved_zone();
         // If not in java code, return and hope for the best.
         return in_java
@@ -3793,6 +3796,11 @@
   GlobalMemoryStatusEx(&ms);
   _physical_memory = ms.ullTotalPhys;
 
+  if (FLAG_IS_DEFAULT(MaxRAM)) {
+    // Adjust MaxRAM according to the maximum virtual address space available.
+    FLAG_SET_DEFAULT(MaxRAM, MIN2(MaxRAM, (uint64_t) ms.ullTotalVirtual));
+  }
+
   OSVERSIONINFOEX oi;
   oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
   GetVersionEx((OSVERSIONINFO*)&oi);
@@ -4207,7 +4215,7 @@
   min_stack_allowed = align_size_up(min_stack_allowed, os::vm_page_size());
 
   if (actual_reserve_size < min_stack_allowed) {
-    tty->print_cr("\nThe stack size specified is too small, "
+    tty->print_cr("\nThe Java thread stack size specified is too small. "
                   "Specify at least %dk",
                   min_stack_allowed / K);
     return JNI_ERR;
--- a/src/os_cpu/aix_ppc/vm/globals_aix_ppc.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/aix_ppc/vm/globals_aix_ppc.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -33,10 +33,6 @@
 define_pd_global(intx, ThreadStackSize,          2048); // 0 => use system default
 define_pd_global(intx, VMThreadStackSize,        2048);
 
-// if we set CompilerThreadStackSize to a value different than 0, it will
-// be used in os::create_thread(). Otherwise, due the strange logic in os::create_thread(),
-// the stack size for compiler threads will default to VMThreadStackSize, although it
-// is defined to 4M in os::Aix::default_stack_size()!
 define_pd_global(intx, CompilerThreadStackSize,  4096);
 
 // Allow extra space in DEBUG builds for asserts.
--- a/src/os_cpu/aix_ppc/vm/os_aix_ppc.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/aix_ppc/vm/os_aix_ppc.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -533,23 +533,17 @@
 ////////////////////////////////////////////////////////////////////////////////
 // thread stack
 
-size_t os::Aix::min_stack_allowed = 128*K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 128 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 128 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 128 * K;
 
 // return default stack size for thr_type
-size_t os::Aix::default_stack_size(os::ThreadType thr_type) {
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
   // default stack size (compiler thread needs larger stack)
-  // Notice that the setting for compiler threads here have no impact
-  // because of the strange 'fallback logic' in os::create_thread().
-  // Better set CompilerThreadStackSize in globals_<os_cpu>.hpp if you want to
-  // specify a different stack size for compiler threads!
   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
   return s;
 }
 
-size_t os::Aix::default_guard_size(os::ThreadType thr_type) {
-  return 2 * page_size();
-}
-
 /////////////////////////////////////////////////////////////////////////////
 // helper functions for fatal error handler
 
--- a/src/os_cpu/bsd_x86/vm/globals_bsd_x86.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/bsd_x86/vm/globals_bsd_x86.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,9 +31,11 @@
 //
 define_pd_global(bool, DontYieldALot,            false);
 #ifdef AMD64
+define_pd_global(intx, CompilerThreadStackSize,  1024);
 define_pd_global(intx, ThreadStackSize,          1024); // 0 => use system default
 define_pd_global(intx, VMThreadStackSize,        1024);
 #else
+define_pd_global(intx, CompilerThreadStackSize,  512);
 // ThreadStackSize 320 allows a couple of test cases to run while
 // keeping the number of threads that can be created high.  System
 // default ThreadStackSize appears to be 512 which is too big.
@@ -41,7 +43,6 @@
 define_pd_global(intx, VMThreadStackSize,        512);
 #endif // AMD64
 
-define_pd_global(intx, CompilerThreadStackSize,  0);
 
 define_pd_global(size_t, JVMInvokeMethodSlack,   8192);
 
--- a/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -838,9 +838,13 @@
 // thread stack
 
 #ifdef AMD64
-size_t os::Bsd::min_stack_allowed  = 64 * K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 64 * K;
 #else
-size_t os::Bsd::min_stack_allowed  =  (48 DEBUG_ONLY(+4))*K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = (48 DEBUG_ONLY(+ 4)) * K;
+size_t os::Posix::_java_thread_min_stack_allowed = (48 DEBUG_ONLY(+ 4)) * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = (48 DEBUG_ONLY(+ 4)) * K;
 
 #ifdef __GNUC__
 #define GET_GS() ({int gs; __asm__ volatile("movw %%gs, %w0":"=q"(gs)); gs&0xffff;})
@@ -849,7 +853,7 @@
 #endif // AMD64
 
 // return default stack size for thr_type
-size_t os::Bsd::default_stack_size(os::ThreadType thr_type) {
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
   // default stack size (compiler thread needs larger stack)
 #ifdef AMD64
   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
@@ -859,11 +863,6 @@
   return s;
 }
 
-size_t os::Bsd::default_guard_size(os::ThreadType thr_type) {
-  // Creating guard page is very expensive. Java thread has HotSpot
-  // guard page, only enable glibc guard page for non-Java threads.
-  return (thr_type == java_thread ? 0 : page_size());
-}
 
 // Java thread:
 //
--- a/src/os_cpu/bsd_zero/vm/os_bsd_zero.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/bsd_zero/vm/os_bsd_zero.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -282,9 +282,11 @@
 ///////////////////////////////////////////////////////////////////////////////
 // thread stack
 
-size_t os::Bsd::min_stack_allowed = 64 * K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 64 * K;
 
-size_t os::Bsd::default_stack_size(os::ThreadType thr_type) {
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
 #ifdef _LP64
   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
 #else
@@ -293,12 +295,6 @@
   return s;
 }
 
-size_t os::Bsd::default_guard_size(os::ThreadType thr_type) {
-  // Only enable glibc guard pages for non-Java threads
-  // (Java threads have HotSpot guard pages)
-  return (thr_type == java_thread ? 0 : page_size());
-}
-
 static void current_stack_region(address *bottom, size_t *size) {
   address stack_bottom;
   address stack_top;
--- a/src/os_cpu/linux_aarch64/vm/globals_linux_aarch64.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_aarch64/vm/globals_linux_aarch64.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2014, Red Hat Inc. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -33,7 +33,7 @@
 define_pd_global(intx, ThreadStackSize,          2048); // 0 => use system default
 define_pd_global(intx, VMThreadStackSize,        2048);
 
-define_pd_global(intx, CompilerThreadStackSize,  0);
+define_pd_global(intx, CompilerThreadStackSize,  2048);
 
 define_pd_global(uintx,JVMInvokeMethodSlack,     8192);
 
--- a/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -473,10 +473,12 @@
 ////////////////////////////////////////////////////////////////////////////////
 // thread stack
 
-size_t os::Linux::min_stack_allowed  = 64 * K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 64 * K;
 
 // return default stack size for thr_type
-size_t os::Linux::default_stack_size(os::ThreadType thr_type) {
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
   // default stack size (compiler thread needs larger stack)
   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
   return s;
--- a/src/os_cpu/linux_ppc/vm/globals_linux_ppc.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_ppc/vm/globals_linux_ppc.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -33,10 +33,6 @@
 define_pd_global(intx, ThreadStackSize,          2048); // 0 => use system default
 define_pd_global(intx, VMThreadStackSize,        2048);
 
-// if we set CompilerThreadStackSize to a value different than 0, it will
-// be used in os::create_thread(). Otherwise, due the strange logic in os::create_thread(),
-// the stack size for compiler threads will default to VMThreadStackSize, although it
-// is defined to 4M in os::Linux::default_stack_size()!
 define_pd_global(intx, CompilerThreadStackSize,  4096);
 
 // Allow extra space in DEBUG builds for asserts.
--- a/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -533,15 +533,13 @@
 ////////////////////////////////////////////////////////////////////////////////
 // thread stack
 
-size_t os::Linux::min_stack_allowed = 128*K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 128 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 128 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 128 * K;
 
 // return default stack size for thr_type
-size_t os::Linux::default_stack_size(os::ThreadType thr_type) {
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
   // default stack size (compiler thread needs larger stack)
-  // Notice that the setting for compiler threads here have no impact
-  // because of the strange 'fallback logic' in os::create_thread().
-  // Better set CompilerThreadStackSize in globals_<os_cpu>.hpp if you want to
-  // specify a different stack size for compiler threads!
   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1024 * K);
   return s;
 }
--- a/src/os_cpu/linux_sparc/vm/globals_linux_sparc.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_sparc/vm/globals_linux_sparc.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,6 @@
 //
 
 define_pd_global(size_t, JVMInvokeMethodSlack,   12288);
-define_pd_global(intx, CompilerThreadStackSize,  0);
 
 // Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(size_t, HeapBaseMinAddress,     CONST64(4)*G);
--- a/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -726,10 +726,12 @@
 ///////////////////////////////////////////////////////////////////////////////
 // thread stack
 
-size_t os::Linux::min_stack_allowed  = 128 * K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 128 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 128 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 128 * K;
 
 // return default stack size for thr_type
-size_t os::Linux::default_stack_size(os::ThreadType thr_type) {
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
   // default stack size (compiler thread needs larger stack)
   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
   return s;
--- a/src/os_cpu/linux_x86/vm/globals_linux_x86.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_x86/vm/globals_linux_x86.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,9 +30,11 @@
 
 define_pd_global(bool, DontYieldALot,            false);
 #ifdef AMD64
+define_pd_global(intx, CompilerThreadStackSize,  1024);
 define_pd_global(intx, ThreadStackSize,          1024); // 0 => use system default
 define_pd_global(intx, VMThreadStackSize,        1024);
 #else
+define_pd_global(intx, CompilerThreadStackSize,  512);
 // ThreadStackSize 320 allows a couple of test cases to run while
 // keeping the number of threads that can be created high.  System
 // default ThreadStackSize appears to be 512 which is too big.
@@ -40,8 +42,6 @@
 define_pd_global(intx, VMThreadStackSize,        512);
 #endif // AMD64
 
-define_pd_global(intx, CompilerThreadStackSize,  0);
-
 define_pd_global(size_t, JVMInvokeMethodSlack,   8192);
 
 // Used on 64 bit platforms for UseCompressedOops base address
--- a/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -676,13 +676,17 @@
 // thread stack
 
 #ifdef AMD64
-size_t os::Linux::min_stack_allowed  = 64 * K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 64 * K;
 #else
-size_t os::Linux::min_stack_allowed  =  (48 DEBUG_ONLY(+4))*K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = (48 DEBUG_ONLY(+ 4)) * K;
+size_t os::Posix::_java_thread_min_stack_allowed = (48 DEBUG_ONLY(+ 4)) * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = (48 DEBUG_ONLY(+ 4)) * K;
 #endif // AMD64
 
 // return default stack size for thr_type
-size_t os::Linux::default_stack_size(os::ThreadType thr_type) {
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
   // default stack size (compiler thread needs larger stack)
 #ifdef AMD64
   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
--- a/src/os_cpu/linux_zero/vm/os_linux_zero.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/linux_zero/vm/os_linux_zero.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -307,9 +307,11 @@
 ///////////////////////////////////////////////////////////////////////////////
 // thread stack
 
-size_t os::Linux::min_stack_allowed = 64 * K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 64 * K;
 
-size_t os::Linux::default_stack_size(os::ThreadType thr_type) {
+size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
 #ifdef _LP64
   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
 #else
--- a/src/os_cpu/solaris_sparc/vm/globals_solaris_sparc.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/solaris_sparc/vm/globals_solaris_sparc.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,6 @@
 //
 
 define_pd_global(size_t, JVMInvokeMethodSlack,   12288);
-define_pd_global(intx, CompilerThreadStackSize,  0);
 
 // Used on 64 bit platforms for UseCompressedOops base address
 #ifdef _LP64
--- a/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -84,9 +84,13 @@
 // Minimum stack size for the VM.  It's easier to document a constant
 // but it's different for x86 and sparc because the page sizes are different.
 #ifdef _LP64
-size_t os::Solaris::min_stack_allowed = 128*K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 128 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 128 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 128 * K;
 #else
-size_t os::Solaris::min_stack_allowed = 96*K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 96 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 96 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 96 * K;
 #endif
 
 int os::Solaris::max_register_window_saves_before_flushing() {
@@ -444,7 +448,7 @@
 
 
     if (thread->thread_state() == _thread_in_vm) {
-      if (sig == SIGBUS && info->si_code == BUS_OBJERR && thread->doing_unsafe_access()) {
+      if (sig == SIGBUS && thread->doing_unsafe_access()) {
         stub = SharedRuntime::handle_unsafe_access(thread, npc);
       }
     }
--- a/src/os_cpu/solaris_x86/vm/globals_solaris_x86.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/solaris_x86/vm/globals_solaris_x86.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,10 +30,12 @@
 
 define_pd_global(bool, DontYieldALot,            true); // Determined in the design center
 #ifdef AMD64
+define_pd_global(intx, CompilerThreadStackSize,  1024);
 define_pd_global(intx, ThreadStackSize,          1024); // 0 => use system default
 define_pd_global(intx, VMThreadStackSize,        1024);
 define_pd_global(size_t, JVMInvokeMethodSlack,   8*K);
 #else
+define_pd_global(intx, CompilerThreadStackSize,  512);
 // ThreadStackSize 320 allows a couple of test cases to run while
 // keeping the number of threads that can be created high.
 define_pd_global(intx, ThreadStackSize,          320);
@@ -41,7 +43,6 @@
 define_pd_global(size_t, JVMInvokeMethodSlack,   10*K);
 #endif // AMD64
 
-define_pd_global(intx, CompilerThreadStackSize,  0);
 
 // Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(size_t, HeapBaseMinAddress,     2*G);
--- a/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -86,15 +86,19 @@
 
 #define MAX_PATH (2 * K)
 
-// Minimum stack size for the VM.  It's easier to document a constant value
+// Minimum stack sizes for the VM.  It's easier to document a constant value
 // but it's different for x86 and sparc because the page sizes are different.
 #ifdef AMD64
-size_t os::Solaris::min_stack_allowed = 224*K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 394 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 224 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 224 * K;
 #define REG_SP REG_RSP
 #define REG_PC REG_RIP
 #define REG_FP REG_RBP
 #else
-size_t os::Solaris::min_stack_allowed = 64*K;
+size_t os::Posix::_compiler_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_java_thread_min_stack_allowed = 64 * K;
+size_t os::Posix::_vm_internal_thread_min_stack_allowed = 64 * K;
 #define REG_SP UESP
 #define REG_PC EIP
 #define REG_FP EBP
--- a/src/share/vm/c1/c1_Compiler.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/c1/c1_Compiler.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -221,6 +221,9 @@
   case vmIntrinsics::_putCharStringU:
 #ifdef TRACE_HAVE_INTRINSICS
   case vmIntrinsics::_counterTime:
+#if defined(_LP64) || !defined(TRACE_ID_CLASS_SHIFT)
+  case vmIntrinsics::_getClassId:
+#endif
 #endif
     break;
   default:
--- a/src/share/vm/c1/c1_LIRGenerator.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/c1/c1_LIRGenerator.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -2410,6 +2410,15 @@
 #endif // INCLUDE_ALL_GCS
 
   if (x->is_volatile() && os::is_MP()) __ membar_acquire();
+
+  /* Normalize boolean value returned by unsafe operation, i.e., value  != 0 ? value = true : value false. */
+  if (type == T_BOOLEAN) {
+    LabelObj* equalZeroLabel = new LabelObj();
+    __ cmp(lir_cond_equal, value, 0);
+    __ branch(lir_cond_equal, T_BOOLEAN, equalZeroLabel->label());
+    __ move(LIR_OprFact::intConst(1), value);
+    __ branch_destination(equalZeroLabel->label());
+  }
 }
 
 
@@ -3083,6 +3092,37 @@
   __ cmove(lir_cond(x->cond()), t_val.result(), f_val.result(), reg, as_BasicType(x->x()->type()));
 }
 
+#ifdef TRACE_HAVE_INTRINSICS
+void LIRGenerator::do_ClassIDIntrinsic(Intrinsic* x) {
+  CodeEmitInfo* info = state_for(x);
+  CodeEmitInfo* info2 = new CodeEmitInfo(info); // Clone for the second null check
+
+  assert(info != NULL, "must have info");
+  LIRItem arg(x->argument_at(0), this);
+
+  arg.load_item();
+  LIR_Opr klass = new_register(T_METADATA);
+  __ move(new LIR_Address(arg.result(), java_lang_Class::klass_offset_in_bytes(), T_ADDRESS), klass, info);
+  LIR_Opr id = new_register(T_LONG);
+  ByteSize offset = TRACE_KLASS_TRACE_ID_OFFSET;
+  LIR_Address* trace_id_addr = new LIR_Address(klass, in_bytes(offset), T_LONG);
+
+  __ move(trace_id_addr, id);
+  __ logical_or(id, LIR_OprFact::longConst(0x01l), id);
+  __ store(id, trace_id_addr);
+
+#ifdef TRACE_ID_META_BITS
+  __ logical_and(id, LIR_OprFact::longConst(~TRACE_ID_META_BITS), id);
+#endif
+#ifdef TRACE_ID_CLASS_SHIFT
+  __ unsigned_shift_right(id, TRACE_ID_CLASS_SHIFT, id);
+#endif
+
+  __ move(id, rlock_result(x));
+}
+#endif
+
+
 void LIRGenerator::do_RuntimeCall(address routine, Intrinsic* x) {
   assert(x->number_of_arguments() == 0, "wrong type");
   // Enforce computation of _reserved_argument_area_size which is required on some platforms.
@@ -3108,6 +3148,9 @@
   }
 
 #ifdef TRACE_HAVE_INTRINSICS
+  case vmIntrinsics::_getClassId:
+    do_ClassIDIntrinsic(x);
+    break;
   case vmIntrinsics::_counterTime:
     do_RuntimeCall(CAST_FROM_FN_PTR(address, TRACE_TIME_METHOD), x);
     break;
--- a/src/share/vm/c1/c1_LIRGenerator.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/c1/c1_LIRGenerator.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -438,6 +438,10 @@
   SwitchRangeArray* create_lookup_ranges(LookupSwitch* x);
   void do_SwitchRanges(SwitchRangeArray* x, LIR_Opr value, BlockBegin* default_sux);
 
+#ifdef TRACE_HAVE_INTRINSICS
+  void do_ClassIDIntrinsic(Intrinsic* x);
+#endif
+
   void do_RuntimeCall(address routine, Intrinsic* x);
 
   ciKlass* profile_type(ciMethodData* md, int md_first_offset, int md_offset, intptr_t profiled_k,
--- a/src/share/vm/c1/c1_Runtime1.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/c1/c1_Runtime1.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -576,9 +576,8 @@
     // normal bytecode execution.
     thread->clear_exception_oop_and_pc();
 
-    Handle original_exception(thread, exception());
-
-    continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false);
+    bool recursive_exception = false;
+    continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false, recursive_exception);
     // If an exception was thrown during exception dispatch, the exception oop may have changed
     thread->set_exception_oop(exception());
     thread->set_exception_pc(pc);
@@ -586,8 +585,9 @@
     // the exception cache is used only by non-implicit exceptions
     // Update the exception cache only when there didn't happen
     // another exception during the computation of the compiled
-    // exception handler.
-    if (continuation != NULL && original_exception() == exception()) {
+    // exception handler. Checking for exception oop equality is not
+    // sufficient because some exceptions are pre-allocated and reused.
+    if (continuation != NULL && !recursive_exception) {
       nm->add_handler_for_exception_and_pc(exception, pc, continuation);
     }
   }
--- a/src/share/vm/classfile/altHashing.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/altHashing.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -205,103 +205,3 @@
 juint AltHashing::murmur3_32(const int* data, int len) {
   return murmur3_32(0, data, len);
 }
-
-#ifndef PRODUCT
-// Overloaded versions for internal test.
-juint AltHashing::murmur3_32(const jbyte* data, int len) {
-  return murmur3_32(0, data, len);
-}
-
-juint AltHashing::murmur3_32(const jchar* data, int len) {
-  return murmur3_32(0, data, len);
-}
-
-// Internal test for alternate hashing.  Translated from JDK version
-// test/sun/misc/Hashing.java
-static const jbyte ONE_BYTE[] = { (jbyte) 0x80};
-static const jbyte TWO_BYTE[] = { (jbyte) 0x80, (jbyte) 0x81};
-static const jchar ONE_CHAR[] = { (jchar) 0x8180};
-static const jbyte THREE_BYTE[] = { (jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82};
-static const jbyte FOUR_BYTE[] = { (jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82, (jbyte) 0x83};
-static const jchar TWO_CHAR[] = { (jchar) 0x8180, (jchar) 0x8382};
-static const jint ONE_INT[] = { (jint)0x83828180};
-static const jbyte SIX_BYTE[] = { (jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82, (jbyte) 0x83, (jbyte) 0x84, (jbyte) 0x85};
-static const jchar THREE_CHAR[] = { (jchar) 0x8180, (jchar) 0x8382, (jchar) 0x8584};
-static const jbyte EIGHT_BYTE[] = {
-  (jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82,
-  (jbyte) 0x83, (jbyte) 0x84, (jbyte) 0x85,
-  (jbyte) 0x86, (jbyte) 0x87};
-static const jchar FOUR_CHAR[] = {
-  (jchar) 0x8180, (jchar) 0x8382,
-  (jchar) 0x8584, (jchar) 0x8786};
-
-static const jint TWO_INT[] = { (jint)0x83828180, (jint)0x87868584};
-
-static const juint MURMUR3_32_X86_CHECK_VALUE = 0xB0F57EE3;
-
-void AltHashing::testMurmur3_32_ByteArray() {
-  // printf("testMurmur3_32_ByteArray\n");
-
-  jbyte vector[256];
-  jbyte hashes[4 * 256];
-
-  for (int i = 0; i < 256; i++) {
-    vector[i] = (jbyte) i;
-  }
-
-  // Hash subranges {}, {0}, {0,1}, {0,1,2}, ..., {0,...,255}
-  for (int i = 0; i < 256; i++) {
-    juint hash = murmur3_32(256 - i, vector, i);
-    hashes[i * 4] = (jbyte) hash;
-    hashes[i * 4 + 1] = (jbyte)(hash >> 8);
-    hashes[i * 4 + 2] = (jbyte)(hash >> 16);
-    hashes[i * 4 + 3] = (jbyte)(hash >> 24);
-  }
-
-  // hash to get const result.
-  juint final_hash = murmur3_32(hashes, 4*256);
-
-  assert (MURMUR3_32_X86_CHECK_VALUE == final_hash,
-          "Calculated hash result not as expected. Expected %08X got %08X\n",
-          MURMUR3_32_X86_CHECK_VALUE,
-          final_hash);
-}
-
-void AltHashing::testEquivalentHashes() {
-  juint jbytes, jchars, ints;
-
-  // printf("testEquivalentHashes\n");
-
-  jbytes = murmur3_32(TWO_BYTE, 2);
-  jchars = murmur3_32(ONE_CHAR, 1);
-  assert (jbytes == jchars,
-          "Hashes did not match. b:%08x != c:%08x\n", jbytes, jchars);
-
-  jbytes = murmur3_32(FOUR_BYTE, 4);
-  jchars = murmur3_32(TWO_CHAR, 2);
-  ints = murmur3_32(ONE_INT, 1);
-  assert ((jbytes == jchars) && (jbytes == ints),
-          "Hashes did not match. b:%08x != c:%08x != i:%08x\n", jbytes, jchars, ints);
-
-  jbytes = murmur3_32(SIX_BYTE, 6);
-  jchars = murmur3_32(THREE_CHAR, 3);
-  assert (jbytes == jchars,
-         "Hashes did not match. b:%08x != c:%08x\n", jbytes, jchars);
-
-  jbytes = murmur3_32(EIGHT_BYTE, 8);
-  jchars = murmur3_32(FOUR_CHAR, 4);
-  ints = murmur3_32(TWO_INT, 2);
-  assert ((jbytes == jchars) && (jbytes == ints),
-          "Hashes did not match. b:%08x != c:%08x != i:%08x\n", jbytes, jchars, ints);
-}
-
-// Returns true if the alternate hashcode is correct
-void AltHashing::test_alt_hash() {
-  testMurmur3_32_ByteArray();
-  testEquivalentHashes();
-}
-
-void AltHashing_test() {
-  AltHashing::test_alt_hash();
-}
-#endif // PRODUCT
--- a/src/share/vm/classfile/altHashing.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/altHashing.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,26 +37,18 @@
  */
 
 class AltHashing : AllStatic {
+  friend class AltHashingTest;
 
   // utility function copied from java/lang/Integer
   static juint Integer_rotateLeft(juint i, int distance) {
-    return (i << distance) | (i >> (32-distance));
+    return (i << distance) | (i >> (32 - distance));
   }
   static juint murmur3_32(const int* data, int len);
   static juint murmur3_32(juint seed, const int* data, int len);
 
-#ifndef PRODUCT
-  // Hashing functions used for internal testing
-  static juint murmur3_32(const jbyte* data, int len);
-  static juint murmur3_32(const jchar* data, int len);
-  static void testMurmur3_32_ByteArray();
-  static void testEquivalentHashes();
-#endif // PRODUCT
-
  public:
   static juint compute_seed();
   static juint murmur3_32(juint seed, const jbyte* data, int len);
   static juint murmur3_32(juint seed, const jchar* data, int len);
-  NOT_PRODUCT(static void test_alt_hash();)
 };
 #endif // SHARE_VM_CLASSFILE_ALTHASHING_HPP
--- a/src/share/vm/classfile/classFileParser.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/classFileParser.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -95,7 +95,6 @@
 #define JAVA_6_VERSION                    50
 
 // Used for backward compatibility reasons:
-// - to check NameAndType_info signatures more aggressively
 // - to disallow argument and require ACC_STATIC for <clinit> methods
 #define JAVA_7_VERSION                    51
 
@@ -564,7 +563,7 @@
         break;
       }
       case JVM_CONSTANT_NameAndType: {
-        if (_need_verify && _major_version >= JAVA_7_VERSION) {
+        if (_need_verify) {
           const int sig_index = cp->signature_ref_index_at(index);
           const int name_index = cp->name_ref_index_at(index);
           const Symbol* const name = cp->symbol_at(name_index);
@@ -572,9 +571,17 @@
           guarantee_property(sig->utf8_length() != 0,
             "Illegal zero length constant pool entry at %d in class %s",
             sig_index, CHECK);
+          guarantee_property(name->utf8_length() != 0,
+            "Illegal zero length constant pool entry at %d in class %s",
+            name_index, CHECK);
+
           if (sig->byte_at(0) == JVM_SIGNATURE_FUNC) {
+            // Format check method name and signature
+            verify_legal_method_name(name, CHECK);
             verify_legal_method_signature(name, sig, CHECK);
           } else {
+            // Format check field name and signature
+            verify_legal_field_name(name, CHECK);
             verify_legal_field_signature(name, sig, CHECK);
           }
         }
@@ -595,42 +602,32 @@
         const Symbol* const name = cp->symbol_at(name_ref_index);
         const Symbol* const signature = cp->symbol_at(signature_ref_index);
         if (tag == JVM_CONSTANT_Fieldref) {
-          verify_legal_field_name(name, CHECK);
-          if (_need_verify && _major_version >= JAVA_7_VERSION) {
-            // Signature is verified above, when iterating NameAndType_info.
-            // Need only to be sure it's non-zero length and the right type.
+          if (_need_verify) {
+            // Field name and signature are verified above, when iterating NameAndType_info.
+            // Need only to be sure signature is non-zero length and the right type.
             if (signature->utf8_length() == 0 ||
                 signature->byte_at(0) == JVM_SIGNATURE_FUNC) {
-              throwIllegalSignature(
-                "Field", name, signature, CHECK);
+              throwIllegalSignature("Field", name, signature, CHECK);
             }
-          } else {
-            verify_legal_field_signature(name, signature, CHECK);
           }
         } else {
-          verify_legal_method_name(name, CHECK);
-          if (_need_verify && _major_version >= JAVA_7_VERSION) {
-            // Signature is verified above, when iterating NameAndType_info.
-            // Need only to be sure it's non-zero length and the right type.
+          if (_need_verify) {
+            // Method name and signature are verified above, when iterating NameAndType_info.
+            // Need only to be sure signature is non-zero length and the right type.
             if (signature->utf8_length() == 0 ||
                 signature->byte_at(0) != JVM_SIGNATURE_FUNC) {
-              throwIllegalSignature(
-                "Method", name, signature, CHECK);
+              throwIllegalSignature("Method", name, signature, CHECK);
             }
-          } else {
-            verify_legal_method_signature(name, signature, CHECK);
           }
-          if (tag == JVM_CONSTANT_Methodref) {
-            // 4509014: If a class method name begins with '<', it must be "<init>".
-            assert(name != NULL, "method name in constant pool is null");
-            const unsigned int name_len = name->utf8_length();
-            if (name_len != 0 && name->byte_at(0) == '<') {
-              if (name != vmSymbols::object_initializer_name()) {
-                classfile_parse_error(
-                  "Bad method name at constant pool index %u in class file %s",
-                  name_ref_index, CHECK);
-              }
-            }
+          // 4509014: If a class method name begins with '<', it must be "<init>"
+          const unsigned int name_len = name->utf8_length();
+          if (tag == JVM_CONSTANT_Methodref &&
+              name_len != 0 &&
+              name->byte_at(0) == '<' &&
+              name != vmSymbols::object_initializer_name()) {
+            classfile_parse_error(
+              "Bad method name at constant pool index %u in class file %s",
+              name_ref_index, CHECK);
           }
         }
         break;
@@ -4843,19 +4840,28 @@
         }
       }
       else {
-        // 4900761: For class version > 48, any unicode is allowed in class name.
+        // Skip leading 'L' and ignore first appearance of ';'
         length--;
         signature++;
-        while (length > 0 && signature[0] != ';') {
-          if (signature[0] == '.') {
-            classfile_parse_error("Class name contains illegal character '.' in descriptor in class file %s", CHECK_0);
+        char* c = strchr((char*) signature, ';');
+        // Format check signature
+        if (c != NULL) {
+          ResourceMark rm(THREAD);
+          int newlen = c - (char*) signature;
+          char* sig = NEW_RESOURCE_ARRAY(char, newlen + 1);
+          strncpy(sig, signature, newlen);
+          sig[newlen] = '\0';
+
+          bool legal = verify_unqualified_name(sig, newlen, LegalClass);
+          if (!legal) {
+            classfile_parse_error("Class name contains illegal character "
+                                  "in descriptor in class file %s",
+                                  CHECK_0);
+            return NULL;
           }
-          length--;
-          signature++;
+          return signature + newlen + 1;
         }
-        if (signature[0] == ';') { return signature + 1; }
       }
-
       return NULL;
     }
     case JVM_SIGNATURE_ARRAY:
@@ -4869,7 +4875,6 @@
       length--;
       void_ok = false;
       break;
-
     default:
       return NULL;
     }
@@ -5402,6 +5407,59 @@
   debug_only(ik->verify();)
 }
 
+// For an anonymous class that is in the unnamed package, move it to its host class's
+// package by prepending its host class's package name to its class name and setting
+// its _class_name field.
+void ClassFileParser::prepend_host_package_name(const InstanceKlass* host_klass, TRAPS) {
+  ResourceMark rm(THREAD);
+  assert(strrchr(_class_name->as_C_string(), '/') == NULL,
+         "Anonymous class should not be in a package");
+  const char* host_pkg_name =
+    ClassLoader::package_from_name(host_klass->name()->as_C_string(), NULL);
+
+  if (host_pkg_name != NULL) {
+    size_t host_pkg_len = strlen(host_pkg_name);
+    int class_name_len = _class_name->utf8_length();
+    char* new_anon_name =
+      NEW_RESOURCE_ARRAY(char, host_pkg_len + 1 + class_name_len);
+    // Copy host package name and trailing /.
+    strncpy(new_anon_name, host_pkg_name, host_pkg_len);
+    new_anon_name[host_pkg_len] = '/';
+    // Append anonymous class name. The anonymous class name can contain odd
+    // characters.  So, do a strncpy instead of using sprintf("%s...").
+    strncpy(new_anon_name + host_pkg_len + 1, (char *)_class_name->base(), class_name_len);
+
+    // Create a symbol and update the anonymous class name.
+    _class_name = SymbolTable::new_symbol(new_anon_name,
+                                          (int)host_pkg_len + 1 + class_name_len,
+                                          CHECK);
+  }
+}
+
+// If the host class and the anonymous class are in the same package then do
+// nothing.  If the anonymous class is in the unnamed package then move it to its
+// host's package.  If the classes are in different packages then throw an IAE
+// exception.
+void ClassFileParser::fix_anonymous_class_name(TRAPS) {
+  assert(_host_klass != NULL, "Expected an anonymous class");
+
+  const jbyte* anon_last_slash = UTF8::strrchr(_class_name->base(),
+                                               _class_name->utf8_length(), '/');
+  if (anon_last_slash == NULL) {  // Unnamed package
+    prepend_host_package_name(_host_klass, CHECK);
+  } else {
+    if (!InstanceKlass::is_same_class_package(_host_klass->class_loader(),
+                                              _host_klass->name(),
+                                              _host_klass->class_loader(),
+                                              _class_name)) {
+      ResourceMark rm(THREAD);
+      THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
+        err_msg("Host class %s and anonymous class %s are in different packages",
+        _host_klass->name()->as_C_string(), _class_name->as_C_string()));
+    }
+  }
+}
+
 static bool relax_format_check_for(ClassLoaderData* loader_data) {
   bool trusted = (loader_data->is_the_null_class_loader_data() ||
                   SystemDictionary::is_platform_class_loader(loader_data->class_loader()));
@@ -5417,7 +5475,7 @@
                                  Symbol* name,
                                  ClassLoaderData* loader_data,
                                  Handle protection_domain,
-                                 const Klass* host_klass,
+                                 const InstanceKlass* host_klass,
                                  GrowableArray<Handle>* cp_patches,
                                  Publicity pub_level,
                                  TRAPS) :
@@ -5692,6 +5750,13 @@
     return;
   }
 
+  // if this is an anonymous class fix up its name if it's in the unnamed
+  // package.  Otherwise, throw IAE if it is in a different package than
+  // its host class.
+  if (_host_klass != NULL) {
+    fix_anonymous_class_name(CHECK);
+  }
+
   // Verification prevents us from creating names with dots in them, this
   // asserts that that's the case.
   assert(is_internal_format(_class_name), "external class name format used internally");
--- a/src/share/vm/classfile/classFileParser.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/classFileParser.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -79,7 +79,7 @@
   const Symbol* _requested_name;
   Symbol* _class_name;
   mutable ClassLoaderData* _loader_data;
-  const Klass* _host_klass;
+  const InstanceKlass* _host_klass;
   GrowableArray<Handle>* _cp_patches; // overrides for CP entries
 
   // Metadata created before the instance klass is created.  Must be deallocated
@@ -155,6 +155,9 @@
                                   ConstantPool* cp,
                                   TRAPS);
 
+  void prepend_host_package_name(const InstanceKlass* host_klass, TRAPS);
+  void fix_anonymous_class_name(TRAPS);
+
   void fill_instance_klass(InstanceKlass* ik, bool cf_changed_in_CFLH, TRAPS);
   void set_klass(InstanceKlass* instance);
 
@@ -474,7 +477,7 @@
                   Symbol* name,
                   ClassLoaderData* loader_data,
                   Handle protection_domain,
-                  const Klass* host_klass,
+                  const InstanceKlass* host_klass,
                   GrowableArray<Handle>* cp_patches,
                   Publicity pub_level,
                   TRAPS);
@@ -500,7 +503,7 @@
   bool is_anonymous() const { return _host_klass != NULL; }
   bool is_interface() const { return _access_flags.is_interface(); }
 
-  const Klass* host_klass() const { return _host_klass; }
+  const InstanceKlass* host_klass() const { return _host_klass; }
   const GrowableArray<Handle>* cp_patches() const { return _cp_patches; }
   ClassLoaderData* loader_data() const { return _loader_data; }
   const Symbol* class_name() const { return _class_name; }
--- a/src/share/vm/classfile/classLoaderData.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/classLoaderData.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -962,11 +962,11 @@
 
   // Mark metadata seen on the stack only so we can delete unneeded entries.
   // Only walk all metadata, including the expensive code cache walk, for Full GC
-  // and only if class redefinition occurred and if there are previous versions of
+  // and only if class redefinition and if there's previous versions of
   // Klasses to delete.
   bool walk_all_metadata = clean_previous_versions &&
                            JvmtiExport::has_redefined_a_class() &&
-                           InstanceKlass::has_previous_versions();
+                           InstanceKlass::has_previous_versions_and_reset();
   MetadataOnStackMark md_on_stack(walk_all_metadata);
 
   // Save previous _unloading pointer for CMS which may add to unloading list before
--- a/src/share/vm/classfile/klassFactory.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/klassFactory.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -94,7 +94,7 @@
                                                      Symbol* name,
                                                      ClassLoaderData* loader_data,
                                                      Handle protection_domain,
-                                                     const Klass* host_klass,
+                                                     const InstanceKlass* host_klass,
                                                      GrowableArray<Handle>* cp_patches,
                                                      TRAPS) {
 
--- a/src/share/vm/classfile/klassFactory.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/klassFactory.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -72,7 +72,7 @@
                                                 Symbol* name,
                                                 ClassLoaderData* loader_data,
                                                 Handle protection_domain,
-                                                const Klass* host_klass,
+                                                const InstanceKlass* host_klass,
                                                 GrowableArray<Handle>* cp_patches,
                                                 TRAPS);
 };
--- a/src/share/vm/classfile/systemDictionary.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/systemDictionary.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1027,7 +1027,7 @@
                                       Handle class_loader,
                                       Handle protection_domain,
                                       ClassFileStream* st,
-                                      const Klass* host_klass,
+                                      const InstanceKlass* host_klass,
                                       GrowableArray<Handle>* cp_patches,
                                       TRAPS) {
 
--- a/src/share/vm/classfile/systemDictionary.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/systemDictionary.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -299,7 +299,7 @@
                              Handle class_loader,
                              Handle protection_domain,
                              ClassFileStream* st,
-                             const Klass* host_klass,
+                             const InstanceKlass* host_klass,
                              GrowableArray<Handle>* cp_patches,
                              TRAPS);
 
--- a/src/share/vm/classfile/verifier.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/verifier.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -2786,7 +2786,7 @@
       // direct interface relative to the host class
       have_imr_indirect = (have_imr_indirect &&
                            !is_same_or_direct_interface(
-                             InstanceKlass::cast(current_class()->host_klass()),
+                             current_class()->host_klass(),
                              host_klass_type, ref_class_type));
     }
     if (!subtype) {
--- a/src/share/vm/classfile/vmSymbols.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/classfile/vmSymbols.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -366,6 +366,7 @@
   switch(id) {
 #ifdef TRACE_HAVE_INTRINSICS
   case vmIntrinsics::_counterTime:
+  case vmIntrinsics::_getClassId:
 #endif
   case vmIntrinsics::_currentTimeMillis:
   case vmIntrinsics::_nanoTime:
--- a/src/share/vm/code/codeCache.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/code/codeCache.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1305,7 +1305,7 @@
     event.set_entryCount(heap->blob_count());
     event.set_methodCount(heap->nmethod_count());
     event.set_adaptorCount(heap->adapter_count());
-    event.set_unallocatedCapacity(heap->unallocated_capacity()/K);
+    event.set_unallocatedCapacity(heap->unallocated_capacity());
     event.set_fullCount(heap->full_count());
     event.commit();
   }
--- a/src/share/vm/gc/cms/concurrentMarkSweepGeneration.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/cms/concurrentMarkSweepGeneration.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -3511,6 +3511,7 @@
                                                                   conc_workers()->active_workers(),
                                                                   Threads::number_of_non_daemon_threads());
   num_workers = conc_workers()->update_active_workers(num_workers);
+  log_info(gc,task)("Using %u workers of %u for marking", num_workers, conc_workers()->total_workers());
 
   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
 
--- a/src/share/vm/gc/cms/parNewGeneration.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/cms/parNewGeneration.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -899,6 +899,8 @@
                                                workers->active_workers(),
                                                Threads::number_of_non_daemon_threads());
   active_workers = workers->update_active_workers(active_workers);
+  log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers->total_workers());
+
   _old_gen = gch->old_gen();
 
   // If the next generation is too full to accommodate worst-case promotion
--- a/src/share/vm/gc/g1/g1CodeCacheRemSet.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1CodeCacheRemSet.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "code/codeCache.hpp"
 #include "code/nmethod.hpp"
+#include "gc/g1/g1CodeRootSetTable.hpp"
 #include "gc/g1/g1CodeCacheRemSet.hpp"
 #include "gc/g1/heapRegion.hpp"
 #include "memory/heap.hpp"
@@ -33,58 +34,13 @@
 #include "utilities/hashtable.inline.hpp"
 #include "utilities/stack.inline.hpp"
 
-class CodeRootSetTable : public Hashtable<nmethod*, mtGC> {
-  friend class G1CodeRootSetTest;
-  typedef HashtableEntry<nmethod*, mtGC> Entry;
+G1CodeRootSetTable* volatile G1CodeRootSetTable::_purge_list = NULL;
 
-  static CodeRootSetTable* volatile _purge_list;
-
-  CodeRootSetTable* _purge_next;
-
-  unsigned int compute_hash(nmethod* nm) {
-    uintptr_t hash = (uintptr_t)nm;
-    return hash ^ (hash >> 7); // code heap blocks are 128byte aligned
-  }
-
-  void remove_entry(Entry* e, Entry* previous);
-  Entry* new_entry(nmethod* nm);
-
- public:
-  CodeRootSetTable(int size) : Hashtable<nmethod*, mtGC>(size, sizeof(Entry)), _purge_next(NULL) {}
-  ~CodeRootSetTable();
-
-  // Needs to be protected locks
-  bool add(nmethod* nm);
-  bool remove(nmethod* nm);
-
-  // Can be called without locking
-  bool contains(nmethod* nm);
-
-  int entry_size() const { return BasicHashtable<mtGC>::entry_size(); }
-
-  void copy_to(CodeRootSetTable* new_table);
-  void nmethods_do(CodeBlobClosure* blk);
-
-  template<typename CB>
-  int remove_if(CB& should_remove);
-
-  static void purge_list_append(CodeRootSetTable* tbl);
-  static void purge();
-
-  static size_t static_mem_size() {
-    return sizeof(_purge_list);
-  }
-
-  size_t mem_size();
-};
-
-CodeRootSetTable* volatile CodeRootSetTable::_purge_list = NULL;
-
-size_t CodeRootSetTable::mem_size() {
-  return sizeof(CodeRootSetTable) + (entry_size() * number_of_entries()) + (sizeof(HashtableBucket<mtGC>) * table_size());
+size_t G1CodeRootSetTable::mem_size() {
+  return sizeof(G1CodeRootSetTable) + (entry_size() * number_of_entries()) + (sizeof(HashtableBucket<mtGC>) * table_size());
 }
 
-CodeRootSetTable::Entry* CodeRootSetTable::new_entry(nmethod* nm) {
+G1CodeRootSetTable::Entry* G1CodeRootSetTable::new_entry(nmethod* nm) {
   unsigned int hash = compute_hash(nm);
   Entry* entry = (Entry*) new_entry_free_list();
   if (entry == NULL) {
@@ -96,7 +52,7 @@
   return entry;
 }
 
-void CodeRootSetTable::remove_entry(Entry* e, Entry* previous) {
+void G1CodeRootSetTable::remove_entry(Entry* e, Entry* previous) {
   int index = hash_to_index(e->hash());
   assert((e == bucket(index)) == (previous == NULL), "if e is the first entry then previous should be null");
 
@@ -108,7 +64,7 @@
   free_entry(e);
 }
 
-CodeRootSetTable::~CodeRootSetTable() {
+G1CodeRootSetTable::~G1CodeRootSetTable() {
   for (int index = 0; index < table_size(); ++index) {
     for (Entry* e = bucket(index); e != NULL; ) {
       Entry* to_remove = e;
@@ -125,7 +81,7 @@
   }
 }
 
-bool CodeRootSetTable::add(nmethod* nm) {
+bool G1CodeRootSetTable::add(nmethod* nm) {
   if (!contains(nm)) {
     Entry* e = new_entry(nm);
     int index = hash_to_index(e->hash());
@@ -135,7 +91,7 @@
   return false;
 }
 
-bool CodeRootSetTable::contains(nmethod* nm) {
+bool G1CodeRootSetTable::contains(nmethod* nm) {
   int index = hash_to_index(compute_hash(nm));
   for (Entry* e = bucket(index); e != NULL; e = e->next()) {
     if (e->literal() == nm) {
@@ -145,7 +101,7 @@
   return false;
 }
 
-bool CodeRootSetTable::remove(nmethod* nm) {
+bool G1CodeRootSetTable::remove(nmethod* nm) {
   int index = hash_to_index(compute_hash(nm));
   Entry* previous = NULL;
   for (Entry* e = bucket(index); e != NULL; previous = e, e = e->next()) {
@@ -157,7 +113,7 @@
   return false;
 }
 
-void CodeRootSetTable::copy_to(CodeRootSetTable* new_table) {
+void G1CodeRootSetTable::copy_to(G1CodeRootSetTable* new_table) {
   for (int index = 0; index < table_size(); ++index) {
     for (Entry* e = bucket(index); e != NULL; e = e->next()) {
       new_table->add(e->literal());
@@ -166,7 +122,7 @@
   new_table->copy_freelist(this);
 }
 
-void CodeRootSetTable::nmethods_do(CodeBlobClosure* blk) {
+void G1CodeRootSetTable::nmethods_do(CodeBlobClosure* blk) {
   for (int index = 0; index < table_size(); ++index) {
     for (Entry* e = bucket(index); e != NULL; e = e->next()) {
       blk->do_code_blob(e->literal());
@@ -175,7 +131,7 @@
 }
 
 template<typename CB>
-int CodeRootSetTable::remove_if(CB& should_remove) {
+int G1CodeRootSetTable::remove_if(CB& should_remove) {
   int num_removed = 0;
   for (int index = 0; index < table_size(); ++index) {
     Entry* previous = NULL;
@@ -198,52 +154,52 @@
   delete _table;
 }
 
-CodeRootSetTable* G1CodeRootSet::load_acquire_table() {
-  return (CodeRootSetTable*) OrderAccess::load_ptr_acquire(&_table);
+G1CodeRootSetTable* G1CodeRootSet::load_acquire_table() {
+  return (G1CodeRootSetTable*) OrderAccess::load_ptr_acquire(&_table);
 }
 
 void G1CodeRootSet::allocate_small_table() {
-  CodeRootSetTable* temp = new CodeRootSetTable(SmallSize);
+  G1CodeRootSetTable* temp = new G1CodeRootSetTable(SmallSize);
 
   OrderAccess::release_store_ptr(&_table, temp);
 }
 
-void CodeRootSetTable::purge_list_append(CodeRootSetTable* table) {
+void G1CodeRootSetTable::purge_list_append(G1CodeRootSetTable* table) {
   for (;;) {
     table->_purge_next = _purge_list;
-    CodeRootSetTable* old = (CodeRootSetTable*) Atomic::cmpxchg_ptr(table, &_purge_list, table->_purge_next);
+    G1CodeRootSetTable* old = (G1CodeRootSetTable*) Atomic::cmpxchg_ptr(table, &_purge_list, table->_purge_next);
     if (old == table->_purge_next) {
       break;
     }
   }
 }
 
-void CodeRootSetTable::purge() {
-  CodeRootSetTable* table = _purge_list;
+void G1CodeRootSetTable::purge() {
+  G1CodeRootSetTable* table = _purge_list;
   _purge_list = NULL;
   while (table != NULL) {
-    CodeRootSetTable* to_purge = table;
+    G1CodeRootSetTable* to_purge = table;
     table = table->_purge_next;
     delete to_purge;
   }
 }
 
 void G1CodeRootSet::move_to_large() {
-  CodeRootSetTable* temp = new CodeRootSetTable(LargeSize);
+  G1CodeRootSetTable* temp = new G1CodeRootSetTable(LargeSize);
 
   _table->copy_to(temp);
 
-  CodeRootSetTable::purge_list_append(_table);
+  G1CodeRootSetTable::purge_list_append(_table);
 
   OrderAccess::release_store_ptr(&_table, temp);
 }
 
 void G1CodeRootSet::purge() {
-  CodeRootSetTable::purge();
+  G1CodeRootSetTable::purge();
 }
 
 size_t G1CodeRootSet::static_mem_size() {
-  return CodeRootSetTable::static_mem_size();
+  return G1CodeRootSetTable::static_mem_size();
 }
 
 void G1CodeRootSet::add(nmethod* method) {
@@ -278,7 +234,7 @@
 }
 
 bool G1CodeRootSet::contains(nmethod* method) {
-  CodeRootSetTable* table = load_acquire_table(); // contains() may be called outside of lock, so ensure mem sync.
+  G1CodeRootSetTable* table = load_acquire_table(); // contains() may be called outside of lock, so ensure mem sync.
   if (table != NULL) {
     return table->contains(method);
   }
@@ -348,67 +304,3 @@
     clear();
   }
 }
-
-#ifndef PRODUCT
-
-class G1CodeRootSetTest {
- public:
-  static void test() {
-    {
-      G1CodeRootSet set1;
-      assert(set1.is_empty(), "Code root set must be initially empty but is not.");
-
-      assert(G1CodeRootSet::static_mem_size() == sizeof(void*),
-             "The code root set's static memory usage is incorrect, " SIZE_FORMAT " bytes", G1CodeRootSet::static_mem_size());
-
-      set1.add((nmethod*)1);
-      assert(set1.length() == 1, "Added exactly one element, but set contains "
-             SIZE_FORMAT " elements", set1.length());
-
-      const size_t num_to_add = (size_t)G1CodeRootSet::Threshold + 1;
-
-      for (size_t i = 1; i <= num_to_add; i++) {
-        set1.add((nmethod*)1);
-      }
-      assert(set1.length() == 1,
-             "Duplicate detection should not have increased the set size but "
-             "is " SIZE_FORMAT, set1.length());
-
-      for (size_t i = 2; i <= num_to_add; i++) {
-        set1.add((nmethod*)(uintptr_t)(i));
-      }
-      assert(set1.length() == num_to_add,
-             "After adding in total " SIZE_FORMAT " distinct code roots, they "
-             "need to be in the set, but there are only " SIZE_FORMAT,
-             num_to_add, set1.length());
-
-      assert(CodeRootSetTable::_purge_list != NULL, "should have grown to large hashtable");
-
-      size_t num_popped = 0;
-      for (size_t i = 1; i <= num_to_add; i++) {
-        bool removed = set1.remove((nmethod*)i);
-        if (removed) {
-          num_popped += 1;
-        } else {
-          break;
-        }
-      }
-      assert(num_popped == num_to_add,
-             "Managed to pop " SIZE_FORMAT " code roots, but only " SIZE_FORMAT " "
-             "were added", num_popped, num_to_add);
-      assert(CodeRootSetTable::_purge_list != NULL, "should have grown to large hashtable");
-
-      G1CodeRootSet::purge();
-
-      assert(CodeRootSetTable::_purge_list == NULL, "should have purged old small tables");
-
-    }
-
-  }
-};
-
-void TestCodeCacheRemSet_test() {
-  G1CodeRootSetTest::test();
-}
-
-#endif
--- a/src/share/vm/gc/g1/g1CodeCacheRemSet.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1CodeCacheRemSet.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,7 +28,7 @@
 #include "memory/allocation.hpp"
 
 class CodeBlobClosure;
-class CodeRootSetTable;
+class G1CodeRootSetTable;
 class HeapRegion;
 class nmethod;
 
@@ -42,8 +42,8 @@
   const static size_t Threshold = 24;
   const static size_t LargeSize = 512;
 
-  CodeRootSetTable* _table;
-  CodeRootSetTable* load_acquire_table();
+  G1CodeRootSetTable* _table;
+  G1CodeRootSetTable* load_acquire_table();
 
   size_t _length;
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/vm/gc/g1/g1CodeRootSetTable.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#ifndef SHARE_VM_GC_G1_G1CODEROOTSETTABLE_HPP
+#define SHARE_VM_GC_G1_G1CODEROOTSETTABLE_HPP
+
+#include "utilities/hashtable.hpp"
+
+class nmethod;
+
+class G1CodeRootSetTable : public Hashtable<nmethod*, mtGC> {
+  friend class G1CodeRootSetTest;
+  typedef HashtableEntry<nmethod*, mtGC> Entry;
+
+  static G1CodeRootSetTable* volatile _purge_list;
+
+  G1CodeRootSetTable* _purge_next;
+
+  unsigned int compute_hash(nmethod* nm) {
+    uintptr_t hash = (uintptr_t)nm;
+    return hash ^ (hash >> 7); // code heap blocks are 128byte aligned
+  }
+
+  void remove_entry(Entry* e, Entry* previous);
+  Entry* new_entry(nmethod* nm);
+
+ public:
+  G1CodeRootSetTable(int size) : Hashtable<nmethod*, mtGC>(size, sizeof(Entry)), _purge_next(NULL) {}
+  ~G1CodeRootSetTable();
+
+  // Needs to be protected by locks
+  bool add(nmethod* nm);
+  bool remove(nmethod* nm);
+
+  // Can be called without locking
+  bool contains(nmethod* nm);
+
+  int entry_size() const { return BasicHashtable<mtGC>::entry_size(); }
+
+  void copy_to(G1CodeRootSetTable* new_table);
+  void nmethods_do(CodeBlobClosure* blk);
+
+  template<typename CB>
+  int remove_if(CB& should_remove);
+
+  static void purge_list_append(G1CodeRootSetTable* tbl);
+  static void purge();
+
+  static size_t static_mem_size() {
+    return sizeof(_purge_list);
+  }
+
+  size_t mem_size();
+};
+
+#endif /* SHARE_VM_GC_G1_G1CODEROOTSETTABLE_HPP */
--- a/src/share/vm/gc/g1/g1CollectedHeap.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1CollectedHeap.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1332,6 +1332,7 @@
                                                 workers()->active_workers(),
                                                 Threads::number_of_non_daemon_threads());
       workers()->update_active_workers(n_workers);
+      log_info(gc,task)("Using %u workers of %u to rebuild remembered set", n_workers, workers()->total_workers());
 
       ParRebuildRSTask rebuild_rs_task(this);
       workers()->run_task(&rebuild_rs_task);
@@ -3068,6 +3069,7 @@
                                                                   workers()->active_workers(),
                                                                   Threads::number_of_non_daemon_threads());
     workers()->update_active_workers(active_workers);
+    log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());
 
     TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
     TraceMemoryManagerStats tms(false /* fullGC */, gc_cause());
@@ -4513,6 +4515,7 @@
 #if defined(COMPILER2) || INCLUDE_JVMCI
   DerivedPointerTable::update_pointers();
 #endif
+  g1_policy()->print_age_table();
 }
 
 void G1CollectedHeap::record_obj_copy_mem_stats() {
--- a/src/share/vm/gc/g1/g1CollectionSet.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1CollectionSet.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -32,6 +32,7 @@
 #include "gc/g1/heapRegionSet.hpp"
 #include "logging/logStream.hpp"
 #include "utilities/debug.hpp"
+#include "utilities/quickSort.hpp"
 
 G1CollectorState* G1CollectionSet::collector_state() {
   return _g1->collector_state();
@@ -396,6 +397,16 @@
   return time_remaining_ms;
 }
 
+static int compare_region_idx(const uint a, const uint b) {
+  if (a > b) {
+    return 1;
+  } else if (a == b) {
+    return 0;
+  } else {
+    return -1;
+  }
+}
+
 void G1CollectionSet::finalize_old_part(double time_remaining_ms) {
   double non_young_start_time_sec = os::elapsedTime();
   double predicted_old_time_ms = 0.0;
@@ -493,6 +504,8 @@
 
   double non_young_end_time_sec = os::elapsedTime();
   phase_times()->record_non_young_cset_choice_time_ms((non_young_end_time_sec - non_young_start_time_sec) * 1000.0);
+
+  QuickSort::sort<uint>(_collection_set_regions, (int)_collection_set_cur_length, compare_region_idx, true);
 }
 
 #ifdef ASSERT
--- a/src/share/vm/gc/g1/g1ConcurrentMark.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1ConcurrentMark.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1035,6 +1035,8 @@
   // worker threads may currently exist and more may not be
   // available.
   active_workers = _parallel_workers->update_active_workers(active_workers);
+  log_info(gc, task)("Using %u workers of %u for marking", active_workers, _parallel_workers->total_workers());
+
   // Parallel task terminator is set in "set_concurrency_and_phase()"
   set_concurrency_and_phase(active_workers, true /* concurrent */);
 
@@ -1902,7 +1904,8 @@
     assert(_g1h->is_in_g1_reserved(finger), "invariant");
 
     HeapRegion* curr_region = _g1h->heap_region_containing(finger);
-
+    // Make sure that the reads below do not float before loading curr_region.
+    OrderAccess::loadload();
     // Above heap_region_containing may return NULL as we always scan claim
     // until the end of the heap. In this case, just jump to the next region.
     HeapWord* end = curr_region != NULL ? curr_region->end() : finger + HeapRegion::GrainWords;
--- a/src/share/vm/gc/g1/g1DefaultPolicy.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1DefaultPolicy.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -885,6 +885,15 @@
   return _young_gen_sizer.adaptive_young_list_length();
 }
 
+size_t G1DefaultPolicy::desired_survivor_size() const {
+  size_t const survivor_capacity = HeapRegion::GrainWords * _max_survivor_regions;
+  return (size_t)((((double)survivor_capacity) * TargetSurvivorRatio) / 100);
+}
+
+void G1DefaultPolicy::print_age_table() {
+  _survivors_age_table.print_age_table(_tenuring_threshold);
+}
+
 void G1DefaultPolicy::update_max_gc_locker_expansion() {
   uint expansion_region_num = 0;
   if (GCLockerEdenExpansionPercent > 0) {
@@ -908,8 +917,11 @@
   // smaller than 1.0) we'll get 1.
   _max_survivor_regions = (uint) ceil(max_survivor_regions_d);
 
-  _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
-      HeapRegion::GrainWords * _max_survivor_regions, _policy_counters);
+  _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(desired_survivor_size());
+  if (UsePerfData) {
+    _policy_counters->tenuring_threshold()->set_value(_tenuring_threshold);
+    _policy_counters->desired_survivor_size()->set_value(desired_survivor_size() * oopSize);
+  }
 }
 
 bool G1DefaultPolicy::force_initial_mark_if_outside_cycle(GCCause::Cause gc_cause) {
--- a/src/share/vm/gc/g1/g1DefaultPolicy.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1DefaultPolicy.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -360,6 +360,8 @@
 
   AgeTable _survivors_age_table;
 
+protected:
+  size_t desired_survivor_size() const;
 public:
   uint tenuring_threshold() const { return _tenuring_threshold; }
 
@@ -379,6 +381,8 @@
     _survivors_age_table.merge(age_table);
   }
 
+  void print_age_table();
+
   void update_max_gc_locker_expansion();
 
   void update_survivors_policy();
--- a/src/share/vm/gc/g1/g1MarkSweep.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1MarkSweep.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -132,9 +132,16 @@
   MarkingCodeBlobClosure follow_code_closure(&GenMarkSweep::follow_root_closure, !CodeBlobToOopClosure::FixRelocations);
   {
     G1RootProcessor root_processor(g1h, 1);
-    root_processor.process_strong_roots(&GenMarkSweep::follow_root_closure,
-                                        &GenMarkSweep::follow_cld_closure,
-                                        &follow_code_closure);
+    if (ClassUnloading) {
+      root_processor.process_strong_roots(&GenMarkSweep::follow_root_closure,
+                                          &GenMarkSweep::follow_cld_closure,
+                                          &follow_code_closure);
+    } else {
+      root_processor.process_all_roots_no_string_table(
+                                          &GenMarkSweep::follow_root_closure,
+                                          &GenMarkSweep::follow_cld_closure,
+                                          &follow_code_closure);
+    }
   }
 
   {
@@ -157,7 +164,7 @@
   // This is the point where the entire marking should have completed.
   assert(GenMarkSweep::_marking_stack.is_empty(), "Marking should have completed");
 
-  {
+  if (ClassUnloading) {
     GCTraceTime(Debug, gc, phases) trace("Class Unloading", gc_timer());
 
     // Unload classes and purge the SystemDictionary.
--- a/src/share/vm/gc/g1/g1Policy.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1Policy.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -181,6 +181,9 @@
   virtual void note_stop_adding_survivor_regions() = 0;
 
   virtual void record_age_table(AgeTable* age_table) = 0;
+  virtual void print_age_table() = 0;
+protected:
+  virtual size_t desired_survivor_size() const = 0;
 };
 
 #endif // SHARE_VM_GC_G1_G1POLICY_HPP
--- a/src/share/vm/gc/g1/g1Predictions.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,98 +0,0 @@
-/*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-#include "gc/g1/g1Predictions.hpp"
-
-#ifndef PRODUCT
-
-void G1Predictions::test() {
-  double const epsilon = 1e-6;
-  {
-    // Some basic formula tests with confidence = 0.0
-    G1Predictions predictor(0.0);
-    TruncatedSeq s;
-
-    double p0 = predictor.get_new_prediction(&s);
-    assert(p0 < epsilon, "Initial prediction of empty sequence must be 0.0 but is %f", p0);
-
-    s.add(5.0);
-    double p1 = predictor.get_new_prediction(&s);
-    assert(fabs(p1 - 5.0) < epsilon, "Prediction should be 5.0 but is %f", p1);
-    for (int i = 0; i < 40; i++) {
-      s.add(5.0);
-    }
-    double p2 = predictor.get_new_prediction(&s);
-    assert(fabs(p2 - 5.0) < epsilon, "Prediction should be 5.0 but is %f", p1);
-  }
-
-  {
-    // The following tests checks that the initial predictions are based on the
-    // average of the sequence and not on the stddev (which is 0).
-    G1Predictions predictor(0.5);
-    TruncatedSeq s;
-
-    s.add(1.0);
-    double p1 = predictor.get_new_prediction(&s);
-    assert(p1 > 1.0, "First prediction must be larger than average, but avg is %f and prediction %f", s.davg(), p1);
-    s.add(1.0);
-    double p2 = predictor.get_new_prediction(&s);
-    assert(p2 < p1, "First prediction must be larger than second, but they are %f %f", p1, p2);
-    s.add(1.0);
-    double p3 = predictor.get_new_prediction(&s);
-    assert(p3 < p2, "Second prediction must be larger than third, but they are %f %f", p2, p3);
-    s.add(1.0);
-    s.add(1.0); // Five elements are now in the sequence.
-    double p5 = predictor.get_new_prediction(&s);
-    assert(p5 < p3, "Fifth prediction must be smaller than third, but they are %f %f", p3, p5);
-    assert(fabs(p5 - 1.0) < epsilon, "Prediction must be 1.0+epsilon, but is %f", p5);
-  }
-
-  {
-    // The following tests checks that initially prediction based on the average is
-    // used, that gets overridden by the stddev prediction at the end.
-    G1Predictions predictor(0.5);
-    TruncatedSeq s;
-
-    s.add(0.5);
-    double p1 = predictor.get_new_prediction(&s);
-    assert(p1 > 0.5, "First prediction must be larger than average, but avg is %f and prediction %f", s.davg(), p1);
-    s.add(0.2);
-    double p2 = predictor.get_new_prediction(&s);
-    assert(p2 < p1, "First prediction must be larger than second, but they are %f %f", p1, p2);
-    s.add(0.5);
-    double p3 = predictor.get_new_prediction(&s);
-    assert(p3 < p2, "Second prediction must be larger than third, but they are %f %f", p2, p3);
-    s.add(0.2);
-    s.add(2.0);
-    double p5 = predictor.get_new_prediction(&s);
-    assert(p5 > p3, "Fifth prediction must be bigger than third, but they are %f %f", p3, p5);
-  }
-}
-
-void TestPredictions_test() {
-  G1Predictions::test();
-}
-
-#endif
--- a/src/share/vm/gc/g1/g1Predictions.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1Predictions.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -57,10 +57,6 @@
   double get_new_prediction(TruncatedSeq const* seq) const {
     return seq->davg() + _sigma * stddev_estimate(seq);
   }
-
-#ifndef PRODUCT
-  static void test();
-#endif
 };
 
 #endif // SHARE_VM_GC_G1_G1PREDICTIONS_HPP
--- a/src/share/vm/gc/g1/g1RootProcessor.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1RootProcessor.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -83,6 +83,7 @@
   }
 
   process_vm_roots(closures, phase_times, worker_i);
+  process_string_table_roots(closures, phase_times, worker_i);
 
   {
     // Now the CM ref_processor roots.
@@ -191,19 +192,34 @@
 
 void G1RootProcessor::process_all_roots(OopClosure* oops,
                                         CLDClosure* clds,
-                                        CodeBlobClosure* blobs) {
+                                        CodeBlobClosure* blobs,
+                                        bool process_string_table) {
   AllRootsClosures closures(oops, clds);
 
   process_java_roots(&closures, NULL, 0);
   process_vm_roots(&closures, NULL, 0);
 
-  if (!_process_strong_tasks.is_task_claimed(G1RP_PS_CodeCache_oops_do)) {
-    CodeCache::blobs_do(blobs);
+  if (process_string_table) {
+    process_string_table_roots(&closures, NULL, 0);
   }
+  process_code_cache_roots(blobs, NULL, 0);
 
   _process_strong_tasks.all_tasks_completed(n_workers());
 }
 
+void G1RootProcessor::process_all_roots(OopClosure* oops,
+                                        CLDClosure* clds,
+                                        CodeBlobClosure* blobs) {
+  process_all_roots(oops, clds, blobs, true);
+}
+
+void G1RootProcessor::process_all_roots_no_string_table(OopClosure* oops,
+                                                        CLDClosure* clds,
+                                                        CodeBlobClosure* blobs) {
+  assert(!ClassUnloading, "Should only be used when class unloading is disabled");
+  process_all_roots(oops, clds, blobs, false);
+}
+
 void G1RootProcessor::process_java_roots(G1RootClosures* closures,
                                          G1GCPhaseTimes* phase_times,
                                          uint worker_i) {
@@ -280,14 +296,23 @@
       SystemDictionary::roots_oops_do(strong_roots, weak_roots);
     }
   }
+}
 
-  {
-    G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::StringTableRoots, worker_i);
-    // All threads execute the following. A specific chunk of buckets
-    // from the StringTable are the individual tasks.
-    if (weak_roots != NULL) {
-      StringTable::possibly_parallel_oops_do(weak_roots);
-    }
+void G1RootProcessor::process_string_table_roots(G1RootClosures* closures,
+                                                 G1GCPhaseTimes* phase_times,
+                                                 uint worker_i) {
+  assert(closures->weak_oops() != NULL, "Should only be called when all roots are processed");
+  G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::StringTableRoots, worker_i);
+  // All threads execute the following. A specific chunk of buckets
+  // from the StringTable are the individual tasks.
+  StringTable::possibly_parallel_oops_do(closures->weak_oops());
+}
+
+void G1RootProcessor::process_code_cache_roots(CodeBlobClosure* code_closure,
+                                               G1GCPhaseTimes* phase_times,
+                                               uint worker_i) {
+  if (!_process_strong_tasks.is_task_claimed(G1RP_PS_CodeCache_oops_do)) {
+    CodeCache::blobs_do(code_closure);
   }
 }
 
--- a/src/share/vm/gc/g1/g1RootProcessor.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/g1RootProcessor.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -73,6 +73,11 @@
   void worker_has_discovered_all_strong_classes();
   void wait_until_all_strong_classes_discovered();
 
+  void process_all_roots(OopClosure* oops,
+                         CLDClosure* clds,
+                         CodeBlobClosure* blobs,
+                         bool process_string_table);
+
   void process_java_roots(G1RootClosures* closures,
                           G1GCPhaseTimes* phase_times,
                           uint worker_i);
@@ -81,6 +86,14 @@
                         G1GCPhaseTimes* phase_times,
                         uint worker_i);
 
+  void process_string_table_roots(G1RootClosures* closures,
+                                  G1GCPhaseTimes* phase_times,
+                                  uint worker_i);
+
+  void process_code_cache_roots(CodeBlobClosure* code_closure,
+                                G1GCPhaseTimes* phase_times,
+                                uint worker_i);
+
 public:
   G1RootProcessor(G1CollectedHeap* g1h, uint n_workers);
 
@@ -99,6 +112,13 @@
                          CLDClosure* clds,
                          CodeBlobClosure* blobs);
 
+  // Apply oops, clds and blobs to strongly and weakly reachable roots in the system,
+  // the only thing different from process_all_roots is that we skip the string table
+  // to avoid keeping every string live when doing class unloading.
+  void process_all_roots_no_string_table(OopClosure* oops,
+                                         CLDClosure* clds,
+                                         CodeBlobClosure* blobs);
+
   // Number of worker threads used by the root processor.
   uint n_workers() const;
 };
--- a/src/share/vm/gc/g1/heapRegionManager.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/g1/heapRegionManager.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -123,6 +123,7 @@
   for (uint i = start; i < start + num_regions; i++) {
     if (_regions.get_by_index(i) == NULL) {
       HeapRegion* new_hr = new_heap_region(i);
+      OrderAccess::storestore();
       _regions.set_by_index(i, new_hr);
       _allocated_heapregions_length = MAX2(_allocated_heapregions_length, i + 1);
     }
--- a/src/share/vm/gc/parallel/psAdaptiveSizePolicy.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/parallel/psAdaptiveSizePolicy.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1133,18 +1133,3 @@
 
   return false;
 }
-
-#ifndef PRODUCT
-
-void TestOldFreeSpaceCalculation_test() {
-  assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(100, 20) == 25, "Calculation of free memory failed");
-  assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(100, 50) == 100, "Calculation of free memory failed");
-  assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(100, 60) == 150, "Calculation of free memory failed");
-  assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(100, 75) == 300, "Calculation of free memory failed");
-  assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(400, 20) == 100, "Calculation of free memory failed");
-  assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(400, 50) == 400, "Calculation of free memory failed");
-  assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(400, 60) == 600, "Calculation of free memory failed");
-  assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(400, 75) == 1200, "Calculation of free memory failed");
-}
-
-#endif /* !PRODUCT */
--- a/src/share/vm/gc/serial/defNewGeneration.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/serial/defNewGeneration.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -564,9 +564,18 @@
 
 void DefNewGeneration::adjust_desired_tenuring_threshold() {
   // Set the desired survivor size to half the real survivor space
-  GCPolicyCounters* gc_counters = GenCollectedHeap::heap()->gen_policy()->counters();
-  _tenuring_threshold =
-    age_table()->compute_tenuring_threshold(to()->capacity()/HeapWordSize, gc_counters);
+  size_t const survivor_capacity = to()->capacity() / HeapWordSize;
+  size_t const desired_survivor_size = (size_t)((((double)survivor_capacity) * TargetSurvivorRatio) / 100);
+
+  _tenuring_threshold = age_table()->compute_tenuring_threshold(desired_survivor_size);
+
+  if (UsePerfData) {
+    GCPolicyCounters* gc_counters = GenCollectedHeap::heap()->gen_policy()->counters();
+    gc_counters->tenuring_threshold()->set_value(_tenuring_threshold);
+    gc_counters->desired_survivor_size()->set_value(desired_survivor_size * oopSize);
+  }
+
+  age_table()->print_age_table(_tenuring_threshold);
 }
 
 void DefNewGeneration::collect(bool   full,
--- a/src/share/vm/gc/shared/ageTable.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/shared/ageTable.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -27,7 +27,6 @@
 #include "gc/shared/ageTableTracer.hpp"
 #include "gc/shared/collectedHeap.hpp"
 #include "gc/shared/collectorPolicy.hpp"
-#include "gc/shared/gcPolicyCounters.hpp"
 #include "memory/resourceArea.hpp"
 #include "logging/log.hpp"
 #include "oops/oop.inline.hpp"
@@ -75,8 +74,7 @@
   }
 }
 
-uint AgeTable::compute_tenuring_threshold(size_t survivor_capacity, GCPolicyCounters* gc_counters) {
-  size_t desired_survivor_size = (size_t)((((double) survivor_capacity)*TargetSurvivorRatio)/100);
+uint AgeTable::compute_tenuring_threshold(size_t desired_survivor_size) {
   uint result;
 
   if (AlwaysTenure || NeverTenure) {
@@ -99,9 +97,16 @@
 
 
   log_debug(gc, age)("Desired survivor size " SIZE_FORMAT " bytes, new threshold " UINTX_FORMAT " (max threshold " UINTX_FORMAT ")",
-                     desired_survivor_size*oopSize, (uintx) result, MaxTenuringThreshold);
+                     desired_survivor_size * oopSize, (uintx) result, MaxTenuringThreshold);
 
+  return result;
+}
+
+void AgeTable::print_age_table(uint tenuring_threshold) {
   if (log_is_enabled(Trace, gc, age) || UsePerfData || AgeTableTracer::is_tenuring_distribution_event_enabled()) {
+    log_trace(gc, age)("Age table with threshold %u (max threshold " UINTX_FORMAT ")",
+                       tenuring_threshold, MaxTenuringThreshold);
+
     size_t total = 0;
     uint age = 1;
     while (age < table_size) {
@@ -109,20 +114,14 @@
       total += wordSize;
       if (wordSize > 0) {
         log_trace(gc, age)("- age %3u: " SIZE_FORMAT_W(10) " bytes, " SIZE_FORMAT_W(10) " total",
-                            age, wordSize*oopSize, total*oopSize);
+                            age, wordSize * oopSize, total * oopSize);
       }
-      AgeTableTracer::send_tenuring_distribution_event(age, wordSize*oopSize);
+      AgeTableTracer::send_tenuring_distribution_event(age, wordSize * oopSize);
       if (UsePerfData) {
-        _perf_sizes[age]->set_value(wordSize*oopSize);
+        _perf_sizes[age]->set_value(wordSize * oopSize);
       }
       age++;
     }
-    if (UsePerfData) {
-      gc_counters->tenuring_threshold()->set_value(result);
-      gc_counters->desired_survivor_size()->set_value(
-        desired_survivor_size*oopSize);
-    }
   }
+}
 
-  return result;
-}
--- a/src/share/vm/gc/shared/ageTable.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/shared/ageTable.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -29,8 +29,6 @@
 #include "oops/oop.hpp"
 #include "runtime/perfData.hpp"
 
-class GCPolicyCounters;
-
 /* Copyright (c) 1992, 2016, Oracle and/or its affiliates, and Stanford University.
    See the LICENSE file for license information. */
 
@@ -67,10 +65,12 @@
   // for parallel young generation gc.
   void merge(AgeTable* subTable);
 
-  // calculate new tenuring threshold based on age information
-  uint compute_tenuring_threshold(size_t survivor_capacity, GCPolicyCounters* gc_counters);
+  // Calculate new tenuring threshold based on age information.
+  uint compute_tenuring_threshold(size_t desired_survivor_size);
+  void print_age_table(uint tenuring_threshold);
 
  private:
+
   PerfVariable* _perf_sizes[table_size];
 };
 
--- a/src/share/vm/gc/shared/gcTrace.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/shared/gcTrace.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -185,8 +185,10 @@
 }
 
 #if INCLUDE_ALL_GCS
-void G1MMUTracer::report_mmu(double timeSlice, double gcTime, double maxTime) {
-  send_g1_mmu_event(timeSlice, gcTime, maxTime);
+void G1MMUTracer::report_mmu(double time_slice_sec, double gc_time_sec, double max_time_sec) {
+  send_g1_mmu_event(time_slice_sec * MILLIUNITS,
+                    gc_time_sec * MILLIUNITS,
+                    max_time_sec * MILLIUNITS);
 }
 
 void G1NewTracer::report_yc_type(G1YCType type) {
--- a/src/share/vm/gc/shared/gcTrace.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/shared/gcTrace.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -235,10 +235,10 @@
 
 #if INCLUDE_ALL_GCS
 class G1MMUTracer : public AllStatic {
-  static void send_g1_mmu_event(double timeSlice, double gcTime, double maxTime);
+  static void send_g1_mmu_event(double time_slice_ms, double gc_time_ms, double max_time_ms);
 
  public:
-  static void report_mmu(double timeSlice, double gcTime, double maxTime);
+  static void report_mmu(double time_slice_sec, double gc_time_sec, double max_time_sec);
 };
 
 class G1NewTracer : public YoungGCTracer {
--- a/src/share/vm/gc/shared/gcTraceSend.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/shared/gcTraceSend.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -200,13 +200,13 @@
   }
 }
 
-void G1MMUTracer::send_g1_mmu_event(double timeSlice, double gcTime, double maxTime) {
+void G1MMUTracer::send_g1_mmu_event(double time_slice_ms, double gc_time_ms, double max_time_ms) {
   EventG1MMU e;
   if (e.should_commit()) {
     e.set_gcId(GCId::current());
-    e.set_timeSlice(timeSlice);
-    e.set_gcTime(gcTime);
-    e.set_maxGcTime(maxTime);
+    e.set_timeSlice(time_slice_ms);
+    e.set_gcTime(gc_time_ms);
+    e.set_pauseTarget(max_time_ms);
     e.commit();
   }
 }
@@ -281,10 +281,10 @@
     evt.set_targetOccupancy(target_occupancy);
     evt.set_thresholdPercentage(target_occupancy > 0 ? ((double)threshold / target_occupancy) : 0.0);
     evt.set_currentOccupancy(current_occupancy);
-    evt.set_lastAllocationSize(last_allocation_size);
-    evt.set_lastAllocationDuration(last_allocation_duration);
-    evt.set_lastAllocationRate(last_allocation_duration != 0.0 ? last_allocation_size / last_allocation_duration : 0.0);
-    evt.set_lastMarkingLength(last_marking_length);
+    evt.set_recentMutatorAllocationSize(last_allocation_size);
+    evt.set_recentMutatorDuration(last_allocation_duration * MILLIUNITS);
+    evt.set_recentAllocationRate(last_allocation_duration != 0.0 ? last_allocation_size / last_allocation_duration : 0.0);
+    evt.set_lastMarkingDuration(last_marking_length * MILLIUNITS);
     evt.commit();
   }
 }
@@ -301,11 +301,11 @@
     evt.set_gcId(GCId::current());
     evt.set_threshold(threshold);
     evt.set_thresholdPercentage(internal_target_occupancy > 0 ? ((double)threshold / internal_target_occupancy) : 0.0);
-    evt.set_internalTargetOccupancy(internal_target_occupancy);
+    evt.set_ihopTargetOccupancy(internal_target_occupancy);
     evt.set_currentOccupancy(current_occupancy);
     evt.set_additionalBufferSize(additional_buffer_size);
     evt.set_predictedAllocationRate(predicted_allocation_rate);
-    evt.set_predictedMarkingLength(predicted_marking_length);
+    evt.set_predictedMarkingDuration(predicted_marking_length * MILLIUNITS);
     evt.set_predictionActive(prediction_active);
     evt.commit();
   }
--- a/src/share/vm/gc/shared/memset_with_concurrent_readers.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-
-#include <string.h>
-#include "gc/shared/memset_with_concurrent_readers.hpp"
-#include "utilities/debug.hpp"
-#include "utilities/globalDefinitions.hpp"
-#include "utilities/macros.hpp"
-#include "utilities/ostream.hpp"
-
-#if INCLUDE_ALL_GCS
-
-// Unit test
-#ifndef PRODUCT
-
-static unsigned line_byte(const char* line, size_t i) {
-  return unsigned(line[i]) & 0xFF;
-}
-
-// Verify memset_with_concurrent_readers mimics memset.
-// We don't attempt to verify the concurrent reader case.
-void test_memset_with_concurrent_readers() {
-  const size_t chunk_size = 8 * BytesPerWord;
-  const unsigned chunk_count = 4;
-  const size_t block_size = (chunk_count + 4) * chunk_size;
-  char block[block_size];
-  char clear_block[block_size];
-  char set_block[block_size];
-
-  // block format:
-  // 0: unused leading chunk
-  // 1: chunk written from start index to end of chunk
-  // ... nchunks fully written chunks
-  // N: chunk written from start of chunk to end index
-  // N+1: unused trailing chunk
-
-  const int clear_value = 0;
-  const int set_value = 0xAC;
-
-  memset(clear_block, clear_value, block_size);
-  memset(set_block, set_value, block_size);
-
-  for (unsigned nchunks = 0; nchunks <= chunk_count; ++nchunks) {
-    for (size_t start = 1; start <= chunk_size; ++start) {
-      for (size_t end = 0; end <= chunk_size; ++end) {
-        size_t set_start = chunk_size + start;
-        size_t set_end = (2 + nchunks) * chunk_size + end;
-        size_t set_size = set_end - set_start;
-
-        memset(block, clear_value, block_size);
-        memset_with_concurrent_readers(&block[set_start], set_value, set_size);
-        bool head_clear = !memcmp(clear_block, block, set_start);
-        bool middle_set = !memcmp(set_block, block + set_start, set_size);
-        bool tail_clear = !memcmp(clear_block, block + set_end, block_size - set_end);
-        if (!(head_clear && middle_set && tail_clear)) {
-          tty->print_cr("*** memset_with_concurrent_readers failed: "
-                        "set start " SIZE_FORMAT ", set end " SIZE_FORMAT,
-                        set_start, set_end);
-          for (unsigned chunk = 0; chunk < (block_size / chunk_size); ++chunk) {
-            for (unsigned line = 0; line < (chunk_size / BytesPerWord); ++line) {
-              const char* lp = &block[chunk * chunk_size + line * BytesPerWord];
-              tty->print_cr("%d,%d: %2x %2x  %2x %2x  %2x %2x  %2x %2x",
-                            chunk, line,
-                            line_byte(lp, 0), line_byte(lp, 1),
-                            line_byte(lp, 2), line_byte(lp, 3),
-                            line_byte(lp, 4), line_byte(lp, 5),
-                            line_byte(lp, 6), line_byte(lp, 7));
-            }
-          }
-          assert(head_clear, "leading byte not clear");
-          assert(middle_set, "memset byte not set");
-          assert(tail_clear, "trailing bye not clear");
-        }
-      }
-    }
-  }
-}
-
-#endif // end unit test
-
-#endif // INCLUDE_ALL_GCS
--- a/src/share/vm/gc/shared/workgroup.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/gc/shared/workgroup.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -162,7 +162,7 @@
     _active_workers = MIN2(v, _total_workers);
     add_workers(false /* exit_on_failure */);
     assert(v != 0, "Trying to set active workers to 0");
-    log_info(gc, task)("GC Workers: using %d out of %d", _active_workers, _total_workers);
+    log_trace(gc, task)("%s: using %d out of %d workers", name(), _active_workers, _total_workers);
     return _active_workers;
   }
 
--- a/src/share/vm/interpreter/interpreterRuntime.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/interpreter/interpreterRuntime.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -576,27 +576,39 @@
   // compute auxiliary field attributes
   TosState state  = as_TosState(info.field_type());
 
-  // Put instructions on final fields are not resolved. This is required so we throw
-  // exceptions at the correct place (when the instruction is actually invoked).
+  // Resolution of put instructions on final fields is delayed. That is required so that
+  // exceptions are thrown at the correct place (when the instruction is actually invoked).
   // If we do not resolve an instruction in the current pass, leaving the put_code
   // set to zero will cause the next put instruction to the same field to reresolve.
+
+  // Resolution of put instructions to final instance fields with invalid updates (i.e.,
+  // to final instance fields with updates originating from a method different than <init>)
+  // is inhibited. A putfield instruction targeting an instance final field must throw
+  // an IllegalAccessError if the instruction is not in an instance
+  // initializer method <init>. If resolution were not inhibited, a putfield
+  // in an initializer method could be resolved in the initializer. Subsequent
+  // putfield instructions to the same field would then use cached information.
+  // As a result, those instructions would not pass through the VM. That is,
+  // checks in resolve_field_access() would not be executed for those instructions
+  // and the required IllegalAccessError would not be thrown.
   //
   // Also, we need to delay resolving getstatic and putstatic instructions until the
   // class is initialized.  This is required so that access to the static
   // field will call the initialization function every time until the class
   // is completely initialized ala. in 2.17.5 in JVM Specification.
   InstanceKlass* klass = InstanceKlass::cast(info.field_holder());
-  bool uninitialized_static = ((bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic) &&
-                               !klass->is_initialized());
-
-  Bytecodes::Code put_code = (Bytecodes::Code)0;
-  if (is_put && !info.access_flags().is_final() && !uninitialized_static) {
-    put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
-  }
+  bool uninitialized_static = is_static && !klass->is_initialized();
+  bool has_initialized_final_update = info.field_holder()->major_version() >= 53 &&
+                                      info.has_initialized_final_update();
+  assert(!(has_initialized_final_update && !info.access_flags().is_final()), "Fields with initialized final updates must be final");
 
   Bytecodes::Code get_code = (Bytecodes::Code)0;
+  Bytecodes::Code put_code = (Bytecodes::Code)0;
   if (!uninitialized_static) {
     get_code = ((is_static) ? Bytecodes::_getstatic : Bytecodes::_getfield);
+    if ((is_put && !has_initialized_final_update) || !info.access_flags().is_final()) {
+      put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
+    }
   }
 
   cp_cache_entry->set_field(
--- a/src/share/vm/jvmci/jvmciCompilerToVM.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/jvmci/jvmciCompilerToVM.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -768,6 +768,11 @@
   Symbol* h_name      = method->name();
   Symbol* h_signature = method->signature();
 
+  if (MethodHandles::is_signature_polymorphic_method(method())) {
+      // Signature polymorphic methods are already resolved, JVMCI just returns NULL in this case.
+      return NULL;
+  }
+
   LinkInfo link_info(h_resolved, h_name, h_signature, caller_klass);
   methodHandle m;
   // Only do exact lookup if receiver klass has been linked.  Otherwise,
@@ -782,7 +787,7 @@
   }
 
   if (m.is_null()) {
-    // Return NULL only if there was a problem with lookup (uninitialized class, etc.)
+    // Return NULL if there was a problem with lookup (uninitialized class, etc.)
     return NULL;
   }
 
--- a/src/share/vm/jvmci/jvmciRuntime.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/jvmci/jvmciRuntime.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -313,13 +313,18 @@
     // normal bytecode execution.
     thread->clear_exception_oop_and_pc();
 
-    continuation = SharedRuntime::compute_compiled_exc_handler(cm, pc, exception, false, false);
+    bool recursive_exception = false;
+    continuation = SharedRuntime::compute_compiled_exc_handler(cm, pc, exception, false, false, recursive_exception);
     // If an exception was thrown during exception dispatch, the exception oop may have changed
     thread->set_exception_oop(exception());
     thread->set_exception_pc(pc);
 
     // the exception cache is used only by non-implicit exceptions
-    if (continuation != NULL && !SharedRuntime::deopt_blob()->contains(continuation)) {
+    // Update the exception cache only when there didn't happen
+    // another exception during the computation of the compiled
+    // exception handler. Checking for exception oop equality is not
+    // sufficient because some exceptions are pre-allocated and reused.
+    if (continuation != NULL && !recursive_exception && !SharedRuntime::deopt_blob()->contains(continuation)) {
       cm->add_handler_for_exception_and_pc(exception, pc, continuation);
     }
   }
--- a/src/share/vm/logging/log.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/logging/log.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1161,7 +1161,7 @@
 
   // Attempt to log to a directory (existing log not a regular file)
   create_directory(target_name);
-  LogFileOutput bad_file("tmplogdir");
+  LogFileOutput bad_file("file=tmplogdir");
   assert(bad_file.initialize("", &ss) == false, "file was initialized "
          "when there was an existing directory with the same name");
   assert(strstr(ss.as_string(), "tmplogdir is not a regular file") != NULL,
--- a/src/share/vm/logging/logConfiguration.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/logging/logConfiguration.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -44,6 +44,9 @@
 LogConfiguration::UpdateListenerFunction* LogConfiguration::_listener_callbacks = NULL;
 size_t      LogConfiguration::_n_listener_callbacks = 0;
 
+// LogFileOutput is the default type of output, its type prefix should be used if no type was specified
+static const char* implicit_output_prefix = LogFileOutput::Prefix;
+
 // Stack object to take the lock for configuring the logging.
 // Should only be held during the critical parts of the configuration
 // (when calling configure_output or reading/modifying the outputs array).
@@ -107,6 +110,55 @@
   FREE_C_HEAP_ARRAY(LogOutput*, _outputs);
 }
 
+// Normalizes the given LogOutput name to type=name form.
+// For example, foo, "foo", file="foo", will all be normalized to file=foo (no quotes, prefixed).
+static bool normalize_output_name(const char* full_name, char* buffer, size_t len, outputStream* errstream) {
+  const char* start_quote = strchr(full_name, '"');
+  const char* equals = strchr(full_name, '=');
+  const bool quoted = start_quote != NULL;
+  const bool is_stdout_or_stderr = (strcmp(full_name, "stdout") == 0 || strcmp(full_name, "stderr") == 0);
+
+  // ignore equals sign within quotes
+  if (quoted && equals > start_quote) {
+    equals = NULL;
+  }
+
+  const char* prefix = "";
+  size_t prefix_len = 0;
+  const char* name = full_name;
+  if (equals != NULL) {
+    // split on equals sign
+    name = equals + 1;
+    prefix = full_name;
+    prefix_len = equals - full_name + 1;
+  } else if (!is_stdout_or_stderr) {
+    prefix = implicit_output_prefix;
+    prefix_len = strlen(prefix);
+  }
+  size_t name_len = strlen(name);
+
+  if (quoted) {
+    const char* end_quote = strchr(start_quote + 1, '"');
+    if (end_quote == NULL) {
+      errstream->print_cr("Output name has opening quote but is missing a terminating quote.");
+      return false;
+    }
+    if (start_quote != name || end_quote[1] != '\0') {
+      errstream->print_cr("Output name can not be partially quoted."
+                          " Either surround the whole name with quotation marks,"
+                          " or do not use quotation marks at all.");
+      return false;
+    }
+    // strip start and end quote
+    name++;
+    name_len -= 2;
+  }
+
+  int ret = jio_snprintf(buffer, len, "%.*s%.*s", prefix_len, prefix, name_len, name);
+  assert(ret > 0, "buffer issue");
+  return true;
+}
+
 size_t LogConfiguration::find_output(const char* name) {
   for (size_t i = 0; i < _n_outputs; i++) {
     if (strcmp(_outputs[i]->name(), name) == 0) {
@@ -116,39 +168,14 @@
   return SIZE_MAX;
 }
 
-LogOutput* LogConfiguration::new_output(char* name, const char* options, outputStream* errstream) {
-  const char* type;
-  char* equals_pos = strchr(name, '=');
-  if (equals_pos == NULL) {
-    type = "file";
-  } else {
-    *equals_pos = '\0';
-    type = name;
-    name = equals_pos + 1;
-  }
-
-  // Check if name is quoted, and if so, strip the quotes
-  char* quote = strchr(name, '"');
-  if (quote != NULL) {
-    char* end_quote = strchr(name + 1, '"');
-    if (end_quote == NULL) {
-      errstream->print_cr("Output name has opening quote but is missing a terminating quote.");
-      return NULL;
-    } else if (quote != name || end_quote[1] != '\0') {
-      errstream->print_cr("Output name can not be partially quoted."
-                          " Either surround the whole name with quotation marks,"
-                          " or do not use quotation marks at all.");
-      return NULL;
-    }
-    name++;
-    *end_quote = '\0';
-  }
-
+LogOutput* LogConfiguration::new_output(const char* name,
+                                        const char* options,
+                                        outputStream* errstream) {
   LogOutput* output;
-  if (strcmp(type, "file") == 0) {
+  if (strncmp(name, LogFileOutput::Prefix, strlen(LogFileOutput::Prefix)) == 0) {
     output = new LogFileOutput(name);
   } else {
-    errstream->print_cr("Unsupported log output type.");
+    errstream->print_cr("Unsupported log output type: %s", name);
     return NULL;
   }
 
@@ -358,6 +385,7 @@
                                            const char* decoratorstr,
                                            const char* output_options,
                                            outputStream* errstream) {
+  assert(errstream != NULL, "errstream can not be NULL");
   if (outputstr == NULL || strlen(outputstr) == 0) {
     outputstr = "stdout";
   }
@@ -374,25 +402,35 @@
 
   ConfigurationLock cl;
   size_t idx;
-  if (outputstr[0] == '#') {
-    int ret = sscanf(outputstr+1, SIZE_FORMAT, &idx);
+  if (outputstr[0] == '#') { // Output specified using index
+    int ret = sscanf(outputstr + 1, SIZE_FORMAT, &idx);
     if (ret != 1 || idx >= _n_outputs) {
       errstream->print_cr("Invalid output index '%s'", outputstr);
       return false;
     }
-  } else {
-    idx = find_output(outputstr);
+  } else { // Output specified using name
+    // Normalize the name, stripping quotes and ensures it includes type prefix
+    size_t len = strlen(outputstr) + strlen(implicit_output_prefix) + 1;
+    char* normalized = NEW_C_HEAP_ARRAY(char, len, mtLogging);
+    if (!normalize_output_name(outputstr, normalized, len, errstream)) {
+      return false;
+    }
+
+    idx = find_output(normalized);
     if (idx == SIZE_MAX) {
-      char* tmp = os::strdup_check_oom(outputstr, mtLogging);
-      LogOutput* output = new_output(tmp, output_options, errstream);
-      os::free(tmp);
-      if (output == NULL) {
-        return false;
+      // Attempt to create and add the output
+      LogOutput* output = new_output(normalized, output_options, errstream);
+      if (output != NULL) {
+        idx = add_output(output);
       }
-      idx = add_output(output);
     } else if (output_options != NULL && strlen(output_options) > 0) {
       errstream->print_cr("Output options for existing outputs are ignored.");
     }
+
+    FREE_C_HEAP_ARRAY(char, normalized);
+    if (idx == SIZE_MAX) {
+      return false;
+    }
   }
   configure_output(idx, expr, decorators);
   notify_update_listeners();
--- a/src/share/vm/logging/logConfiguration.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/logging/logConfiguration.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -59,7 +59,7 @@
   static size_t                     _n_listener_callbacks;
 
   // Create a new output. Returns NULL if failed.
-  static LogOutput* new_output(char* name, const char* options, outputStream* errstream);
+  static LogOutput* new_output(const char* name, const char* options, outputStream* errstream);
 
   // Add an output to the list of configured outputs. Returns the assigned index.
   static size_t add_output(LogOutput* out);
--- a/src/share/vm/logging/logFileOutput.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/logging/logFileOutput.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -31,6 +31,7 @@
 #include "utilities/globalDefinitions.hpp"
 #include "utilities/defaultStream.hpp"
 
+const char* LogFileOutput::Prefix = "file=";
 const char* LogFileOutput::FileOpenMode = "a";
 const char* LogFileOutput::PidFilenamePlaceholder = "%p";
 const char* LogFileOutput::TimestampFilenamePlaceholder = "%t";
@@ -45,7 +46,8 @@
       _file_name(NULL), _archive_name(NULL), _archive_name_len(0),
       _rotate_size(DefaultFileSize), _file_count(DefaultFileCount),
       _current_size(0), _current_file(0), _rotation_semaphore(1) {
-  _file_name = make_file_name(name, _pid_str, _vm_start_time_str);
+  assert(strstr(name, Prefix) == name, "invalid output name '%s': missing prefix: %s", name, Prefix);
+  _file_name = make_file_name(name + strlen(Prefix), _pid_str, _vm_start_time_str);
 }
 
 void LogFileOutput::set_file_name_parameters(jlong vm_start_time) {
--- a/src/share/vm/logging/logFileOutput.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/logging/logFileOutput.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -91,6 +91,7 @@
     return _name;
   }
 
+  static const char* Prefix;
   static void set_file_name_parameters(jlong start_time);
 };
 
--- a/src/share/vm/logging/logTagLevelExpression.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/logging/logTagLevelExpression.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -164,7 +164,14 @@
         success = false;
         break;
       }
-      add_tag(tag);
+      if (!add_tag(tag)) {
+        if (errstream != NULL) {
+          errstream->print_cr("Tag combination have duplicate tag '%s' in what-expression.",
+                              cur_tag);
+        }
+        success = false;
+        break;
+      }
       cur_tag = plus_pos + 1;
     } while (plus_pos != NULL);
 
--- a/src/share/vm/logging/logTagLevelExpression.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/logging/logTagLevelExpression.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -59,9 +59,15 @@
     _ntags = 0;
   }
 
-  void add_tag(LogTagType tag) {
+  bool add_tag(LogTagType tag) {
     assert(_ntags < LogTag::MaxTags, "Can't have more tags than MaxTags!");
+    for (size_t i = 0; i < _ntags; i++) {
+      if (_tags[_ncombinations][i] == tag) {
+        return false;
+      }
+    }
     _tags[_ncombinations][_ntags++] = tag;
+    return true;
   }
 
   void set_level(LogLevelType level) {
--- a/src/share/vm/oops/instanceKlass.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/oops/instanceKlass.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -3365,94 +3365,119 @@
 
 #if INCLUDE_JVMTI
 
-// RedefineClasses() support for previous versions:
-int InstanceKlass::_previous_version_count = 0;
-
-// Purge previous versions before adding new previous versions of the class.
-void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
+// RedefineClasses() support for previous versions
+
+// Globally, there is at least one previous version of a class to walk
+// during class unloading, which is saved because old methods in the class
+// are still running.   Otherwise the previous version list is cleaned up.
+bool InstanceKlass::_has_previous_versions = false;
+
+// Returns true if there are previous versions of a class for class
+// unloading only. Also resets the flag to false. purge_previous_version
+// will set the flag to true if there are any left, i.e., if there's any
+// work to do for next time. This is to avoid the expensive code cache
+// walk in CLDG::do_unloading().
+bool InstanceKlass::has_previous_versions_and_reset() {
+  bool ret = _has_previous_versions;
+  log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
+     ret ? "true" : "false");
+  _has_previous_versions = false;
+  return ret;
+}
+
+// Purge previous versions before adding new previous versions of the class and
+// during class unloading.
+void InstanceKlass::purge_previous_version_list() {
   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
-  if (ik->previous_versions() != NULL) {
-    // This klass has previous versions so see what we can cleanup
-    // while it is safe to do so.
-
-    int deleted_count = 0;    // leave debugging breadcrumbs
-    int live_count = 0;
-    ClassLoaderData* loader_data = ik->class_loader_data();
-    assert(loader_data != NULL, "should never be null");
-
-    ResourceMark rm;
-    log_trace(redefine, class, iklass, purge)("%s: previous versions", ik->external_name());
-
-    // previous versions are linked together through the InstanceKlass
-    InstanceKlass* pv_node = ik->previous_versions();
-    InstanceKlass* last = ik;
-    int version = 0;
-
-    // check the previous versions list
-    for (; pv_node != NULL; ) {
-
-      ConstantPool* pvcp = pv_node->constants();
-      assert(pvcp != NULL, "cp ref was unexpectedly cleared");
-
-      if (!pvcp->on_stack()) {
-        // If the constant pool isn't on stack, none of the methods
-        // are executing.  Unlink this previous_version.
-        // The previous version InstanceKlass is on the ClassLoaderData deallocate list
-        // so will be deallocated during the next phase of class unloading.
-        //
-        // Update count for class unloading.
-        _previous_version_count--;
-        log_trace(redefine, class, iklass, purge)
-          ("previous version " INTPTR_FORMAT " is dead.  previous_version_count = %d",
-           p2i(pv_node), _previous_version_count);
-        // For debugging purposes.
-        pv_node->set_is_scratch_class();
-        pv_node->class_loader_data()->add_to_deallocate_list(pv_node);
-        pv_node = pv_node->previous_versions();
-        last->link_previous_versions(pv_node);
-        deleted_count++;
-        version++;
-        continue;
-      } else {
-        log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
-        assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
-        guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
-        live_count++;
-      }
-
-      // At least one method is live in this previous version.
-      // Reset dead EMCP methods not to get breakpoints.
-      // All methods are deallocated when all of the methods for this class are no
-      // longer running.
-      Array<Method*>* method_refs = pv_node->methods();
-      if (method_refs != NULL) {
-        log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length());
-        for (int j = 0; j < method_refs->length(); j++) {
-          Method* method = method_refs->at(j);
-
-          if (!method->on_stack()) {
-            // no breakpoints for non-running methods
-            if (method->is_running_emcp()) {
-              method->set_running_emcp(false);
-            }
-          } else {
-            assert (method->is_obsolete() || method->is_running_emcp(),
-                    "emcp method cannot run after emcp bit is cleared");
-            log_trace(redefine, class, iklass, purge)
-              ("purge: %s(%s): prev method @%d in version @%d is alive",
-               method->name()->as_C_string(), method->signature()->as_C_string(), j, version);
+  assert(has_been_redefined(), "Should only be called for main class");
+
+  // Quick exit.
+  if (previous_versions() == NULL) {
+    return;
+  }
+
+  // This klass has previous versions so see what we can cleanup
+  // while it is safe to do so.
+
+  int deleted_count = 0;    // leave debugging breadcrumbs
+  int live_count = 0;
+  ClassLoaderData* loader_data = class_loader_data();
+  assert(loader_data != NULL, "should never be null");
+
+  ResourceMark rm;
+  log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
+
+  // previous versions are linked together through the InstanceKlass
+  InstanceKlass* pv_node = previous_versions();
+  InstanceKlass* last = this;
+  int version = 0;
+
+  // check the previous versions list
+  for (; pv_node != NULL; ) {
+
+    ConstantPool* pvcp = pv_node->constants();
+    assert(pvcp != NULL, "cp ref was unexpectedly cleared");
+
+    if (!pvcp->on_stack()) {
+      // If the constant pool isn't on stack, none of the methods
+      // are executing.  Unlink this previous_version.
+      // The previous version InstanceKlass is on the ClassLoaderData deallocate list
+      // so will be deallocated during the next phase of class unloading.
+      log_trace(redefine, class, iklass, purge)
+        ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
+      // For debugging purposes.
+      pv_node->set_is_scratch_class();
+      // Unlink from previous version list.
+      assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
+      InstanceKlass* next = pv_node->previous_versions();
+      pv_node->link_previous_versions(NULL);   // point next to NULL
+      last->link_previous_versions(next);
+      // Add to the deallocate list after unlinking
+      loader_data->add_to_deallocate_list(pv_node);
+      pv_node = next;
+      deleted_count++;
+      version++;
+      continue;
+    } else {
+      log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
+      assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
+      guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
+      live_count++;
+      // found a previous version for next time we do class unloading
+      _has_previous_versions = true;
+    }
+
+    // At least one method is live in this previous version.
+    // Reset dead EMCP methods not to get breakpoints.
+    // All methods are deallocated when all of the methods for this class are no
+    // longer running.
+    Array<Method*>* method_refs = pv_node->methods();
+    if (method_refs != NULL) {
+      log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length());
+      for (int j = 0; j < method_refs->length(); j++) {
+        Method* method = method_refs->at(j);
+
+        if (!method->on_stack()) {
+          // no breakpoints for non-running methods
+          if (method->is_running_emcp()) {
+            method->set_running_emcp(false);
           }
+        } else {
+          assert (method->is_obsolete() || method->is_running_emcp(),
+                  "emcp method cannot run after emcp bit is cleared");
+          log_trace(redefine, class, iklass, purge)
+            ("purge: %s(%s): prev method @%d in version @%d is alive",
+             method->name()->as_C_string(), method->signature()->as_C_string(), j, version);
         }
       }
-      // next previous version
-      last = pv_node;
-      pv_node = pv_node->previous_versions();
-      version++;
     }
-    log_trace(redefine, class, iklass, purge)
-      ("previous version stats: live=%d, deleted=%d",
-       live_count, deleted_count);
+    // next previous version
+    last = pv_node;
+    pv_node = pv_node->previous_versions();
+    version++;
   }
+  log_trace(redefine, class, iklass, purge)
+    ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
 }
 
 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
@@ -3519,14 +3544,13 @@
                                          int emcp_method_count) {
   assert(Thread::current()->is_VM_thread(),
          "only VMThread can add previous versions");
-  assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 
   ResourceMark rm;
   log_trace(redefine, class, iklass, add)
     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
 
-  // Clean out old previous versions
-  purge_previous_versions(this);
+  // Clean out old previous versions for this class
+  purge_previous_version_list();
 
   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
   // a previous redefinition may be made obsolete by this redefinition.
@@ -3570,11 +3594,9 @@
   }
 
   // Add previous version if any methods are still running.
-  // Update count for class unloading.
-  _previous_version_count++;
-  log_trace(redefine, class, iklass, add)
-    ("scratch class added; one of its methods is on_stack.  previous_version_count = %d",
-      _previous_version_count);
+  // Set has_previous_version flag for processing during class unloading.
+  _has_previous_versions = true;
+  log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
   scratch_class->link_previous_versions(previous_versions());
   link_previous_versions(scratch_class());
--- a/src/share/vm/oops/instanceKlass.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/oops/instanceKlass.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -619,8 +619,8 @@
   objArrayOop signers() const;
 
   // host class
-  Klass* host_klass() const              {
-    Klass** hk = (Klass**)adr_host_klass();
+  InstanceKlass* host_klass() const              {
+    InstanceKlass** hk = adr_host_klass();
     if (hk == NULL) {
       return NULL;
     } else {
@@ -628,9 +628,9 @@
       return *hk;
     }
   }
-  void set_host_klass(const Klass* host) {
+  void set_host_klass(const InstanceKlass* host) {
     assert(is_anonymous(), "not anonymous");
-    const Klass** addr = (const Klass**)adr_host_klass();
+    const InstanceKlass** addr = (const InstanceKlass **)adr_host_klass();
     assert(addr != NULL, "no reversed space");
     if (addr != NULL) {
       *addr = host;
@@ -709,6 +709,7 @@
 
   // RedefineClasses() support for previous versions:
   void add_previous_version(instanceKlassHandle ikh, int emcp_method_count);
+  void purge_previous_version_list();
 
   InstanceKlass* previous_versions() const { return _previous_versions; }
 #else
@@ -768,14 +769,16 @@
   }
 
  private:
-  static int  _previous_version_count;
+  static bool  _has_previous_versions;
  public:
-  static void purge_previous_versions(InstanceKlass* ik);
-  static bool has_previous_versions() {
-    assert(_previous_version_count >= 0, "count should never be negative");
-    return _previous_version_count > 0;
+  static void purge_previous_versions(InstanceKlass* ik) {
+    if (ik->has_been_redefined()) {
+      ik->purge_previous_version_list();
+    }
   }
 
+  static bool has_previous_versions_and_reset();
+
   // JVMTI: Support for caching a class file before it is modified by an agent that can do retransformation
   void set_cached_class_file(JvmtiCachedClassFileData *data) {
     _cached_class_file = data;
@@ -795,7 +798,7 @@
 #else // INCLUDE_JVMTI
 
   static void purge_previous_versions(InstanceKlass* ik) { return; };
-  static bool has_previous_versions() { return false; }
+  static bool has_previous_versions_and_reset() { return false; }
 
   void set_cached_class_file(JvmtiCachedClassFileData *data) {
     assert(data == NULL, "unexpected call with JVMTI disabled");
@@ -1060,13 +1063,13 @@
     }
   };
 
-  Klass** adr_host_klass() const {
+  InstanceKlass** adr_host_klass() const {
     if (is_anonymous()) {
-      Klass** adr_impl = adr_implementor();
+      InstanceKlass** adr_impl = (InstanceKlass **)adr_implementor();
       if (adr_impl != NULL) {
         return adr_impl + 1;
       } else {
-        return end_of_nonstatic_oop_maps();
+        return (InstanceKlass **)end_of_nonstatic_oop_maps();
       }
     } else {
       return NULL;
--- a/src/share/vm/oops/klass.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/oops/klass.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -431,6 +431,12 @@
     if (clean_alive_klasses && current->is_instance_klass()) {
       InstanceKlass* ik = InstanceKlass::cast(current);
       ik->clean_weak_instanceklass_links(is_alive);
+
+      // JVMTI RedefineClasses creates previous versions that are not in
+      // the class hierarchy, so process them here.
+      while ((ik = ik->previous_versions()) != NULL) {
+        ik->clean_weak_instanceklass_links(is_alive);
+      }
     }
   }
 }
--- a/src/share/vm/opto/c2compiler.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/opto/c2compiler.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -530,6 +530,7 @@
   case vmIntrinsics::_isInterrupted:
 #ifdef TRACE_HAVE_INTRINSICS
   case vmIntrinsics::_counterTime:
+  case vmIntrinsics::_getClassId:
 #endif
   case vmIntrinsics::_currentTimeMillis:
   case vmIntrinsics::_nanoTime:
--- a/src/share/vm/opto/graphKit.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/opto/graphKit.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -2172,10 +2172,9 @@
       java_bc() == Bytecodes::_instanceof ||
       java_bc() == Bytecodes::_aastore) {
     ciProfileData* data = method()->method_data()->bci_to_data(bci());
-    bool maybe_null = data == NULL ? true : data->as_BitData()->null_seen();
+    maybe_null = data == NULL ? true : data->as_BitData()->null_seen();
   }
   return record_profile_for_speculation(n, exact_kls, maybe_null);
-  return n;
 }
 
 /**
--- a/src/share/vm/opto/library_call.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/opto/library_call.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -254,6 +254,9 @@
   bool inline_native_currentThread();
 
   bool inline_native_time_funcs(address method, const char* funcName);
+#ifdef TRACE_HAVE_INTRINSICS
+  bool inline_native_classID();
+#endif
   bool inline_native_isInterrupted();
   bool inline_native_Class_query(vmIntrinsics::ID id);
   bool inline_native_subtype_check();
@@ -708,6 +711,7 @@
 
 #ifdef TRACE_HAVE_INTRINSICS
   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, TRACE_TIME_METHOD), "counterTime");
+  case vmIntrinsics::_getClassId:               return inline_native_classID();
 #endif
   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
@@ -2471,6 +2475,28 @@
       // load value
       switch (type) {
       case T_BOOLEAN:
+      {
+        // Normalize the value returned by getBoolean in the following cases
+        if (mismatched ||
+            heap_base_oop == top() ||                            // - heap_base_oop is NULL or
+            (can_access_non_heap && alias_type->field() == NULL) // - heap_base_oop is potentially NULL
+                                                                 //   and the unsafe access is made to large offset
+                                                                 //   (i.e., larger than the maximum offset necessary for any
+                                                                 //   field access)
+            ) {
+          IdealKit ideal = IdealKit(this);
+#define __ ideal.
+          IdealVariable normalized_result(ideal);
+          __ declarations_done();
+          __ set(normalized_result, p);
+          __ if_then(p, BoolTest::ne, ideal.ConI(0));
+          __ set(normalized_result, ideal.ConI(1));
+          ideal.end_if();
+          final_sync(ideal);
+          p = __ value(normalized_result);
+#undef __
+        }
+      }
       case T_CHAR:
       case T_BYTE:
       case T_SHORT:
@@ -3132,6 +3158,43 @@
   return true;
 }
 
+#ifdef TRACE_HAVE_INTRINSICS
+
+/*
+* oop -> myklass
+* myklass->trace_id |= USED
+* return myklass->trace_id & ~0x3
+*/
+bool LibraryCallKit::inline_native_classID() {
+  Node* cls = null_check(argument(0), T_OBJECT);
+  Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
+  kls = null_check(kls, T_OBJECT);
+
+  ByteSize offset = TRACE_KLASS_TRACE_ID_OFFSET;
+  Node* insp = basic_plus_adr(kls, in_bytes(offset));
+  Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);
+
+  Node* clsused = longcon(0x01l); // set the class bit
+  Node* orl = _gvn.transform(new OrLNode(tvalue, clsused));
+  const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
+  store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);
+
+#ifdef TRACE_ID_META_BITS
+  Node* mbits = longcon(~TRACE_ID_META_BITS);
+  tvalue = _gvn.transform(new AndLNode(tvalue, mbits));
+#endif
+#ifdef TRACE_ID_CLASS_SHIFT
+  Node* cbits = intcon(TRACE_ID_CLASS_SHIFT);
+  tvalue = _gvn.transform(new URShiftLNode(tvalue, cbits));
+#endif
+
+  set_result(tvalue);
+  return true;
+
+}
+
+#endif
+
 //------------------------inline_native_currentThread------------------
 bool LibraryCallKit::inline_native_currentThread() {
   Node* junk = NULL;
--- a/src/share/vm/opto/runtime.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/opto/runtime.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1349,17 +1349,23 @@
         force_unwind ? NULL : nm->handler_for_exception_and_pc(exception, pc);
 
       if (handler_address == NULL) {
-        Handle original_exception(thread, exception());
-        handler_address = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true);
+        bool recursive_exception = false;
+        handler_address = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true, recursive_exception);
         assert (handler_address != NULL, "must have compiled handler");
         // Update the exception cache only when the unwind was not forced
         // and there didn't happen another exception during the computation of the
-        // compiled exception handler.
-        if (!force_unwind && original_exception() == exception()) {
+        // compiled exception handler. Checking for exception oop equality is not
+        // sufficient because some exceptions are pre-allocated and reused.
+        if (!force_unwind && !recursive_exception) {
           nm->add_handler_for_exception_and_pc(exception,pc,handler_address);
         }
       } else {
-        assert(handler_address == SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true), "Must be the same");
+#ifdef ASSERT
+        bool recursive_exception = false;
+        address computed_address = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true, recursive_exception);
+        vmassert(recursive_exception || (handler_address == computed_address), "Handler address inconsistency: " PTR_FORMAT " != " PTR_FORMAT,
+                 p2i(handler_address), p2i(computed_address));
+#endif
       }
     }
 
--- a/src/share/vm/prims/jvmtiEnv.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/prims/jvmtiEnv.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -649,18 +649,14 @@
 
 jvmtiError
 JvmtiEnv::SetVerboseFlag(jvmtiVerboseFlag flag, jboolean value) {
+  LogLevelType level = value == 0 ? LogLevel::Off : LogLevel::Info;
   switch (flag) {
   case JVMTI_VERBOSE_OTHER:
     // ignore
     break;
   case JVMTI_VERBOSE_CLASS:
-    if (value == 0) {
-      LogConfiguration::parse_log_arguments("stdout", "class+unload=off", NULL, NULL, NULL);
-      LogConfiguration::parse_log_arguments("stdout", "class+load=off", NULL, NULL, NULL);
-    } else {
-      LogConfiguration::parse_log_arguments("stdout", "class+load=info", NULL, NULL, NULL);
-      LogConfiguration::parse_log_arguments("stdout", "class+unload=info", NULL, NULL, NULL);
-    }
+    LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, unload));
+    LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, load));
     break;
   case JVMTI_VERBOSE_GC:
     if (value == 0) {
--- a/src/share/vm/prims/unsafe.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/prims/unsafe.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -150,14 +150,23 @@
   }
 
   template <typename T>
-  T normalize(T x) {
+  T normalize_for_write(T x) {
     return x;
   }
 
-  jboolean normalize(jboolean x) {
+  jboolean normalize_for_write(jboolean x) {
     return x & 1;
   }
 
+  template <typename T>
+  T normalize_for_read(T x) {
+    return x;
+  }
+
+  jboolean normalize_for_read(jboolean x) {
+    return x != 0;
+  }
+
   /**
    * Helper class to wrap memory accesses in JavaThread::doing_unsafe_access()
    */
@@ -196,7 +205,7 @@
 
     T* p = (T*)addr();
 
-    T x = *p;
+    T x = normalize_for_read(*p);
 
     return x;
   }
@@ -207,7 +216,7 @@
 
     T* p = (T*)addr();
 
-    *p = normalize(x);
+    *p = normalize_for_write(x);
   }
 
 
@@ -223,7 +232,7 @@
 
     T x = OrderAccess::load_acquire((volatile T*)p);
 
-    return x;
+    return normalize_for_read(x);
   }
 
   template <typename T>
@@ -232,7 +241,7 @@
 
     T* p = (T*)addr();
 
-    OrderAccess::release_store_fence((volatile T*)p, normalize(x));
+    OrderAccess::release_store_fence((volatile T*)p, normalize_for_write(x));
   }
 
 
@@ -256,7 +265,7 @@
 
     jlong* p = (jlong*)addr();
 
-    Atomic::store(normalize(x),  p);
+    Atomic::store(normalize_for_write(x),  p);
   }
 #endif
 };
@@ -324,6 +333,10 @@
 
   volatile oop v;
 
+  if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    OrderAccess::fence();
+  }
+
   if (UseCompressedOops) {
     volatile narrowOop n = *(volatile narrowOop*) addr;
     (void)const_cast<oop&>(v = oopDesc::decode_heap_oop(n));
@@ -779,6 +792,7 @@
 
 // define a class but do not make it known to the class loader or system dictionary
 // - host_class:  supplies context for linkage, access control, protection domain, and class loader
+//                if host_class is itself anonymous then it is replaced with its host class.
 // - data:  bytes of a class file, a raw memory address (length gives the number of bytes)
 // - cp_patches:  where non-null entries exist, they replace corresponding CP entries in data
 
@@ -787,8 +801,12 @@
 // link to any member of U.  Just after U is loaded, the only way to use it is reflectively,
 // through java.lang.Class methods like Class.newInstance.
 
+// The package of an anonymous class must either match its host's class's package or be in the
+// unnamed package.  If it is in the unnamed package then it will be put in its host class's
+// package.
+//
+
 // Access checks for linkage sites within U continue to follow the same rules as for named classes.
-// The package of an anonymous class is given by the package qualifier on the name under which it was loaded.
 // An anonymous class also has special privileges to access any member of its host class.
 // This is the main reason why this loading operation is unsafe.  The purpose of this is to
 // allow language implementations to simulate "open classes"; a host class in effect gets
@@ -870,9 +888,11 @@
 
   // Primitive types have NULL Klass* fields in their java.lang.Class instances.
   if (host_klass == NULL) {
-    THROW_0(vmSymbols::java_lang_IllegalArgumentException());
+    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Host class is null");
   }
 
+  assert(host_klass->is_instance_klass(), "Host class must be an instance class");
+
   const char* host_source = host_klass->external_name();
   Handle      host_loader(THREAD, host_klass->class_loader());
   Handle      host_domain(THREAD, host_klass->protection_domain());
@@ -903,7 +923,7 @@
                                                 host_loader,
                                                 host_domain,
                                                 &st,
-                                                host_klass,
+                                                InstanceKlass::cast(host_klass),
                                                 cp_patches,
                                                 CHECK_NULL);
   if (anonk == NULL) {
--- a/src/share/vm/runtime/arguments.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/runtime/arguments.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -33,8 +33,9 @@
 #include "gc/shared/referenceProcessor.hpp"
 #include "gc/shared/taskqueue.hpp"
 #include "logging/log.hpp"
+#include "logging/logConfiguration.hpp"
+#include "logging/logStream.hpp"
 #include "logging/logTag.hpp"
-#include "logging/logConfiguration.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/universe.inline.hpp"
 #include "oops/oop.inline.hpp"
@@ -1307,35 +1308,13 @@
   return true;
 }
 
-// sets or adds a module name to the jdk.module.addmods property
-bool Arguments::append_to_addmods_property(const char* module_name) {
-  const char* key = "jdk.module.addmods";
-  const char* old_value = Arguments::get_property(key);
-  size_t buf_len = strlen(key) + strlen(module_name) + 2;
-  if (old_value != NULL) {
-    buf_len += strlen(old_value) + 1;
-  }
-  char* new_value = AllocateHeap(buf_len, mtArguments);
-  if (new_value == NULL) {
-    return false;
-  }
-  if (old_value == NULL) {
-    jio_snprintf(new_value, buf_len, "%s=%s", key, module_name);
-  } else {
-    jio_snprintf(new_value, buf_len, "%s=%s,%s", key, old_value, module_name);
-  }
-  bool added = add_property(new_value, UnwriteableProperty, InternalProperty);
-  FreeHeap(new_value);
-  return added;
-}
-
 #if INCLUDE_CDS
 void Arguments::check_unsupported_dumping_properties() {
   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
   const char* unsupported_properties[5] = { "jdk.module.main",
                                            "jdk.module.path",
                                            "jdk.module.upgrade.path",
-                                           "jdk.module.addmods",
+                                           "jdk.module.addmods.0",
                                            "jdk.module.limitmods" };
   const char* unsupported_options[5] = { "-m",
                                         "--module-path",
@@ -1686,11 +1665,6 @@
     CompactibleFreeListSpaceLAB::modify_initialization(OldPLABSize, OldPLABWeight);
   }
 
-  if (!ClassUnloading) {
-    FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
-    FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
-  }
-
   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
 }
 #endif // INCLUDE_ALL_GCS
@@ -2018,6 +1992,13 @@
     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
   }
+
+  // If class unloading is disabled, also disable concurrent class unloading.
+  if (!ClassUnloading) {
+    FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
+    FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);
+    FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
+  }
 #endif // INCLUDE_ALL_GCS
 }
 
@@ -2565,8 +2546,8 @@
 
 unsigned int addreads_count = 0;
 unsigned int addexports_count = 0;
+unsigned int addmods_count = 0;
 unsigned int patch_mod_count = 0;
-const char* add_modules_value = NULL;
 
 bool Arguments::create_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
@@ -2820,7 +2801,9 @@
         return JNI_ENOMEM;
       }
     } else if (match_option(option, "--add-modules=", &tail)) {
-      add_modules_value = tail;
+      if (!create_numbered_property("jdk.module.addmods", tail, addmods_count++)) {
+        return JNI_ENOMEM;
+      }
     } else if (match_option(option, "--limit-modules=", &tail)) {
       if (!create_property("jdk.module.limitmods", tail, InternalProperty)) {
         return JNI_ENOMEM;
@@ -2872,7 +2855,7 @@
         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtArguments), tail);
         add_init_agent("instrument", options, false);
         // java agents need module java.instrument
-        if (!Arguments::append_to_addmods_property("java.instrument")) {
+        if (!create_numbered_property("jdk.module.addmods", "java.instrument", addmods_count++)) {
           return JNI_ENOMEM;
         }
       }
@@ -3148,7 +3131,7 @@
           return JNI_EINVAL;
         }
         // management agent in module java.management
-        if (!Arguments::append_to_addmods_property("java.management")) {
+        if (!create_numbered_property("jdk.module.addmods", "java.management", addmods_count++)) {
           return JNI_ENOMEM;
         }
 #else
@@ -3559,15 +3542,6 @@
     return JNI_ERR;
   }
 
-  // Append the value of the last --add-modules option specified on the command line.
-  // This needs to be done here, to prevent overwriting possible values written
-  // to the jdk.module.addmods property by -javaagent and other options.
-  if (add_modules_value != NULL) {
-    if (!append_to_addmods_property(add_modules_value)) {
-      return JNI_ENOMEM;
-    }
-  }
-
   // This must be done after all arguments have been processed.
   // java_compiler() true means set to "NONE" or empty.
   if (java_compiler() && !xdebug_mode()) {
@@ -3616,7 +3590,8 @@
 #endif
 
 #if INCLUDE_JVMCI
-  if (EnableJVMCI && !append_to_addmods_property("jdk.vm.ci")) {
+  if (EnableJVMCI &&
+      !create_numbered_property("jdk.module.addmods", "jdk.vm.ci", addmods_count++)) {
     return JNI_ENOMEM;
   }
 #endif
@@ -4176,7 +4151,10 @@
   if (_gc_log_filename != NULL) {
     // -Xloggc was used to specify a filename
     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
-    return  LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, NULL);
+
+    LogTarget(Error, logging) target;
+    LogStreamCHeap errstream(target);
+    return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);
   } else if (PrintGC || PrintGCDetails) {
     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
   }
--- a/src/share/vm/runtime/arguments.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/runtime/arguments.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -489,9 +489,6 @@
 
   static int process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase);
 
-  // Miscellaneous system property setter
-  static bool append_to_addmods_property(const char* module_name);
-
   // Aggressive optimization flags.
   static jint set_aggressive_opts_flags();
 
--- a/src/share/vm/runtime/interfaceSupport.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/runtime/interfaceSupport.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -219,6 +219,9 @@
     trans_from_java(_thread_in_vm);
   }
   ~ThreadInVMfromJava()  {
+    if (_thread->stack_yellow_reserved_zone_disabled()) {
+      _thread->enable_stack_yellow_reserved_zone();
+    }
     trans(_thread_in_vm, _thread_in_Java);
     // Check for pending. async. exceptions or suspends.
     if (_thread->has_special_runtime_exit_condition()) _thread->handle_special_runtime_exit_condition();
@@ -306,6 +309,9 @@
     trans_from_java(_thread_in_vm);
   }
   ~ThreadInVMfromJavaNoAsyncException()  {
+    if (_thread->stack_yellow_reserved_zone_disabled()) {
+      _thread->enable_stack_yellow_reserved_zone();
+    }
     trans(_thread_in_vm, _thread_in_Java);
     // NOTE: We do not check for pending. async. exceptions.
     // If we did and moved the pending async exception over into the
@@ -314,6 +320,7 @@
     // to the _thread_in_vm state. Instead we postpone the handling of
     // the async exception.
 
+
     // Check for pending. suspends only.
     if (_thread->has_special_runtime_exit_condition())
       _thread->handle_special_runtime_exit_condition(false);
--- a/src/share/vm/runtime/os.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/runtime/os.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -443,7 +443,7 @@
 
   static bool create_thread(Thread* thread,
                             ThreadType thr_type,
-                            size_t stack_size = 0);
+                            size_t req_stack_size = 0);
   static bool create_main_thread(JavaThread* thread);
   static bool create_attached_thread(JavaThread* thread);
   static void pd_start_thread(Thread* thread);
--- a/src/share/vm/runtime/reflection.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/runtime/reflection.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -412,13 +412,13 @@
   return result;
 }
 
-static bool under_host_klass(const InstanceKlass* ik, const Klass* host_klass) {
+static bool under_host_klass(const InstanceKlass* ik, const InstanceKlass* host_klass) {
   DEBUG_ONLY(int inf_loop_check = 1000 * 1000 * 1000);
   for (;;) {
-    const Klass* hc = (const Klass*)ik->host_klass();
+    const InstanceKlass* hc = ik->host_klass();
     if (hc == NULL)        return false;
     if (hc == host_klass)  return true;
-    ik = InstanceKlass::cast(hc);
+    ik = hc;
 
     // There's no way to make a host class loop short of patching memory.
     // Therefore there cannot be a loop here unless there's another bug.
@@ -436,8 +436,8 @@
 
   // If either is on the other's host_klass chain, access is OK,
   // because one is inside the other.
-  if (under_host_klass(accessor_ik, accessee) ||
-    under_host_klass(accessee_ik, accessor))
+  if (under_host_klass(accessor_ik, accessee_ik) ||
+    under_host_klass(accessee_ik, accessor_ik))
     return true;
 
   if ((RelaxAccessControlCheck &&
--- a/src/share/vm/runtime/sharedRuntime.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/runtime/sharedRuntime.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -621,7 +621,7 @@
 // ret_pc points into caller; we are returning caller's exception handler
 // for given exception
 address SharedRuntime::compute_compiled_exc_handler(CompiledMethod* cm, address ret_pc, Handle& exception,
-                                                    bool force_unwind, bool top_frame_only) {
+                                                    bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred) {
   assert(cm != NULL, "must exist");
   ResourceMark rm;
 
@@ -677,6 +677,7 @@
         // BCI of the exception handler which caused the exception to be
         // thrown (bugs 4307310 and 4546590). Set "exception" reference
         // argument to ensure that the correct exception is thrown (4870175).
+        recursive_exception_occurred = true;
         exception = Handle(THREAD, PENDING_EXCEPTION);
         CLEAR_PENDING_EXCEPTION;
         if (handler_bci >= 0) {
--- a/src/share/vm/runtime/sharedRuntime.hpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/runtime/sharedRuntime.hpp	Tue Sep 13 18:19:05 2016 +0200
@@ -189,7 +189,7 @@
 
   // exception handling and implicit exceptions
   static address compute_compiled_exc_handler(CompiledMethod* nm, address ret_pc, Handle& exception,
-                                              bool force_unwind, bool top_frame_only);
+                                              bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred);
   enum ImplicitExceptionKind {
     IMPLICIT_NULL,
     IMPLICIT_DIVIDE_BY_ZERO,
--- a/src/share/vm/services/classLoadingService.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/services/classLoadingService.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -183,11 +183,8 @@
 bool ClassLoadingService::set_verbose(bool verbose) {
   MutexLocker m(Management_lock);
   // verbose will be set to the previous value
-  if (verbose) {
-    LogConfiguration::parse_log_arguments("stdout", "class+load=info", NULL, NULL, NULL);
-  } else {
-    LogConfiguration::parse_log_arguments("stdout", "class+load=off", NULL, NULL, NULL);
-  }
+  LogLevelType level = verbose ? LogLevel::Info : LogLevel::Off;
+  LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, load));
   reset_trace_class_unloading();
   return verbose;
 }
@@ -196,11 +193,8 @@
 void ClassLoadingService::reset_trace_class_unloading() {
   assert(Management_lock->owned_by_self(), "Must own the Management_lock");
   bool value = MemoryService::get_verbose() || ClassLoadingService::get_verbose();
-  if (value) {
-    LogConfiguration::parse_log_arguments("stdout", "class+unload=info", NULL, NULL, NULL);
-  } else {
-    LogConfiguration::parse_log_arguments("stdout", "class+unload=off", NULL, NULL, NULL);
-  }
+  LogLevelType level = value ? LogLevel::Info : LogLevel::Off;
+  LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, unload));
 }
 
 GrowableArray<KlassHandle>* LoadedClassesEnumerator::_loaded_classes = NULL;
--- a/src/share/vm/trace/traceevents.xml	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/trace/traceevents.xml	Tue Sep 13 18:19:05 2016 +0200
@@ -315,9 +315,9 @@
 
   <event id="G1MMU" path="vm/gc/detailed/g1_mmu_info" label="G1 MMU Information" is_instant="true">
     <value type="UINT" field="gcId" label="GC Identifier" relation="GcId"/>
-    <value type="DOUBLE" field="timeSlice" label="Time Slice" description="Time slice used to calculate MMU"/>
-    <value type="DOUBLE" field="gcTime" label="GC Time" description="Time spent on GC during last time slice"/>
-    <value type="DOUBLE" field="maxGcTime" label="Max GC Time" description="Max time allowed to be spent on GC during last time slice"/>
+    <value type="MILLIS" field="timeSlice" label="Time Slice" description="Time slice used to calculate MMU"/>
+    <value type="MILLIS" field="gcTime" label="GC Time" description="Time stopped because of GC during last time slice"/>
+    <value type="MILLIS" field="pauseTarget" label="Pause Target" description="Max time allowed to be spent on GC during last time slice"/>
   </event>
 
   <event id="EvacuationInformation" path="vm/gc/detailed/evacuation_info" label="Evacuation Information" is_instant="true">
@@ -377,29 +377,29 @@
     <structvalue type="G1EvacuationStatistics" field="statistics" label="Evacuation Statistics"/>
   </event>
 
-  <event id="G1BasicIHOP" path="vm/gc/detailed/g1_basic_ihop_status" label="G1 Basic IHOP statistics"
+  <event id="G1BasicIHOP" path="vm/gc/detailed/g1_basic_ihop_status" label="G1 Basic IHOP Statistics"
          is_instant="true" description="Basic statistics related to current IHOP calculation">
     <value type="UINT" field="gcId" label="GC Identifier" relation="GcId"/>
-    <value type="BYTES64" field="threshold" label="Current IHOP threshold" description="Current IHOP threshold in bytes"/>
-    <value type="PERCENTAGE" field="thresholdPercentage" label="Current IHOP threshold in percent" description="Current IHOP threshold in percent of old gen"/>
-    <value type="BYTES64" field="targetOccupancy" label="Target Occupancy" description="Target old gen occupancy to reach at the start of mixed GC in bytes"/>
-    <value type="BYTES64" field="currentOccupancy" label="Current Occupancy" description="Current old generation occupancy in bytes"/>
-    <value type="BYTES64" field="lastAllocationSize" label="Last Mutator Allocation" description="Mutator allocation during mutator operation since last GC in bytes"/>
-    <value type="DOUBLE" field="lastAllocationDuration" label="Last Mutator Operation" description="Time the mutator ran since last GC in seconds"/>
-    <value type="DOUBLE" field="lastAllocationRate" label="Last Mutator Allocation Rate" description="Allocation rate of the mutator since last GC in bytes/second"/>
-    <value type="DOUBLE" field="lastMarkingLength" label="Last Marking Length" description="Last time from the end of the last initial mark to the first mixed GC in seconds"/>
+    <value type="BYTES64" field="threshold" label="Current IHOP Threshold" description="Current IHOP threshold"/>
+    <value type="PERCENTAGE" field="thresholdPercentage" label="Current IHOP Threshold" description="Current IHOP threshold in percent of old generation"/>
+    <value type="BYTES64" field="targetOccupancy" label="Target Occupancy" description="Target old generation occupancy to reach at the start of mixed GC"/>
+    <value type="BYTES64" field="currentOccupancy" label="Current Occupancy" description="Current old generation occupancy"/>
+    <value type="BYTES64" field="recentMutatorAllocationSize" label="Recent Mutator Allocation Size" description="Mutator allocation during mutator operation in the most recent interval"/>
+    <value type="MILLIS" field="recentMutatorDuration" label="Recent Mutator Duration" description="Time the mutator ran in the most recent interval"/>
+    <value type="DOUBLE" field="recentAllocationRate" label="Recent Allocation Rate" description="Allocation rate of the mutator in the most recent interval in bytes/second"/>
+    <value type="MILLIS" field="lastMarkingDuration" label="Last Marking Duration" description="Last time from the end of the last initial mark to the first mixed GC"/>
   </event>
 
-  <event id="G1AdaptiveIHOP" path="vm/gc/detailed/g1_adaptive_ihop_status" label="G1 Adaptive IHOP statistics"
+  <event id="G1AdaptiveIHOP" path="vm/gc/detailed/g1_adaptive_ihop_status" label="G1 Adaptive IHOP Statistics"
          is_instant="true" description="Statistics related to current adaptive IHOP calculation">
     <value type="UINT" field="gcId" label="GC Identifier" relation="GcId"/>
-    <value type="BYTES64" field="threshold" label="Threshold" description="Current IHOP threshold in bytes"/>
-    <value type="PERCENTAGE" field="thresholdPercentage" label="Threshold Percentage" description="Current IHOP threshold in percent of the internal target occupancy"/>
-    <value type="BYTES64" field="internalTargetOccupancy" label="Target Occupancy" description="Internal target old generation occupancy to reach at the start of mixed GC in bytes"/>
-    <value type="BYTES64" field="currentOccupancy" label="Current Occupancy" description="Current old generation occupancy in bytes"/>
-    <value type="BYTES64" field="additionalBufferSize" label="Additional Buffer" description="Additional buffer size in bytes"/>
+    <value type="BYTES64" field="threshold" label="Threshold" description="Current IHOP Threshold"/>
+    <value type="PERCENTAGE" field="thresholdPercentage" label="Threshold" description="Current IHOP threshold in percent of the internal target occupancy"/>
+    <value type="BYTES64" field="ihopTargetOccupancy" label="IHOP Target Occupancy" description="Internal target old generation occupancy to reach at the start of mixed GC"/>
+    <value type="BYTES64" field="currentOccupancy" label="Current Occupancy" description="Current old generation occupancy"/>
+    <value type="BYTES64" field="additionalBufferSize" label="Additional Buffer" description="Additional buffer size" experimental="true"/>
     <value type="DOUBLE" field="predictedAllocationRate" label="Predicted Allocation Rate" description="Current predicted allocation rate for the mutator in bytes/second"/>
-    <value type="DOUBLE" field="predictedMarkingLength" label="Predicted Marking Length" description="Current predicted time from the end of the last initial mark to the first mixed GC in seconds"/>
+    <value type="MILLIS" field="predictedMarkingDuration" label="Predicted Marking Duration" description="Current predicted time from the end of the last initial mark to the first mixed GC"/>
     <value type="BOOLEAN" field="predictionActive" label="Prediction Active" description="Indicates whether the adaptive IHOP prediction is active"/>
   </event>
 
--- a/src/share/vm/utilities/exceptions.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/utilities/exceptions.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -80,7 +80,7 @@
   if (h_exception()->klass() == SystemDictionary::StackOverflowError_klass()) {
     InstanceKlass* ik = InstanceKlass::cast(h_exception->klass());
     assert(ik->is_initialized(),
-           "need to increase min_stack_allowed calculation");
+           "need to increase java_thread_min_stack_allowed calculation");
   }
 #endif // ASSERT
 
@@ -227,7 +227,7 @@
     Klass* k = SystemDictionary::StackOverflowError_klass();
     oop e = InstanceKlass::cast(k)->allocate_instance(CHECK);
     exception = Handle(THREAD, e);  // fill_in_stack trace does gc
-    assert(InstanceKlass::cast(k)->is_initialized(), "need to increase min_stack_allowed calculation");
+    assert(InstanceKlass::cast(k)->is_initialized(), "need to increase java_thread_min_stack_allowed calculation");
     if (StackTraceInThrowable) {
       java_lang_Throwable::fill_in_stack_trace(exception, method());
     }
--- a/src/share/vm/utilities/internalVMTests.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/utilities/internalVMTests.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -56,12 +56,10 @@
   run_unit_test(CollectedHeap_test);
   run_unit_test(QuickSort_test);
   run_unit_test(GuardedMemory_test);
-  run_unit_test(AltHashing_test);
   run_unit_test(TestNewSize_test);
   run_unit_test(TestOldSize_test);
   run_unit_test(TestKlass_test);
   run_unit_test(TestBitMap_test);
-  run_unit_test(TestAsUtf8);
   run_unit_test(TestResourcehash_test);
   run_unit_test(ObjectMonitor_test);
   run_unit_test(Test_linked_list);
@@ -89,16 +87,12 @@
   run_unit_test(VMStructs_test);
 #endif
 #if INCLUDE_ALL_GCS
-  run_unit_test(TestOldFreeSpaceCalculation_test);
   run_unit_test(TestG1BiasedArray_test);
   run_unit_test(TestBufferingOopClosure_test);
-  run_unit_test(TestCodeCacheRemSet_test);
   if (UseG1GC) {
     run_unit_test(FreeRegionList_test);
     run_unit_test(IHOP_test);
   }
-  run_unit_test(test_memset_with_concurrent_readers);
-  run_unit_test(TestPredictions_test);
   run_unit_test(WorkerDataArray_test);
   run_unit_test(ParallelCompact_test);
 #endif
--- a/src/share/vm/utilities/utf8.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/src/share/vm/utilities/utf8.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -547,30 +547,3 @@
 template int UNICODE::quoted_ascii_length<jchar>(jchar* base, int length);
 template void UNICODE::as_quoted_ascii<jbyte>(const jbyte* base, int length, char* buf, int buflen);
 template void UNICODE::as_quoted_ascii<jchar>(const jchar* base, int length, char* buf, int buflen);
-
-
-#ifndef PRODUCT
-void TestAsUtf8() {
-  char res[60];
-  jchar str[20];
-
-  for (int i = 0; i < 20; i++) {
-    str[i] = 0x0800; // char that is 2B in UTF-16 but 3B in UTF-8
-  }
-  str[19] = (jchar)'\0';
-
-  // The resulting string in UTF-8 is 3*19 bytes long, but should be truncated
-  UNICODE::as_utf8(str, 19, res, 10);
-  assert(strlen(res) == 9, "string should be truncated here");
-
-  UNICODE::as_utf8(str, 19, res, 18);
-  assert(strlen(res) == 15, "string should be truncated here");
-
-  UNICODE::as_utf8(str, 19, res, 20);
-  assert(strlen(res) == 18, "string should be truncated here");
-
-  // Test with an "unbounded" buffer
-  UNICODE::as_utf8(str, 19, res, INT_MAX);
-  assert(strlen(res) == 3*19, "string should end here");
-}
-#endif
--- a/test/TEST.groups	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/TEST.groups	Tue Sep 13 18:19:05 2016 +0200
@@ -168,7 +168,6 @@
   runtime/InternalApi/ThreadCpuTimesDeadlock.java \
   runtime/NMT/JcmdSummaryDiff.java \
   runtime/RedefineTests/RedefineAnnotations.java \
-  serviceability/sa/jmap-hashcode/Test8028623.java \
   serviceability/threads/TestFalseDeadLock.java \
   compiler/codecache/jmx \
   compiler/jsr292/RedefineMethodUsedByMultipleMethodHandles.java \
--- a/test/compiler/codecache/OverflowCodeCacheTest.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/compiler/codecache/OverflowCodeCacheTest.java	Tue Sep 13 18:19:05 2016 +0200
@@ -75,6 +75,7 @@
         System.out.printf("type %s%n", type);
         System.out.println("allocating till possible...");
         ArrayList<Long> blobs = new ArrayList<>();
+        int compilationActivityMode = -1;
         try {
             long addr;
             int size = (int) (getHeapSize() >> 7);
@@ -88,13 +89,16 @@
                             type + " doesn't allow using " + actualType + " when overflow");
                 }
             }
-            Asserts.assertNotEquals(WHITE_BOX.getCompilationActivityMode(), 1 /* run_compilation*/,
-                    "Compilation must be disabled when CodeCache(CodeHeap) overflows");
+            /* now, remember compilationActivityMode to check it later, after freeing, since we
+               possibly have no free cache for futher work */
+            compilationActivityMode = WHITE_BOX.getCompilationActivityMode();
         } finally {
             for (Long blob : blobs) {
                 WHITE_BOX.freeCodeBlob(blob);
             }
         }
+        Asserts.assertNotEquals(compilationActivityMode, 1 /* run_compilation*/,
+                "Compilation must be disabled when CodeCache(CodeHeap) overflows");
     }
 
     private long getHeapSize() {
--- a/test/compiler/cpuflags/AESIntrinsicsBase.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/compiler/cpuflags/AESIntrinsicsBase.java	Tue Sep 13 18:19:05 2016 +0200
@@ -48,8 +48,8 @@
             = {"-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintIntrinsics"};
     public static final String[] TEST_AES_CMD
             = {"-XX:+IgnoreUnrecognizedVMOptions", "-XX:+PrintFlagsFinal",
-            "-Xbatch", "-DcheckOutput=true", "-Dmode=CBC",
-            TestAESMain.class.getName()};
+            "-Xbatch", "-XX:CompileThresholdScaling=0.01", "-DcheckOutput=true", "-Dmode=CBC",
+            TestAESMain.class.getName(), "100", "1000"};
 
     protected AESIntrinsicsBase(BooleanSupplier predicate) {
         super(predicate);
--- a/test/compiler/cpuflags/TestAESIntrinsicsOnSupportedConfig.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/compiler/cpuflags/TestAESIntrinsicsOnSupportedConfig.java	Tue Sep 13 18:19:05 2016 +0200
@@ -27,11 +27,11 @@
  * @library /test/lib /
  * @modules java.base/jdk.internal.misc
  *          java.management
- * @ignore 8146128
  * @build sun.hotspot.WhiteBox
  * @run driver ClassFileInstaller sun.hotspot.WhiteBox
  *                                sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
+ * @run main/othervm/timeout=600 -Xbootclasspath/a:.
+ *                   -XX:+UnlockDiagnosticVMOptions
  *                   -XX:+WhiteBoxAPI -Xbatch
  *                   compiler.cpuflags.TestAESIntrinsicsOnSupportedConfig
  */
--- a/test/compiler/jsr292/CallSiteDepContextTest.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/compiler/jsr292/CallSiteDepContextTest.java	Tue Sep 13 18:19:05 2016 +0200
@@ -62,7 +62,7 @@
 public class CallSiteDepContextTest {
     static final Unsafe               UNSAFE = Unsafe.getUnsafe();
     static final MethodHandles.Lookup LOOKUP = MethodHandleHelper.IMPL_LOOKUP;
-    static final String           CLASS_NAME = "java/lang/invoke/Test";
+    static final String           CLASS_NAME = "compiler/jsr292/Test";
     static final String          METHOD_NAME = "m";
     static final MethodType TYPE = MethodType.methodType(int.class);
 
@@ -129,8 +129,8 @@
     }
 
     public static void testSharedCallSite() throws Throwable {
-        Class<?> cls1 = UNSAFE.defineAnonymousClass(Object.class, getClassFile("CS_1"), null);
-        Class<?> cls2 = UNSAFE.defineAnonymousClass(Object.class, getClassFile("CS_2"), null);
+        Class<?> cls1 = UNSAFE.defineAnonymousClass(CallSiteDepContextTest.class, getClassFile("CS_1"), null);
+        Class<?> cls2 = UNSAFE.defineAnonymousClass(CallSiteDepContextTest.class, getClassFile("CS_2"), null);
 
         MethodHandle[] mhs = new MethodHandle[] {
                 LOOKUP.findStatic(cls1, METHOD_NAME, TYPE),
@@ -151,7 +151,7 @@
         execute(1, mh);
 
         // mcs.context == cls1
-        Class<?> cls1 = UNSAFE.defineAnonymousClass(Object.class, getClassFile("NonBound_1"), null);
+        Class<?> cls1 = UNSAFE.defineAnonymousClass(CallSiteDepContextTest.class, getClassFile("NonBound_1"), null);
         MethodHandle mh1 = LOOKUP.findStatic(cls1, METHOD_NAME, TYPE);
 
         execute(1, mh1);
@@ -170,8 +170,8 @@
         mcs = new MutableCallSite(LOOKUP.findStatic(T.class, "f1", TYPE));
 
         Class<?>[] cls = new Class[] {
-                UNSAFE.defineAnonymousClass(Object.class, getClassFile("GC_1" + id), null),
-                UNSAFE.defineAnonymousClass(Object.class, getClassFile("GC_2" + id), null),
+                UNSAFE.defineAnonymousClass(CallSiteDepContextTest.class, getClassFile("GC_1" + id), null),
+                UNSAFE.defineAnonymousClass(CallSiteDepContextTest.class, getClassFile("GC_2" + id), null),
         };
 
         MethodHandle[] mhs = new MethodHandle[] {
@@ -185,7 +185,7 @@
         execute(1, mhs);
 
         ref = new PhantomReference<>(cls[0], rq);
-        cls[0] = UNSAFE.defineAnonymousClass(Object.class, getClassFile("GC_3" + id), null);
+        cls[0] = UNSAFE.defineAnonymousClass(CallSiteDepContextTest.class, getClassFile("GC_3" + id), null);
         mhs[0] = LOOKUP.findStatic(cls[0], METHOD_NAME, TYPE);
 
         do {
--- a/test/compiler/jvmci/compilerToVM/ExecuteInstalledCodeTest.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/compiler/jvmci/compilerToVM/ExecuteInstalledCodeTest.java	Tue Sep 13 18:19:05 2016 +0200
@@ -19,7 +19,6 @@
  * @requires (vm.simpleArch == "x64" | vm.simpleArch == "sparcv9" | vm.simpleArch == "aarch64")
  * @library /test/lib /
  * @library ../common/patches
- * @ignore 8139383
  * @modules java.base/jdk.internal.misc
  * @modules java.base/jdk.internal.org.objectweb.asm
  *          java.base/jdk.internal.org.objectweb.asm.tree
--- a/test/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/TestResolvedJavaType.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/TestResolvedJavaType.java	Tue Sep 13 18:19:05 2016 +0200
@@ -25,7 +25,6 @@
  * @test
  * @requires (vm.simpleArch == "x64" | vm.simpleArch == "sparcv9" | vm.simpleArch == "aarch64")
  * @library ../../../../../
- * @ignore 8161550
  * @modules java.base/jdk.internal.reflect
  *          jdk.vm.ci/jdk.vm.ci.meta
  *          jdk.vm.ci/jdk.vm.ci.runtime
@@ -74,11 +73,29 @@
 /**
  * Tests for {@link ResolvedJavaType}.
  */
+@SuppressWarnings("unchecked")
 public class TestResolvedJavaType extends TypeUniverse {
+    private static final Class<? extends Annotation> SIGNATURE_POLYMORPHIC_CLASS = findPolymorphicSignatureClass();
 
     public TestResolvedJavaType() {
     }
 
+    private static Class<? extends Annotation> findPolymorphicSignatureClass() {
+        Class<? extends Annotation> signaturePolyAnnotation = null;
+        try {
+            for (Class<?> clazz : TestResolvedJavaType.class.getClassLoader().loadClass("java.lang.invoke.MethodHandle").getDeclaredClasses()) {
+                if (clazz.getName().endsWith("PolymorphicSignature") && Annotation.class.isAssignableFrom(clazz)) {
+                    signaturePolyAnnotation = (Class<? extends Annotation>) clazz;
+                    break;
+                }
+            }
+        } catch (Throwable e) {
+            throw new AssertionError("Could not find annotation PolymorphicSignature in java.lang.invoke.MethodHandle", e);
+        }
+        assertNotNull(signaturePolyAnnotation);
+        return signaturePolyAnnotation;
+    }
+
     @Test
     public void findInstanceFieldWithOffsetTest() {
         for (Class<?> c : classes) {
@@ -577,8 +594,14 @@
                     for (Method decl : decls) {
                         ResolvedJavaMethod m = metaAccess.lookupJavaMethod(decl);
                         if (m.isPublic()) {
-                            ResolvedJavaMethod i = metaAccess.lookupJavaMethod(impl);
-                            assertEquals(m.toString(), i, type.resolveMethod(m, context));
+                            ResolvedJavaMethod resolvedmethod = type.resolveMethod(m, context);
+                            if (isSignaturePolymorphic(m)) {
+                                // Signature polymorphic methods must not be resolved
+                                assertNull(resolvedmethod);
+                            } else {
+                                ResolvedJavaMethod i = metaAccess.lookupJavaMethod(impl);
+                                assertEquals(m.toString(), i, resolvedmethod);
+                            }
                         }
                     }
                 }
@@ -606,8 +629,14 @@
                     for (Method decl : decls) {
                         ResolvedJavaMethod m = metaAccess.lookupJavaMethod(decl);
                         if (m.isPublic()) {
-                            ResolvedJavaMethod i = metaAccess.lookupJavaMethod(impl);
-                            assertEquals(i, type.resolveConcreteMethod(m, context));
+                            ResolvedJavaMethod resolvedMethod = type.resolveConcreteMethod(m, context);
+                            if (isSignaturePolymorphic(m)) {
+                                // Signature polymorphic methods must not be resolved
+                                assertNull(String.format("Got: %s", resolvedMethod), resolvedMethod);
+                            } else {
+                                ResolvedJavaMethod i = metaAccess.lookupJavaMethod(impl);
+                                assertEquals(i, resolvedMethod);
+                            }
                         }
                     }
                 }
@@ -929,4 +958,8 @@
             }
         }
     }
+
+    private static boolean isSignaturePolymorphic(ResolvedJavaMethod method) {
+        return method.getAnnotation(SIGNATURE_POLYMORPHIC_CLASS) != null;
+    }
 }
--- a/test/compiler/loopopts/UseCountedLoopSafepoints.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/compiler/loopopts/UseCountedLoopSafepoints.java	Tue Sep 13 18:19:05 2016 +0200
@@ -22,51 +22,32 @@
  *
  */
 
-/**
- * @test
- * @bug 6869327
- * @summary Test that C2 flag UseCountedLoopSafepoints ensures a safepoint is kept in a CountedLoop
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- * @ignore 8146096
- * @run driver compiler.loopopts.UseCountedLoopSafepoints
- */
-
 package compiler.loopopts;
 
-import jdk.test.lib.process.OutputAnalyzer;
-import jdk.test.lib.process.ProcessTools;
-
-import java.util.concurrent.atomic.AtomicLong;
+import java.lang.reflect.Method;
+import sun.hotspot.WhiteBox;
+import jdk.test.lib.Asserts;
+import compiler.whitebox.CompilerWhiteBoxTest;
 
 public class UseCountedLoopSafepoints {
-    private static final AtomicLong _num = new AtomicLong(0);
+    private static final WhiteBox WB = WhiteBox.getWhiteBox();
+    private static final String METHOD_NAME = "testMethod";
 
-    // Uses the fact that an EnableBiasedLocking vmop will be started
-    // after 500ms, while we are still in the loop. If there is a
-    // safepoint in the counted loop, then we will reach safepoint
-    // very quickly. Otherwise SafepointTimeout will be hit.
+    private long accum = 0;
+
     public static void main (String args[]) throws Exception {
-        if (args.length == 1) {
-            final int loops = Integer.parseInt(args[0]);
-            for (int i = 0; i < loops; i++) {
-                _num.addAndGet(1);
-            }
-        } else {
-            ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-                    "-XX:+IgnoreUnrecognizedVMOptions",
-                    "-XX:-TieredCompilation",
-                    "-XX:+UseBiasedLocking",
-                    "-XX:BiasedLockingStartupDelay=500",
-                    "-XX:+SafepointTimeout",
-                    "-XX:SafepointTimeoutDelay=2000",
-                    "-XX:+UseCountedLoopSafepoints",
-                    UseCountedLoopSafepoints.class.getName(),
-                    "2000000000"
-                    );
-            OutputAnalyzer output = new OutputAnalyzer(pb.start());
-            output.shouldNotContain("Timeout detected");
-            output.shouldHaveExitValue(0);
+        new UseCountedLoopSafepoints().testMethod();
+        Method m = UseCountedLoopSafepoints.class.getDeclaredMethod(METHOD_NAME);
+        String directive = "[{ match: \"" + UseCountedLoopSafepoints.class.getName().replace('.', '/')
+                + "." + METHOD_NAME + "\", " + "BackgroundCompilation: false }]";
+        Asserts.assertTrue(WB.addCompilerDirective(directive) == 1, "Can't add compiler directive");
+        Asserts.assertTrue(WB.enqueueMethodForCompilation(m,
+                CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION), "Can't enqueue method");
+    }
+
+    private void testMethod() {
+        for (int i = 0; i < 100; i++) {
+            accum += accum << 5 + accum >> 4 - accum >>> 5;
         }
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/loopopts/UseCountedLoopSafepointsTest.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 6869327
+ * @summary Test that C2 flag UseCountedLoopSafepoints ensures a safepoint is kept in a CountedLoop
+ * @library /test/lib /
+ * @requires vm.compMode != "Xint" & vm.flavor == "server" & (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 4)
+ * @modules java.base/jdk.internal.misc
+ * @build sun.hotspot.WhiteBox
+ * @run driver ClassFileInstaller sun.hotspot.WhiteBox
+ *                                sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver compiler.loopopts.UseCountedLoopSafepointsTest
+ */
+
+package compiler.loopopts;
+
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import jdk.test.lib.Asserts;
+
+/* Idea of this test is to check if ideal graph has CountedLoopEnd->SafePoint edge in case
+   of UseCountedLoopSafepoint enabled and has no such edge in case it's disabled. Restricting
+   compilation to testMethod only will leave only one counted loop (the one in testedMethod) */
+public class UseCountedLoopSafepointsTest {
+
+    public static void main (String args[]) {
+        check(true); // check ideal graph with UseCountedLoopSafepoint enabled
+        check(false); // ... and disabled
+    }
+
+    private static void check(boolean enabled) {
+        OutputAnalyzer oa;
+        try {
+            oa = ProcessTools.executeTestJvm("-XX:+UnlockDiagnosticVMOptions", "-Xbootclasspath/a:.",
+                    "-XX:" + (enabled ? "+" : "-") + "UseCountedLoopSafepoints", "-XX:+WhiteBoxAPI",
+                    "-XX:-Inline", "-Xbatch", "-XX:+PrintIdeal", "-XX:LoopUnrollLimit=0",
+                    "-XX:CompileOnly=" + UseCountedLoopSafepoints.class.getName() + "::testMethod",
+                    UseCountedLoopSafepoints.class.getName());
+        } catch (Exception e) {
+            throw new Error("Exception launching child for case enabled=" + enabled + " : " + e, e);
+        }
+        oa.shouldHaveExitValue(0);
+        // parse output in seach of SafePoint and CountedLoopEnd nodes
+        List<Node> safePoints = new ArrayList<>();
+        List<Node> loopEnds = new ArrayList<>();
+        for (String line : oa.getOutput().split("\\n")) {
+            int separatorIndex = line.indexOf("\t===");
+            if (separatorIndex > -1) {
+                String header = line.substring(0, separatorIndex);
+                if (header.endsWith("\tSafePoint")) {
+                    safePoints.add(new Node("SafePoint", line));
+                } else if (header.endsWith("\tCountedLoopEnd")) {
+                    loopEnds.add(new Node("CountedLoopEnd", line));
+                }
+            }
+        }
+        // now, find CountedLoopEnd -> SafePoint edge
+        boolean found = false;
+        for (Node loopEnd : loopEnds) {
+            found |= loopEnd.to.stream()
+                                 .filter(id -> nodeListHasElementWithId(safePoints, id))
+                                 .findAny()
+                                 .isPresent();
+        }
+        Asserts.assertEQ(enabled, found, "Safepoint " + (found ? "" : "not ") + "found");
+    }
+
+    private static boolean nodeListHasElementWithId(List<Node> list, int id) {
+        return list.stream()
+                   .filter(node -> node.id == id)
+                   .findAny()
+                   .isPresent();
+    }
+
+    private static class Node {
+        public final int id;
+        public final List<Integer> from;
+        public final List<Integer> to;
+
+        public Node(String name, String str) {
+            List<Integer> tmpFrom = new ArrayList<>();
+            List<Integer> tmpTo = new ArrayList<>();
+            // parse string like: " $id    $name       ===  $to1 $to2 ...   [[ $from1 $from2 ... ]] $anything"
+            // example:  318    SafePoint       ===  317  1  304  1  1  10  308  [[ 97  74 ]]  ...
+            id = Integer.parseInt(str.substring(1, str.indexOf(name)).trim());
+            Arrays.stream(str.substring(str.indexOf("===") + 4, str.indexOf("[[")).trim().split("\\s+"))
+                  .map(Integer::parseInt)
+                  .forEach(tmpTo::add);
+            Arrays.stream(str.substring(str.indexOf("[[") + 3, str.indexOf("]]")).trim().split("\\s+"))
+                  .map(Integer::parseInt)
+                  .forEach(tmpFrom::add);
+            this.from = Collections.unmodifiableList(tmpFrom);
+            this.to = Collections.unmodifiableList(tmpTo);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/unsafe/UnsafeOffHeapBooleanTest.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8161720
+ * @modules java.base/jdk.internal.misc
+ * @run main/othervm -Xint UnsafeOffHeapBooleanTest 1
+ * @run main/othervm -XX:+TieredCompilation -XX:TieredStopAtLevel=3 -Xbatch  UnsafeOffHeapBooleanTest 20000
+ * @run main/othervm -XX:-TieredCompilation -Xbatch UnsafeOffHeapBooleanTest 20000
+ */
+
+
+import java.lang.reflect.Field;
+import jdk.internal.misc.Unsafe;
+
+public class UnsafeOffHeapBooleanTest {
+    static boolean bool0 = false, bool1 = false, result = false;
+    static Unsafe UNSAFE = Unsafe.getUnsafe();
+    static long offHeapMemory;
+
+    public static void test() {
+        // Write two bytes to the off-heap memory location, both
+        // bytes correspond to the boolean value 'true'.
+        UNSAFE.putShort(null, offHeapMemory, (short)0x0204);
+
+        // Read two bytes from the storage allocated above (as booleans).
+        bool0 = UNSAFE.getBoolean(null, offHeapMemory + 0);
+        bool1 = UNSAFE.getBoolean(null, offHeapMemory + 1);
+        result = bool0 & bool1;
+    }
+
+    public static void main(String args[]) {
+        System.out.println("### Test started");
+
+        if (args.length != 1) {
+            throw new RuntimeException("### Test failure: test called with incorrect number of arguments");
+        }
+
+        // Allocate two bytes of storage.
+        offHeapMemory = UNSAFE.allocateMemory(2);
+
+        try {
+            for (int i = 0; i < Integer.parseInt(args[0]); i++) {
+                test();
+            }
+
+            // Check if the two 'true' boolean values were normalized
+            // (i.e., reduced from the range 1...255 to 1).
+            if (!bool0 || !bool1 || !result) {
+                System.out.println("Some of the results below are wrong");
+                System.out.println("bool0 is: " + bool0);
+                System.out.println("bool1 is: " + bool1);
+                System.out.println("bool0 & bool1 is: " + result);
+                System.out.println("===================================");
+                throw new RuntimeException("### Test failed");
+            } else {
+                System.out.println("Test generated correct results");
+                System.out.println("bool0 is: " + bool0);
+                System.out.println("bool1 is: " + bool1);
+                System.out.println("bool0 & bool1 is: " + result);
+                System.out.println("===================================");
+            }
+        } catch (NumberFormatException e) {
+            throw new RuntimeException("### Test failure: test called with incorrectly formatted parameter");
+        }
+
+        UNSAFE.freeMemory(offHeapMemory);
+
+        System.out.println("### Test passed");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/unsafe/UnsafeOnHeapBooleanTest.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8161720
+ * @modules java.base/jdk.internal.misc
+ * @run main/othervm -Xint UnsafeOnHeapBooleanTest 1
+ * @run main/othervm -XX:-UseOnStackReplacement -XX:+TieredCompilation -XX:TieredStopAtLevel=3 -Xbatch UnsafeOnHeapBooleanTest 20000
+ * @run main/othervm -XX:-UseOnStackReplacement -XX:-TieredCompilation -Xbatch UnsafeOnHeapBooleanTest 20000
+ */
+
+import java.lang.reflect.Field;
+import jdk.internal.misc.Unsafe;
+
+public class UnsafeOnHeapBooleanTest {
+    static short static_v;
+    static boolean bool0 = false, bool1 = false, result = false;
+    static Unsafe UNSAFE = Unsafe.getUnsafe();
+
+    public static void test() {
+        try {
+            // Write two bytes into the static field
+            // UnsafeOnHeapBooleanTest.static_v write two values. Both
+            // bytes correspond to the boolean value 'true'.
+            Field staticVField = UnsafeOnHeapBooleanTest.class.getDeclaredField("static_v");
+            Object base = UNSAFE.staticFieldBase(staticVField);
+            long offset = UNSAFE.staticFieldOffset(staticVField);
+            UNSAFE.putShort(base, offset, (short)0x0204);
+
+            // Read two bytes from the static field
+            // UnsafeOnHeapBooleanTest.static_v (as booleans).
+            bool0 = UNSAFE.getBoolean(base, offset + 0);
+            bool1 = UNSAFE.getBoolean(base, offset + 1);
+            result = bool0 & bool1;
+        } catch (NoSuchFieldException e) {
+            throw new RuntimeException("### Test failure: static field UnsafeOnHeapBooleanTest.static_v was not found");
+        }
+    }
+
+    public static void main(String args[]) {
+        System.out.println("### Test started");
+
+        if (args.length != 1) {
+            throw new RuntimeException("### Test failure: test called with incorrect number of arguments");
+        }
+
+        try {
+            for (int i = 0; i < Integer.parseInt(args[0]); i++) {
+                test();
+            }
+
+            // Check if the two 'true' boolean values were normalized
+            // (i.e., reduced from the range 1...255 to 1).
+            if (!bool0 || !bool1 || !result) {
+                System.out.println("Some of the results below are wrong");
+                System.out.println("bool0 is: " + bool0);
+                System.out.println("bool1 is: " + bool1);
+                System.out.println("bool0 & bool1 is: " + result);
+                System.out.println("===================================");
+                throw new RuntimeException("### Test failed");
+            } else {
+                System.out.println("Test generated correct results");
+                System.out.println("bool0 is: " + bool0);
+                System.out.println("bool1 is: " + bool1);
+                System.out.println("bool0 & bool1 is: " + result);
+                System.out.println("===================================");
+            }
+        } catch (NumberFormatException e) {
+            throw new RuntimeException("### Test failure: test called with incorrectly formatted parameter");
+        }
+
+        System.out.println("### Test passed");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/unsafe/UnsafeSmallOffsetBooleanAccessTest.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8161720
+ * @modules java.base/jdk.internal.misc
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -Xbatch -XX:-TieredCompilation UnsafeSmallOffsetBooleanAccessTest
+ * @run main/othervm -Xbatch UnsafeSmallOffsetBooleanAccessTest
+ */
+
+import java.util.Random;
+import jdk.internal.misc.Unsafe;
+
+public class UnsafeSmallOffsetBooleanAccessTest {
+    static final Unsafe UNSAFE = Unsafe.getUnsafe();
+    static final long F_OFFSET;
+    static final Random random = new Random();
+
+    static {
+        try {
+            F_OFFSET = UNSAFE.objectFieldOffset(T.class.getDeclaredField("f"));
+            System.out.println("The offset is: " + F_OFFSET);
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+    }
+
+    static class T {
+        boolean f;
+    }
+
+    // Always return false in a way that is not obvious to the compiler.
+    public static boolean myRandom() {
+        if (random.nextInt(101) > 134) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    public static boolean test(T t) {
+        boolean result = false;
+        for (int i = 0; i < 20000; i++) {
+            boolean random = myRandom();
+            // If myRandom() returns false, access t.f.
+            //
+            // If myRandom() returns true, access virtual address
+            // F_OFFSET. That address is most likely not mapped,
+            // therefore the access will most likely cause a
+            // crash. We're not concerned about that, though, because
+            // myRandom() always returns false. However, the C2
+            // compiler avoids normalization of the value returned by
+            // getBoolean in this case.
+            result = UNSAFE.getBoolean(myRandom() ? null : t, F_OFFSET);
+        }
+        return result;
+    }
+
+    public static void main(String[] args) {
+        T t = new T();
+        UNSAFE.putBoolean(t, F_OFFSET, true);
+        System.out.println("The result for t is: " + test(t));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/TestAgeOutput.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test TestAgeOutput
+ * @bug 8164936
+ * @summary Check that collectors using age table based aging print an age table even for the first garbage collection
+ * @key gc
+ * @requires vm.gc=="null"
+ * @modules java.base/jdk.internal.misc
+ * @library /test/lib
+ * @build sun.hotspot.WhiteBox
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -XX:+UseSerialGC TestAgeOutput UseSerialGC
+ * @run main/othervm -XX:+UseConcMarkSweepGC TestAgeOutput UseConcMarkSweepGC
+ * @run main/othervm -XX:+UseG1GC TestAgeOutput UseG1GC
+ */
+
+import sun.hotspot.WhiteBox;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import jdk.test.lib.Platform;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+import static jdk.test.lib.Asserts.*;
+
+public class TestAgeOutput {
+
+    public static void checkPattern(String pattern, String what) throws Exception {
+        Pattern r = Pattern.compile(pattern);
+        Matcher m = r.matcher(what);
+
+        if (!m.find()) {
+            throw new RuntimeException("Could not find pattern " + pattern + " in output");
+        }
+    }
+
+    public static void runTest(String gcArg) throws Exception {
+        final String[] arguments = {
+            "-Xbootclasspath/a:.",
+            "-XX:+UnlockExperimentalVMOptions",
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:+WhiteBoxAPI",
+            "-XX:+" + gcArg,
+            "-Xmx10M",
+            "-Xlog:gc+age=trace",
+            GCTest.class.getName()
+            };
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(arguments);
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+        output.shouldHaveExitValue(0);
+
+        System.out.println(output.getStdout());
+
+        String stdout = output.getStdout();
+
+        checkPattern(".*GC\\(0\\) .*Desired survivor size.*", stdout);
+        checkPattern(".*GC\\(0\\) .*Age table with threshold.*", stdout);
+        checkPattern(".*GC\\(0\\) .*- age   1:.*", stdout);
+    }
+
+    public static void main(String[] args) throws Exception {
+        runTest(args[0]);
+    }
+
+    static class GCTest {
+        private static final WhiteBox WB = WhiteBox.getWhiteBox();
+
+        public static Object holder;
+
+        public static void main(String [] args) {
+            holder = new byte[100];
+            WB.youngGC();
+            System.out.println(holder);
+        }
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/TestNumWorkerOutput.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test TestNumWorkerOutput
+ * @bug 8165292
+ * @summary Check that when PrintGCDetails is enabled, gc,task output is printed only once per collection.
+ * @key gc
+ * @requires vm.gc=="null"
+ * @modules java.base/jdk.internal.misc
+ * @library /test/lib
+ * @build sun.hotspot.WhiteBox
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -XX:+UseConcMarkSweepGC TestNumWorkerOutput UseConcMarkSweepGC
+ * @run main/othervm -XX:+UseG1GC TestNumWorkerOutput UseG1GC
+ */
+
+import sun.hotspot.WhiteBox;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import jdk.test.lib.Platform;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+import static jdk.test.lib.Asserts.*;
+
+public class TestNumWorkerOutput {
+
+    public static void checkPatternOnce(String pattern, String what) throws Exception {
+        Pattern r = Pattern.compile(pattern);
+        Matcher m = r.matcher(what);
+
+        if (!m.find()) {
+            throw new RuntimeException("Could not find pattern " + pattern + " in output");
+        }
+        if (m.find()) {
+            throw new RuntimeException("Could find pattern " + pattern + " in output more than once");
+        }
+    }
+
+    public static void runTest(String gcArg) throws Exception {
+        final String[] arguments = {
+            "-Xbootclasspath/a:.",
+            "-XX:+UnlockExperimentalVMOptions",
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:+WhiteBoxAPI",
+            "-XX:+" + gcArg,
+            "-Xmx10M",
+            "-XX:+PrintGCDetails",
+            GCTest.class.getName()
+            };
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(arguments);
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+        output.shouldHaveExitValue(0);
+
+        System.out.println(output.getStdout());
+
+        String stdout = output.getStdout();
+
+        checkPatternOnce(".*[info.*].*[gc,task.*].*GC\\(0\\) .*Using \\d+ workers of \\d+ for evacuation.*", stdout);
+    }
+
+    public static void main(String[] args) throws Exception {
+        runTest(args[0]);
+    }
+
+    static class GCTest {
+        private static final WhiteBox WB = WhiteBox.getWhiteBox();
+
+        public static Object holder;
+
+        public static void main(String [] args) {
+            holder = new byte[100];
+            WB.youngGC();
+            System.out.println(holder);
+        }
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/class_unloading/TestClassUnloadingDisabled.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reqserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key gc
+ * @bug 8114823
+ * @requires vm.gc == null
+ * @requires vm.opt.ExplicitGCInvokesConcurrent != true
+ * @requires vm.opt.ClassUnloading != true
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ * @build sun.hotspot.WhiteBox
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ *                              sun.hotspot.WhiteBox$WhiteBoxPermission
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:-ClassUnloading -XX:+UseG1GC TestClassUnloadingDisabled
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:-ClassUnloading -XX:+UseSerialGC TestClassUnloadingDisabled
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:-ClassUnloading -XX:+UseParallelGC TestClassUnloadingDisabled
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:-ClassUnloading -XX:+UseConcMarkSweepGC TestClassUnloadingDisabled
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import sun.hotspot.WhiteBox;
+
+import static jdk.test.lib.Asserts.*;
+
+public class TestClassUnloadingDisabled {
+    public static void main(String args[]) throws Exception {
+        final WhiteBox wb = WhiteBox.getWhiteBox();
+        // Fetch the dir where the test class and the class
+        // to be loaded resides.
+        String classDir = TestClassUnloadingDisabled.class.getProtectionDomain().getCodeSource().getLocation().getPath();
+        String className = "ClassToLoadUnload";
+
+        assertFalse(wb.isClassAlive(className), "Should not be loaded yet");
+
+        // The NoPDClassLoader handles loading classes in the test directory
+        // and loads them without a protection domain, which in some cases
+        // keeps the class live regardless of marking state.
+        NoPDClassLoader nopd = new NoPDClassLoader(classDir);
+        nopd.loadClass(className);
+
+        assertTrue(wb.isClassAlive(className), "Class should be loaded");
+
+        // Clear the class-loader, class and object references to make
+        // class unloading possible.
+        nopd = null;
+
+        System.gc();
+        assertTrue(wb.isClassAlive(className), "Class should not have ben unloaded");
+    }
+}
+
+class NoPDClassLoader extends ClassLoader {
+    String path;
+
+    NoPDClassLoader(String path) {
+        this.path = path;
+    }
+
+    public Class<?> loadClass(String name) throws ClassNotFoundException {
+        byte[] cls = null;
+        File f = new File(path,name + ".class");
+
+        // Delegate class loading if class not present in the given
+        // directory.
+        if (!f.exists()) {
+            return super.loadClass(name);
+        }
+
+        try {
+            Path path = Paths.get(f.getAbsolutePath());
+            cls = Files.readAllBytes(path);
+        } catch (IOException e) {
+            throw new ClassNotFoundException(name);
+        }
+
+        // Define class with no protection domain and resolve it.
+        return defineClass(name, cls, 0, cls.length, null);
+    }
+}
+
+class ClassToLoadUnload {
+}
--- a/test/gc/testlibrary/Helpers.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/gc/testlibrary/Helpers.java	Tue Sep 13 18:19:05 2016 +0200
@@ -32,7 +32,6 @@
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.nio.file.Paths;
 
 public class Helpers {
 
@@ -124,20 +123,13 @@
      */
     public static String generate(String className, String superClass, String constructor, long fieldCount) {
 
-        StringBuilder builder = new StringBuilder();
-        builder.append(String.format("public class %s%s {\n", className, superClass == null ? ""
-                : " extends " + superClass));
-
-        if (constructor != null) {
-            builder.append(constructor);
-        }
-
-        for (int i = 0; i < fieldCount; ++i) {
-            builder.append(String.format("long f%d;\n", i));
-        }
-
-        builder.append("}\n");
-        return builder.toString();
+        return new StringBuilder()
+                .append(String.format("public class %s%s {\n", className, superClass == null ? ""
+                        : " extends " + superClass))
+                .append(constructor == null ? "" : constructor)
+                .append(fieldsGenerator(fieldCount))
+                .append("}\n")
+                .toString();
     }
 
     /**
@@ -212,50 +204,9 @@
                                                   Path workDir, String prefix)
             throws IOException, ClassNotFoundException {
 
-        if (instanceSize % SIZE_OF_LONG != 0L) {
-            throw new Error(String.format("Test bug: only sizes aligned by 8 bytes are supported and %d was specified",
-                    instanceSize));
-        }
+        generateByTemplateAndCompile(className, null, "public class ${ClassName} extends ${BaseClass} {\n${Fields}}\n",
+                "", instanceSize, workDir, prefix);
 
-        long instanceSizeWithoutObjectHeader = instanceSize - WhiteBox.getWhiteBox().getObjectSize(new Object());
-
-        int generatedClassesCount;
-        int fieldsInLastClassCount;
-
-        int sizeOfLastFile = (int) (instanceSizeWithoutObjectHeader
-                % (MAXIMUM_AMOUNT_OF_FIELDS_IN_CLASS * SIZE_OF_LONG));
-
-        if (sizeOfLastFile != 0) {
-            generatedClassesCount = (int) instanceSizeWithoutObjectHeader
-                    / (MAXIMUM_AMOUNT_OF_FIELDS_IN_CLASS * SIZE_OF_LONG) + 1;
-            fieldsInLastClassCount = sizeOfLastFile / SIZE_OF_LONG;
-        } else {
-            generatedClassesCount = (int) instanceSizeWithoutObjectHeader
-                    / (MAXIMUM_AMOUNT_OF_FIELDS_IN_CLASS * SIZE_OF_LONG);
-            fieldsInLastClassCount = MAXIMUM_AMOUNT_OF_FIELDS_IN_CLASS;
-        }
-
-        for (int i = 0; i < generatedClassesCount; i++) {
-            // for the last generated class we use specified class name
-            String clsName = (i == generatedClassesCount - 1) ? className : prefix + i;
-
-            // If we already have a file with the same name we do not create it again
-            if (Files.notExists(Paths.get(clsName + ".java"))) {
-                Helpers.compileClass(clsName, workDir,
-                        Helpers.generate(
-                                clsName,
-                                // for first generated class we don't have 'extends'
-                                (i == 0 ? null : prefix + (i - 1)),
-                                null,
-                                // for the last generated class we use different field count
-                                (i == generatedClassesCount - 1) ? fieldsInLastClassCount
-                                        : MAXIMUM_AMOUNT_OF_FIELDS_IN_CLASS));
-            } else {
-                System.out.println("Class " + clsName +
-                        ".java already exists, skipping class' generation and compilation");
-            }
-
-        }
         return classLoader.loadClass(className);
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/native/classfile/test_AltHashing.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+#include "precompiled.hpp"
+#include "classfile/altHashing.hpp"
+#include "unittest.hpp"
+
+// Internal test for alternate hashing.  Translated from JDK version
+// test/sun/misc/Hashing.java
+static const jbyte ONE_BYTE[] = {(jbyte) 0x80};
+static const jbyte TWO_BYTE[] = {(jbyte) 0x80, (jbyte) 0x81};
+static const jchar ONE_CHAR[] = {(jchar) 0x8180};
+static const jbyte THREE_BYTE[] = {(jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82};
+static const jbyte FOUR_BYTE[] = {(jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82, (jbyte) 0x83};
+static const jchar TWO_CHAR[] = {(jchar) 0x8180, (jchar) 0x8382};
+static const jint ONE_INT[] = {(jint) 0x83828180};
+static const jbyte SIX_BYTE[] = {(jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82, (jbyte) 0x83, (jbyte) 0x84, (jbyte) 0x85};
+static const jchar THREE_CHAR[] = {(jchar) 0x8180, (jchar) 0x8382, (jchar) 0x8584};
+static const jbyte EIGHT_BYTE[] = {
+  (jbyte) 0x80, (jbyte) 0x81, (jbyte) 0x82,
+  (jbyte) 0x83, (jbyte) 0x84, (jbyte) 0x85,
+  (jbyte) 0x86, (jbyte) 0x87
+};
+static const jchar FOUR_CHAR[] = {
+  (jchar) 0x8180, (jchar) 0x8382,
+  (jchar) 0x8584, (jchar) 0x8786
+};
+
+static const jint TWO_INT[] = {(jint) 0x83828180, (jint) 0x87868584};
+static const juint MURMUR3_32_X86_CHECK_VALUE = 0xB0F57EE3;
+
+class AltHashingTest : public ::testing::Test {
+ public:
+
+  static juint murmur3_32(const int* data, int len) {
+    return AltHashing::murmur3_32(data, len);
+  }
+};
+
+TEST_F(AltHashingTest, murmur3_32_byte_array_test) {
+  jbyte vector[256];
+  jbyte hashes[4 * 256];
+
+  for (int i = 0; i < 256; i++) {
+    vector[i] = (jbyte) i;
+  }
+
+  // Hash subranges {}, {0}, {0,1}, {0,1,2}, ..., {0,...,255}
+  for (int i = 0; i < 256; i++) {
+    juint hash = AltHashing::murmur3_32(256 - i, vector, i);
+    hashes[i * 4] = (jbyte) hash;
+    hashes[i * 4 + 1] = (jbyte) (hash >> 8);
+    hashes[i * 4 + 2] = (jbyte) (hash >> 16);
+    hashes[i * 4 + 3] = (jbyte) (hash >> 24);
+  }
+
+  // hash to get const result.
+  juint final_hash = AltHashing::murmur3_32(0, hashes, 4 * 256);
+
+  ASSERT_EQ(MURMUR3_32_X86_CHECK_VALUE, final_hash)
+          << "Calculated hash result not as expected.";
+}
+
+TEST_F(AltHashingTest, equivalent_hashes_test) {
+  juint jbytes, jchars, ints;
+
+  jbytes = AltHashing::murmur3_32(0, TWO_BYTE, 2);
+  jchars = AltHashing::murmur3_32(0, ONE_CHAR, 1);
+  ASSERT_EQ(jbytes, jchars) << "Hashes did not match.";
+
+  jbytes = AltHashing::murmur3_32(0, FOUR_BYTE, 4);
+  jchars = AltHashing::murmur3_32(0, TWO_CHAR, 2);
+  ints = AltHashingTest::murmur3_32(ONE_INT, 1);
+
+  ASSERT_EQ(jbytes, jchars) << "Hashes did not match.";
+  ASSERT_EQ(jbytes, ints) << "Hashes did not match.";
+
+  jbytes = AltHashing::murmur3_32(0, SIX_BYTE, 6);
+  jchars = AltHashing::murmur3_32(0, THREE_CHAR, 3);
+  ASSERT_EQ(jbytes, jchars) << "Hashes did not match.";
+
+  jbytes = AltHashing::murmur3_32(0, EIGHT_BYTE, 8);
+  jchars = AltHashing::murmur3_32(0, FOUR_CHAR, 4);
+  ints = AltHashingTest::murmur3_32(TWO_INT, 2);
+
+  ASSERT_EQ(jbytes, jchars) << "Hashes did not match.";
+  ASSERT_EQ(jbytes, ints) << "Hashes did not match.";
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/native/gc/g1/test_g1CodeCacheRemSet.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include "precompiled.hpp"
+#include "gc/g1/g1CodeRootSetTable.hpp"
+#include "gc/g1/g1CodeCacheRemSet.hpp"
+#include "unittest.hpp"
+
+class G1CodeRootSetTest : public ::testing::Test {
+ public:
+
+  size_t threshold() {
+    return G1CodeRootSet::Threshold;
+  }
+
+  G1CodeRootSetTable* purge_list() {
+    return G1CodeRootSetTable::_purge_list;
+  }
+};
+
+TEST_VM_F(G1CodeRootSetTest, g1_code_cache_rem_set) {
+  G1CodeRootSet root_set;
+
+  ASSERT_TRUE(root_set.is_empty()) << "Code root set must be initially empty "
+          "but is not.";
+
+  ASSERT_EQ(G1CodeRootSet::static_mem_size(), sizeof (void*)) <<
+          "The code root set's static memory usage is incorrect, "
+          << G1CodeRootSet::static_mem_size() << " bytes";
+
+  root_set.add((nmethod*) 1);
+  ASSERT_EQ(root_set.length(), (size_t) 1) << "Added exactly one element, but"
+          " set contains " << root_set.length() << " elements";
+
+  const size_t num_to_add = (size_t) threshold() + 1;
+
+  for (size_t i = 1; i <= num_to_add; i++) {
+    root_set.add((nmethod*) 1);
+  }
+  ASSERT_EQ(root_set.length(), (size_t) 1)
+          << "Duplicate detection should not have increased the set size but "
+          << "is " << root_set.length();
+
+  for (size_t i = 2; i <= num_to_add; i++) {
+    root_set.add((nmethod*) (uintptr_t) (i));
+  }
+
+  ASSERT_EQ(root_set.length(), num_to_add)
+          << "After adding in total " << num_to_add << " distinct code roots, "
+          "they need to be in the set, but there are only " << root_set.length();
+
+  ASSERT_NE(purge_list(), (G1CodeRootSetTable*) NULL)
+          << "should have grown to large hashtable";
+
+  size_t num_popped = 0;
+  for (size_t i = 1; i <= num_to_add; i++) {
+    bool removed = root_set.remove((nmethod*) i);
+    if (removed) {
+      num_popped += 1;
+    } else {
+      break;
+    }
+  }
+  ASSERT_EQ(num_popped, num_to_add)
+          << "Managed to pop " << num_popped << " code roots, but only "
+          << num_to_add << " were added";
+  ASSERT_NE(purge_list(), (G1CodeRootSetTable*) NULL)
+          << "should have grown to large hashtable";
+
+  G1CodeRootSet::purge();
+
+  ASSERT_EQ(purge_list(), (G1CodeRootSetTable*) NULL)
+          << "should have purged old small tables";
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/native/gc/g1/test_g1Predictions.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "gc/g1/g1Predictions.hpp"
+#include "unittest.hpp"
+
+static const double epsilon = 1e-6;
+
+// Some basic formula tests with confidence = 0.0
+TEST_VM(G1Predictions, basic_predictions) {
+  G1Predictions predictor(0.0);
+  TruncatedSeq s;
+
+  double p0 = predictor.get_new_prediction(&s);
+  ASSERT_LT(p0, epsilon) << "Initial prediction of empty sequence must be 0.0";
+
+  s.add(5.0);
+  double p1 = predictor.get_new_prediction(&s);
+  ASSERT_NEAR(p1, 5.0, epsilon);
+
+  for (int i = 0; i < 40; i++) {
+    s.add(5.0);
+  }
+  double p2 = predictor.get_new_prediction(&s);
+  ASSERT_NEAR(p2, 5.0, epsilon);
+}
+
+// The following tests checks that the initial predictions are based on
+// the average of the sequence and not on the stddev (which is 0).
+TEST_VM(G1Predictions, average_not_stdev_predictions) {
+  G1Predictions predictor(0.5);
+  TruncatedSeq s;
+
+  s.add(1.0);
+  double p1 = predictor.get_new_prediction(&s);
+  ASSERT_GT(p1, s.davg()) << "First prediction must be greater than average";
+
+  s.add(1.0);
+  double p2 = predictor.get_new_prediction(&s);
+  ASSERT_GT(p1, p2) << "First prediction must be greater than second";
+
+  s.add(1.0);
+  double p3 = predictor.get_new_prediction(&s);
+  ASSERT_GT(p2, p3) << "Second prediction must be greater than third";
+
+  s.add(1.0);
+  s.add(1.0); // Five elements are now in the sequence.
+  double p4 = predictor.get_new_prediction(&s);
+  ASSERT_LT(p4, p3) << "Fourth prediction must be smaller than third";
+  ASSERT_NEAR(p4, 1.0, epsilon);
+}
+
+// The following tests checks that initially prediction based on
+// the average is used, that gets overridden by the stddev prediction at
+// the end.
+TEST_VM(G1Predictions, average_stdev_predictions) {
+  G1Predictions predictor(0.5);
+  TruncatedSeq s;
+
+  s.add(0.5);
+  double p1 = predictor.get_new_prediction(&s);
+  ASSERT_GT(p1, s.davg()) << "First prediction must be greater than average";
+
+  s.add(0.2);
+  double p2 = predictor.get_new_prediction(&s);
+  ASSERT_GT(p1, p2) << "First prediction must be greater than second";
+
+  s.add(0.5);
+  double p3 = predictor.get_new_prediction(&s);
+  ASSERT_GT(p2, p3) << "Second prediction must be greater than third";
+
+  s.add(0.2);
+  s.add(2.0);
+  double p4 = predictor.get_new_prediction(&s);
+  ASSERT_GT(p4, p3) << "Fourth prediction must be greater than third";
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/native/gc/parallel/test_psAdaptiveSizePolicy.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "utilities/macros.hpp"
+#include "gc/parallel/psAdaptiveSizePolicy.hpp"
+#include "unittest.hpp"
+
+#if INCLUDE_ALL_GCS
+
+  TEST_VM(gc, oldFreeSpaceCalculation) {
+
+    struct TestCase {
+        size_t live;
+        uintx ratio;
+        size_t expectedResult;
+    };
+
+    TestCase test_cases[] = {
+                                {100, 20, 25},
+                                {100, 50, 100},
+                                {100, 60, 150},
+                                {100, 75, 300},
+                                {400, 20, 100},
+                                {400, 50, 400},
+                                {400, 60, 600},
+                                {400, 75, 1200},
+                            };
+
+    size_t array_len = sizeof(test_cases) / sizeof(TestCase);
+    for (size_t i = 0; i < array_len; ++i) {
+      ASSERT_EQ(PSAdaptiveSizePolicy::calculate_free_based_on_live(
+          test_cases[i].live, test_cases[i].ratio),
+          test_cases[i].expectedResult)
+          << " Calculation of free memory failed"
+          << " - Test case " << i << ": live = " << test_cases[i].live
+          << "; ratio = " << test_cases[i].ratio;
+    }
+  }
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/native/gc/shared/test_memset_with_concurrent_readers.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include "precompiled.hpp"
+#include <string.h>
+#include "utilities/globalDefinitions.hpp"
+#include <sstream>
+#include "gc/shared/memset_with_concurrent_readers.hpp"
+#include "unittest.hpp"
+
+#if INCLUDE_ALL_GCS
+
+static unsigned line_byte(const char* line, size_t i) {
+  return unsigned(line[i]) & 0xFF;
+}
+
+TEST(gc, memset_with_concurrent_readers) {
+  const size_t chunk_size = 8 * BytesPerWord;
+  const unsigned chunk_count = 4;
+  const size_t block_size = (chunk_count + 4) * chunk_size;
+  char block[block_size];
+  char clear_block[block_size];
+  char set_block[block_size];
+
+  // block format:
+  // 0: unused leading chunk
+  // 1: chunk written from start index to end of chunk
+  // ... nchunks fully written chunks
+  // N: chunk written from start of chunk to end index
+  // N+1: unused trailing chunk
+
+  const int clear_value = 0;
+  const int set_value = 0xAC;
+
+  memset(clear_block, clear_value, block_size);
+  memset(set_block, set_value, block_size);
+
+  for (unsigned nchunks = 0; nchunks <= chunk_count; ++nchunks) {
+    for (size_t start = 1; start <= chunk_size; ++start) {
+      for (size_t end = 0; end <= chunk_size; ++end) {
+        size_t set_start = chunk_size + start;
+        size_t set_end = (2 + nchunks) * chunk_size + end;
+        size_t set_size = set_end - set_start;
+
+        memset(block, clear_value, block_size);
+        memset_with_concurrent_readers(&block[set_start], set_value, set_size);
+        bool head_clear = !memcmp(clear_block, block, set_start);
+        bool middle_set = !memcmp(set_block, block + set_start, set_size);
+        bool tail_clear = !memcmp(clear_block, block + set_end, block_size - set_end);
+        if (!(head_clear && middle_set && tail_clear)) {
+          std::ostringstream err_stream;
+          err_stream << "*** memset_with_concurrent_readers failed: set start "
+                     << set_start << ", set end " << set_end << std::endl;
+          for (unsigned chunk = 0; chunk < (block_size / chunk_size); ++chunk) {
+            for (unsigned line = 0; line < (chunk_size / BytesPerWord); ++line) {
+
+              const char* lp = &block[chunk * chunk_size + line * BytesPerWord];
+
+              err_stream << std::dec << chunk << "," << line << ": " << std::hex
+                         << std::setw(2) << line_byte(lp, 0) << " "
+                         << std::setw(2) << line_byte(lp, 1) << "  "
+                         << std::setw(2) << line_byte(lp, 2) << " "
+                         << std::setw(2) << line_byte(lp, 3) << "  "
+                         << std::setw(2) << line_byte(lp, 4) << " "
+                         << std::setw(2) << line_byte(lp, 5) << "  "
+                         << std::setw(2) << line_byte(lp, 6) << " "
+                         << std::setw(2) << line_byte(lp, 7) << std::endl;
+            }
+          }
+          EXPECT_TRUE(head_clear) << "leading byte not clear";
+          EXPECT_TRUE(middle_set) << "memset byte not set";
+          EXPECT_TRUE(tail_clear) << "trailing bye not clear";
+          ASSERT_TRUE(head_clear && middle_set && tail_clear) << err_stream.str();
+        }
+      }
+    }
+  }
+}
+#endif
--- a/test/native/logging/test_logConfiguration.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/native/logging/test_logConfiguration.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -308,3 +308,30 @@
   EXPECT_TRUE(string_contains_substring(msg, "No tag set matches selection(s):"));
   EXPECT_TRUE(string_contains_substring(msg, invalid_tagset));
 }
+
+TEST_F(LogConfigurationTest, output_name_normalization) {
+  const char* patterns[] = { "%s", "file=%s", "\"%s\"", "file=\"%s\"" };
+  char buf[1 * K];
+  for (size_t i = 0; i < ARRAY_SIZE(patterns); i++) {
+    int ret = jio_snprintf(buf, sizeof(buf), patterns[i], TestLogFileName);
+    ASSERT_NE(-1, ret);
+    set_log_config(buf, "logging=trace");
+    EXPECT_TRUE(is_described("#2: "));
+    EXPECT_TRUE(is_described(TestLogFileName));
+    EXPECT_FALSE(is_described("#3: "))
+        << "duplicate file output due to incorrect normalization for pattern: " << patterns[i];
+  }
+
+  // Make sure prefixes are ignored when used within quotes
+  // (this should create a log with "file=" in its filename)
+  int ret = jio_snprintf(buf, sizeof(buf), "\"file=%s\"", TestLogFileName);
+  ASSERT_NE(-1, ret);
+  set_log_config(buf, "logging=trace");
+  EXPECT_TRUE(is_described("#3: ")) << "prefix within quotes not ignored as it should be";
+  set_log_config(buf, "all=off");
+
+  // Remove the extra log file created
+  ret = jio_snprintf(buf, sizeof(buf), "file=%s", TestLogFileName);
+  ASSERT_NE(-1, ret);
+  delete_file(buf);
+}
--- a/test/native/logging/test_logDecorations.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/native/logging/test_logDecorations.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -144,7 +144,7 @@
   reported_time.tm_hour = h;
   reported_time.tm_min = m;
   reported_time.tm_sec = s;
-  reported_time.tm_isdst = daylight;
+  reported_time.tm_isdst = -1; // let mktime deduce DST settings
   time_t reported_ts = mktime(&reported_time);
   expected_ts = mktime(localtime(&expected_ts));
   time_t diff = reported_ts - expected_ts;
--- a/test/native/logging/test_logFileOutput.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/native/logging/test_logFileOutput.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -29,7 +29,7 @@
 #include "utilities/globalDefinitions.hpp"
 #include "utilities/ostream.hpp"
 
-static const char* name = "testlog.pid%p.%t.log";
+static const char* name = "file=testlog.pid%p.%t.log";
 
 // Test parsing a bunch of valid file output options
 TEST(LogFileOutput, parse_valid) {
--- a/test/native/logging/test_logTagLevelExpression.cpp	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/native/logging/test_logTagLevelExpression.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -33,7 +33,7 @@
   const char* invalid_substr[] = {
     "=", "+", " ", "+=", "+=*", "*+", " +", "**", "++", ".", ",", ",," ",+",
     " *", "all+", "all*", "+all", "+all=Warning", "==Info", "=InfoWarning",
-    "BadTag+", "logging++", "logging*+", ",=", "gc+gc+gc+gc+gc+gc"
+    "BadTag+", "logging++", "logging*+", ",=", "gc+gc+"
   };
   const char* valid_expression[] = {
     "all", "gc", "gc,logging", "gc+logging", "logging+gc", "logging+gc,gc", "logging+gc*", "gc=trace",
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/native/utilities/test_utf8.cpp	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include "precompiled.hpp"
+#include "utilities/utf8.hpp"
+#include "unittest.hpp"
+
+TEST(utf8, length) {
+  char res[60];
+  jchar str[20];
+
+  for (int i = 0; i < 20; i++) {
+    str[i] = 0x0800; // char that is 2B in UTF-16 but 3B in UTF-8
+  }
+  str[19] = (jchar) '\0';
+
+  // The resulting string in UTF-8 is 3*19 bytes long, but should be truncated
+  UNICODE::as_utf8(str, 19, res, 10);
+  ASSERT_EQ(strlen(res), (size_t) 9) << "string should be truncated here";
+
+  UNICODE::as_utf8(str, 19, res, 18);
+  ASSERT_EQ(strlen(res), (size_t) 15) << "string should be truncated here";
+
+  UNICODE::as_utf8(str, 19, res, 20);
+  ASSERT_EQ(strlen(res), (size_t) 18) << "string should be truncated here";
+
+  // Test with an "unbounded" buffer
+  UNICODE::as_utf8(str, 19, res, INT_MAX);
+  ASSERT_EQ(strlen(res), (size_t) 3 * 19) << "string should end here";
+}
--- a/test/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java	Tue Sep 13 18:19:05 2016 +0200
@@ -89,20 +89,6 @@
         excludeTestMaxRange("CICompilerCount");
 
         /*
-         * JDK-8136766
-         * Temporarily remove ThreadStackSize from testing because Windows can set it to 0
-         * (for default OS size) but other platforms insist it must be greater than 0
-        */
-        excludeTestRange("ThreadStackSize");
-
-        /*
-         * Remove the flag controlling the size of the stack because the
-         * flag has direct influence on the physical memory usage of
-         * the VM.
-         */
-        allOptionsAsMap.remove("CompilerThreadStackSize");
-
-        /*
          * Exclude MallocMaxTestWords as it is expected to exit VM at small values (>=0)
          */
         excludeTestMinRange("MallocMaxTestWords");
@@ -124,6 +110,8 @@
         excludeTestMaxRange("OldSize");
         excludeTestMaxRange("ParallelGCThreads");
 
+        excludeTestMaxRange("CompilerThreadStackSize");
+        excludeTestMaxRange("ThreadStackSize");
         excludeTestMaxRange("VMThreadStackSize");
 
         /*
--- a/test/runtime/RedefineTests/RedefineCount.java	Tue Sep 13 11:04:29 2016 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 8164692
- * @summary Redefine previous_versions count goes negative
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- * @modules java.compiler
- *          java.instrument
- *          jdk.jartool/sun.tools.jar
- * @run main RedefineClassHelper
- * @run main/othervm -javaagent:redefineagent.jar -Xlog:redefine+class+iklass+add=trace,redefine+class+iklass+purge=trace RedefineCount
- */
-public class RedefineCount {
-
-    public static String newB =
-                "class RedefineCount$B {" +
-                "}";
-
-    static class B { }
-
-    public static void main(String[] args) throws Exception {
-
-        // Redefine a class and create some garbage
-        // Since there are no methods running, the previous version is never added to the
-        // previous_version_list and the count should stay zero and not go negative
-        RedefineClassHelper.redefineClass(B.class, newB);
-
-        for (int i = 0; i < 20 ; i++) {
-            String s = new String("some garbage");
-            System.gc();
-        }
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/RedefineTests/RedefinePreviousVersions.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8165246
+ * @summary Test has_previous_versions flag and processing during class unloading.
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * @modules java.compiler
+ *          java.instrument
+ *          jdk.jartool/sun.tools.jar
+ * @run main RedefineClassHelper
+ * @run main/othervm RedefinePreviousVersions test
+ */
+
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class RedefinePreviousVersions {
+
+    public static String newB =
+                "class RedefinePreviousVersions$B {" +
+                "}";
+
+    static class B { }
+
+    public static String newRunning =
+        "class RedefinePreviousVersions$Running {" +
+        "    public static volatile boolean stop = true;" +
+        "    static void localSleep() { }" +
+        "    public static void infinite() { }" +
+        "}";
+
+    static class Running {
+        public static volatile boolean stop = false;
+        static void localSleep() {
+          try{
+            Thread.currentThread().sleep(10);//sleep for 10 ms
+          } catch(InterruptedException ie) {
+          }
+        }
+
+        public static void infinite() {
+            while (!stop) { localSleep(); }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        if (args.length > 0) {
+
+            String jarFile = System.getProperty("test.src") + "/testcase.jar";
+
+            // java -javaagent:redefineagent.jar -Xlog:stuff RedefinePreviousVersions
+            ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( "-javaagent:redefineagent.jar",
+               "-Xlog:redefine+class+iklass+add=trace,redefine+class+iklass+purge=trace",
+               "RedefinePreviousVersions");
+            new OutputAnalyzer(pb.start())
+              .shouldContain("Class unloading: has_previous_versions = false")
+              .shouldContain("Class unloading: has_previous_versions = true")
+              .shouldHaveExitValue(0);
+            return;
+        }
+
+        // Redefine a class and create some garbage
+        // Since there are no methods running, the previous version is never added to the
+        // previous_version_list and the flag _has_previous_versions should stay false
+        RedefineClassHelper.redefineClass(B.class, newB);
+
+        for (int i = 0; i < 10 ; i++) {
+            String s = new String("some garbage");
+            System.gc();
+        }
+
+        // Start a class that has a method running
+        new Thread() {
+            public void run() {
+                Running.infinite();
+            }
+        }.start();
+
+        // Since a method of newRunning is running, this class should be added to the previous_version_list
+        // of Running, and _has_previous_versions should return true at class unloading.
+        RedefineClassHelper.redefineClass(Running.class, newRunning);
+
+        for (int i = 0; i < 10 ; i++) {
+            String s = new String("some garbage");
+            System.gc();
+        }
+
+        // purge should clean everything up, except Xcomp it might not.
+        Running.stop = true;
+
+        for (int i = 0; i < 10 ; i++) {
+            String s = new String("some garbage");
+            System.gc();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/Thread/TooSmallStackSize.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8140520
+ * @summary Setting small CompilerThreadStackSize, ThreadStackSize, and
+ * VMThreadStackSize values should result in an error message that shows
+ * the minimum stack size value for each thread type.
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ * @run main TooSmallStackSize
+ */
+
+/*
+ * The primary purpose of this test is to make sure we can run with a
+ * stack smaller than the minimum without crashing. Also this test will
+ * determine the minimum allowed stack size for the platform (as
+ * provided by the JVM error message when a very small stack is used),
+ * and then verify that the JVM can be launched with that stack size
+ * without a crash or any error messages.
+ *
+ * Note: The '-Xss<size>' and '-XX:ThreadStackSize=<k-bytes>' options
+ * both control Java thread stack size. This repo's version of the test
+ * exercises the '-XX:ThreadStackSize' VM option. The jdk repo's version
+ * of the test exercises the '-Xss' option.
+ */
+
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class TooSmallStackSize {
+    /* for debugging. Normally false. */
+    static final boolean verbose = false;
+    static final String CompilerThreadStackSizeString = "CompilerThreadStackSize";
+    static final String ThreadStackSizeString = "Java thread stack size";
+    static final String VMThreadStackSizeString = "VMThreadStackSize";
+
+    /*
+     * Returns the minimum stack size this platform will allowed based on the
+     * contents of the error message the JVM outputs when too small of a
+     * stack size was used.
+     *
+     * The testOutput argument must contain the result of having already run
+     * the JVM with too small of a stack size.
+     */
+    static String getMinStackAllowed(String testOutput) {
+        /*
+         * The JVM output will contain in one of the lines:
+         *   "The CompilerThreadStackSize specified is too small. Specify at least 100k"
+         *   "The Java thread stack size specified is too small. Specify at least 100k"
+         *   "The VMThreadStackSize specified is too small. Specify at least 100k"
+         * Although the actual size will vary. We need to extract this size
+         * string from the output and return it.
+         */
+        String matchStr = "Specify at least ";
+        int match_idx = testOutput.indexOf(matchStr);
+        if (match_idx >= 0) {
+            int size_start_idx = match_idx + matchStr.length();
+            int k_start_idx = testOutput.indexOf("k", size_start_idx);
+            // don't include the 'k'; the caller will have to
+            // add it back as needed.
+            return testOutput.substring(size_start_idx, k_start_idx);
+        }
+
+        System.out.println("Expect='" + matchStr + "'");
+        System.out.println("Actual: " + testOutput);
+        System.out.println("FAILED: Could not get the stack size from the output");
+        throw new RuntimeException("test fails");
+    }
+
+    /*
+     * Run the JVM with the specified stack size.
+     *
+     * Returns the minimum allowed stack size gleaned from the error message,
+     * if there is an error message. Otherwise returns the stack size passed in.
+     */
+    static String checkStack(String stackOption, String optionMesg, String stackSize) throws Exception {
+        String min_stack_allowed;
+
+        System.out.println("*** Testing " + stackOption + stackSize);
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            stackOption + stackSize,
+            // Uncomment the following to get log output
+            // that shows actual thread creation sizes.
+            // "-Xlog:os+thread",
+            "-version");
+
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+        if (verbose) {
+            System.out.println("stdout: " + output.getStdout());
+        }
+
+        if (output.getExitValue() == 0) {
+            // checkMinStackAllowed() is called with stackSize values
+            // that should be the minimum that works. This method,
+            // checkStack(), is called with stackSize values that
+            // should be too small and result in error messages.
+            // However, some platforms fix up a stackSize value that is
+            // too small into something that works so we have to allow
+            // for checkStack() calls that work.
+            System.out.println("PASSED: got exit_code == 0 with " + stackOption + stackSize);
+            min_stack_allowed = stackSize;
+        } else {
+            String expect = "The " + optionMesg + " specified is too small";
+            if (verbose) {
+                System.out.println("Expect='" + expect + "'");
+            }
+            output.shouldContain(expect);
+            min_stack_allowed = getMinStackAllowed(output.getStdout());
+
+            System.out.println("PASSED: got expected error message with " + stackOption + stackSize);
+        }
+
+        return min_stack_allowed;
+    }
+
+    /*
+     * Run the JVM with the minimum allowed stack size. This should always succeed.
+     */
+    static void checkMinStackAllowed(String stackOption, String optionMesg, String stackSize) throws Exception {
+        System.out.println("*** Testing " + stackOption + stackSize);
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            stackOption + stackSize,
+            // Uncomment the following to get log output
+            // that shows actual thread creation sizes.
+            // "-Xlog:os+thread",
+            "-version");
+
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldHaveExitValue(0);
+
+        System.out.println("PASSED: VM launched with " + stackOption + stackSize);
+    }
+
+    public static void main(String... args) throws Exception {
+        /*
+         * The result of a 16k stack size should be a quick exit with a complaint
+         * that the stack size is too small. However, for some win32 builds, the
+         * stack is always at least 64k, and this also sometimes is the minimum
+         * allowed size, so we won't see an error in this case.
+         *
+         * This test case will also produce a crash on some platforms if the fix
+         * for 6762191 is not yet in place.
+         */
+        checkStack("-XX:ThreadStackSize=", ThreadStackSizeString, "16");
+
+        /*
+         * Try with a 32k stack size, which is the size that the launcher will
+         * set to if you try setting to anything smaller. This should produce the same
+         * result as setting to 16k if the fix for 6762191 is in place.
+         */
+        String min_stack_allowed = checkStack("-XX:ThreadStackSize=", ThreadStackSizeString, "32");
+
+        /*
+         * Try again with a the minimum stack size that was given in the error message
+         */
+        checkMinStackAllowed("-XX:ThreadStackSize=", ThreadStackSizeString, min_stack_allowed);
+
+        /*
+         * Now redo the same tests with the compiler thread stack size:
+         */
+        checkStack("-XX:CompilerThreadStackSize=", CompilerThreadStackSizeString, "16");
+        min_stack_allowed = checkStack("-XX:CompilerThreadStackSize=", CompilerThreadStackSizeString, "32");
+        checkMinStackAllowed("-XX:CompilerThreadStackSize=", CompilerThreadStackSizeString, min_stack_allowed);
+
+        /*
+         * Now redo the same tests with the VM thread stack size:
+         */
+        checkStack("-XX:VMThreadStackSize=", VMThreadStackSizeString, "16");
+        min_stack_allowed = checkStack("-XX:VMThreadStackSize=", VMThreadStackSizeString, "32");
+        checkMinStackAllowed("-XX:VMThreadStackSize=", VMThreadStackSizeString, min_stack_allowed);
+    }
+}
--- a/test/runtime/Unsafe/NestedUnsafe.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/runtime/Unsafe/NestedUnsafe.java	Tue Sep 13 18:19:05 2016 +0200
@@ -80,7 +80,7 @@
             "            throw new RuntimeException(\"Exception: \" + ex.toString()); " +
             "        } " +
             "} } ",
-            "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED");
+            "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED");
         Class klass2 = unsafe.defineAnonymousClass(NestedUnsafe.class, klassbuf2, new Object[0]);
         try {
             klass2.getMethod("doit").invoke(null);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/defineAnonClass/DefineAnon.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test DefineAnon
+ * @bug 8058575
+ * @library /testlibrary
+ * @modules java.base/jdk.internal.org.objectweb.asm
+ *          java.management
+ * @compile -XDignore.symbol.file=true DefineAnon.java
+ * @run main/othervm p1.DefineAnon
+ */
+
+package p1;
+
+import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.MethodVisitor;
+import jdk.internal.org.objectweb.asm.Opcodes;
+import sun.misc.Unsafe;
+
+
+class T {
+    static           protected void test0() { System.out.println("test0 (public)"); }
+    static           protected void test1() { System.out.println("test1 (protected)"); }
+    static /*package-private*/ void test2() { System.out.println("test2 (package)"); }
+    static             private void test3() { System.out.println("test3 (private)"); }
+}
+
+public class DefineAnon {
+
+    private static Unsafe getUnsafe() {
+        try {
+            java.lang.reflect.Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
+            singleoneInstanceField.setAccessible(true);
+            return (Unsafe) singleoneInstanceField.get(null);
+        } catch (Throwable ex) {
+            throw new RuntimeException("Was unable to get Unsafe instance.");
+        }
+    }
+
+    static Unsafe UNSAFE = DefineAnon.getUnsafe();
+
+    static Class<?> getAnonClass(Class<?> hostClass, final String className) {
+        final String superName = "java/lang/Object";
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
+        cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, className, null, superName, null);
+
+        MethodVisitor mv = cw.visitMethod(Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC, "test", "()V", null, null);
+        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "p1/T", "test0", "()V", false);
+        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "p1/T", "test1", "()V", false);
+        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "p1/T", "test2", "()V", false);
+        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "p1/T", "test3", "()V", false);
+        mv.visitInsn(Opcodes.RETURN);
+        mv.visitMaxs(0, 0);
+        mv.visitEnd();
+
+        final byte[] classBytes = cw.toByteArray();
+        Class<?> invokerClass = UNSAFE.defineAnonymousClass(hostClass, classBytes, new Object[0]);
+        UNSAFE.ensureClassInitialized(invokerClass);
+        return invokerClass;
+    }
+
+    public static void main(String[] args) throws Throwable {
+        Throwable fail = null;
+
+        // Anonymous class has the privileges of its host class, so test[0123] should all work.
+        System.out.println("Injecting from the same package (p1):");
+        Class<?> p1cls = getAnonClass(T.class, "p1/AnonClass");
+        try {
+            p1cls.getMethod("test").invoke(null);
+        } catch (Throwable ex) {
+            ex.printStackTrace();
+            fail = ex;  // throw this to make test fail, since subtest failed
+        }
+
+        // Anonymous class has different package name from host class.  Should throw
+        // IllegalArgumentException.
+        System.out.println("Injecting from the wrong package (p2):");
+        try {
+            Class<?> p2cls = getAnonClass(DefineAnon.class, "p2/AnonClass");
+            p2cls.getMethod("test").invoke(null);
+            System.out.println("Failed, did not get expected IllegalArgumentException");
+        } catch (java.lang.IllegalArgumentException e) {
+            if (e.getMessage().contains("Host class p1/DefineAnon and anonymous class p2/AnonClass")) {
+                System.out.println("Got expected IllegalArgumentException: " + e.getMessage());
+            } else {
+                throw new RuntimeException("Unexpected message: " + e.getMessage());
+            }
+        } catch (Throwable ex) {
+            ex.printStackTrace();
+            fail = ex;  // throw this to make test fail, since subtest failed
+        }
+
+        // Inject a class in the unnamed package into p1.T.  It should be able
+        // to access all methods in p1.T.
+        System.out.println("Injecting unnamed package into correct host class:");
+        try {
+            Class<?> p3cls = getAnonClass(T.class, "AnonClass");
+            p3cls.getMethod("test").invoke(null);
+        } catch (Throwable ex) {
+            ex.printStackTrace();
+            fail = ex;  // throw this to make test fail, since subtest failed
+        }
+
+        // Try using an array class as the host class.  This should throw IllegalArgumentException.
+        try {
+            Class<?> p3cls = getAnonClass(String[].class, "AnonClass");
+            throw new RuntimeException("Expected IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException ex) {
+        }
+
+        if (fail != null) throw fail;  // make test fail, since subtest failed
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/defineAnonClass/NestedUnsafe.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8058575
+ * @summary Creates an anonymous class inside of an anonymous class.
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ *          java.compiler
+ *          java.management
+ * @run main p.NestedUnsafe
+ */
+
+package p;
+
+import java.security.ProtectionDomain;
+import java.io.InputStream;
+import java.lang.*;
+import jdk.test.lib.*;
+import jdk.internal.misc.Unsafe;
+import jdk.test.lib.unsafe.UnsafeHelper;
+
+
+// Test that an anonymous class in package 'p' cannot define its own anonymous class
+// in another package.
+public class NestedUnsafe {
+    // The String concatenation should create the nested anonymous class.
+    static byte klassbuf[] = InMemoryJavaCompiler.compile("q.TestClass",
+        "package q; " +
+        "public class TestClass { " +
+        "    public static void concat(String one, String two) throws Throwable { " +
+        "        System.out.println(one + two);" +
+        " } } ");
+
+    public static void main(String args[]) throws Exception {
+        Unsafe unsafe = UnsafeHelper.getUnsafe();
+
+        // The anonymous class calls defineAnonymousClass creating a nested anonymous class.
+        byte klassbuf2[] = InMemoryJavaCompiler.compile("p.TestClass2",
+            "package p; " +
+            "import jdk.internal.misc.Unsafe; " +
+            "public class TestClass2 { " +
+            "    public static void doit() throws Throwable { " +
+            "        Unsafe unsafe = jdk.internal.misc.Unsafe.getUnsafe(); " +
+            "        Class klass2 = unsafe.defineAnonymousClass(TestClass2.class, p.NestedUnsafe.klassbuf, new Object[0]); " +
+            "        unsafe.ensureClassInitialized(klass2); " +
+            "        Class[] dArgs = new Class[2]; " +
+            "        dArgs[0] = String.class; " +
+            "        dArgs[1] = String.class; " +
+            "        try { " +
+            "            klass2.getMethod(\"concat\", dArgs).invoke(null, \"CC\", \"DD\"); " +
+            "        } catch (Throwable ex) { " +
+            "            throw new RuntimeException(\"Exception: \" + ex.toString()); " +
+            "        } " +
+            "} } ",
+            "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED");
+
+        Class klass2 = unsafe.defineAnonymousClass(p.NestedUnsafe.class, klassbuf2, new Object[0]);
+        try {
+            klass2.getMethod("doit").invoke(null);
+            throw new RuntimeException("Expected exception not thrown");
+        } catch (Throwable ex) {
+            Throwable iae = ex.getCause();
+            if (!iae.toString().contains(
+                "IllegalArgumentException: Host class p/NestedUnsafe and anonymous class q/TestClass")) {
+                throw new RuntimeException("Exception: " + iae.toString());
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/defineAnonClass/NestedUnsafe2.java	Tue Sep 13 18:19:05 2016 +0200
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8058575
+ * @summary Creates an anonymous class inside of an anonymous class.
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ *          java.compiler
+ *          java.management
+ * @run main p.NestedUnsafe2
+ */
+
+package p;
+
+import java.security.ProtectionDomain;
+import java.io.InputStream;
+import java.lang.*;
+import jdk.test.lib.*;
+import jdk.internal.misc.Unsafe;
+import jdk.test.lib.unsafe.UnsafeHelper;
+
+
+// Test that an anonymous class that gets put in its host's package cannot define
+// an anonymous class in another package.
+public class NestedUnsafe2 {
+    // The String concatenation should create the nested anonymous class.
+    public static byte klassbuf[] = InMemoryJavaCompiler.compile("q.TestClass",
+        "package q; " +
+        "public class TestClass { " +
+        "    public static void concat(String one, String two) throws Throwable { " +
+        "        System.out.println(one + two);" +
+        " } } ");
+
+    public static void main(String args[]) throws Exception {
+        Unsafe unsafe = UnsafeHelper.getUnsafe();
+
+        // The anonymous class calls defineAnonymousClass creating a nested anonymous class.
+        byte klassbuf2[] = InMemoryJavaCompiler.compile("TestClass2",
+            "import jdk.internal.misc.Unsafe; " +
+            "public class TestClass2 { " +
+            "    public static void doit() throws Throwable { " +
+            "        Unsafe unsafe = jdk.internal.misc.Unsafe.getUnsafe(); " +
+            "        Class klass2 = unsafe.defineAnonymousClass(TestClass2.class, p.NestedUnsafe2.klassbuf, new Object[0]); " +
+            "        unsafe.ensureClassInitialized(klass2); " +
+            "        Class[] dArgs = new Class[2]; " +
+            "        dArgs[0] = String.class; " +
+            "        dArgs[1] = String.class; " +
+            "        try { " +
+            "            klass2.getMethod(\"concat\", dArgs).invoke(null, \"CC\", \"DD\"); " +
+            "        } catch (Throwable ex) { " +
+            "            throw new RuntimeException(\"Exception: \" + ex.toString()); " +
+            "        } " +
+            "} } ",
+            "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED");
+
+        Class klass2 = unsafe.defineAnonymousClass(p.NestedUnsafe2.class, klassbuf2, new Object[0]);
+        try {
+            klass2.getMethod("doit").invoke(null);
+            throw new RuntimeException("Expected exception not thrown");
+        } catch (Throwable ex) {
+            Throwable iae = ex.getCause();
+            if (!iae.toString().contains(
+                "IllegalArgumentException: Host class p/NestedUnsafe2 and anonymous class q/TestClass")) {
+                throw new RuntimeException("Exception: " + iae.toString());
+            }
+        }
+    }
+}
--- a/test/runtime/modules/ModuleOptionsTest.java	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/runtime/modules/ModuleOptionsTest.java	Tue Sep 13 18:19:05 2016 +0200
@@ -24,8 +24,8 @@
 /*
  * @test
  * @bug 8136930
- * @summary Test that the VM only recognizes the last specified --add-modules
- *          and --list-modules options
+ * @summary Test that the VM only recognizes the last specified --list-modules
+ *          options but accumulates --add-module values.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  */
@@ -38,14 +38,16 @@
 
     public static void main(String[] args) throws Exception {
 
-        // Test that last --add-modules is the only one recognized.  No exception
-        // should be thrown.
+        // Test that multiple --add-modules options are cumulative, not last one wins.
+        // An exception should be thrown because module i_dont_exist doesn't exist.
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
             "--add-modules=i_dont_exist", "--add-modules=java.base", "-version");
         OutputAnalyzer output = new OutputAnalyzer(pb.start());
-        output.shouldHaveExitValue(0);
+        output.shouldContain("ResolutionException");
+        output.shouldContain("i_dont_exist");
+        output.shouldHaveExitValue(1);
 
-        // Test that last --limit-modules is the only one recognized.  No exception
+        // Test that the last --limit-modules is the only one recognized.  No exception
         // should be thrown.
         pb = ProcessTools.createJavaProcessBuilder(
             "--limit-modules=i_dont_exist", "--limit-modules=java.base", "-version");
--- a/test/testlibrary/ctw/Makefile	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/testlibrary/ctw/Makefile	Tue Sep 13 18:19:05 2016 +0200
@@ -40,7 +40,7 @@
 JAVAC = $(JDK_HOME)/bin/javac
 JAR = $(JDK_HOME)/bin/jar
 
-SRC_FILES = $(shell find $(SRC_DIR) $(TESTLIBRARY_DIR)/share/classes -name '*.java')
+SRC_FILES = $(shell find $(SRC_DIR) $(TESTLIBRARY_DIR)/jdk/test/lib -name '*.java')
 WB_SRC_FILES = $(shell find $(TESTLIBRARY_DIR)/sun/hotspot -name '*.java')
 
 MAIN_CLASS = sun.hotspot.tools.ctw.CompileTheWorld
--- a/test/testlibrary/jittester/Makefile	Tue Sep 13 11:04:29 2016 -0400
+++ b/test/testlibrary/jittester/Makefile	Tue Sep 13 18:19:05 2016 +0200
@@ -56,7 +56,6 @@
 CLASSES_DIR = $(BUILD_DIR)/classes
 SRC_DIR = src
 TEST_DIR = test
-DRIVER_DIR = $(TESTBASE_DIR)/jdk/test/lib/jittester/jtreg
 MANIFEST = manifest.mf
 APPLICATION_ARGS += \
     --property-file $(PROPERTY_FILE) \
@@ -118,19 +117,18 @@
 	@rm filelist
 	@rm -rf $(CLASSES_DIR)
 
-copytestlibrary: $(DRIVER_DIR)
-	@cp -r src/jdk/test/lib/jittester/jtreg/*.java $(DRIVER_DIR)
+copytestlibrary: $(TESTBASE_DIR)/jdk/test/lib/jittester/jtreg
+	@cp -r src/jdk/test/lib/jittester/jtreg/*.java $(TESTBASE_DIR)/jdk/test/lib/jittester/jtreg
+	@cp -r $(TESTLIBRARY_SRC_DIR) $(TESTBASE_DIR)/jdk/test/
 
 testgroup: $(TESTBASE_DIR)
 	@echo 'jittester_all = \\' > $(TESTGROUP_FILE)
 	@echo '	/' >> $(TESTGROUP_FILE)
 	@echo '' >> $(TESTGROUP_FILE)
-	@echo 'main = \\' >> $(TESTGROUP_FILE)
-	@echo '	Test_0.java' >> $(TESTGROUP_FILE)
 
 testroot: $(TESTBASE_DIR)
 	@echo 'groups=TEST.groups' > $(TESTROOT_FILE)
 
-$(TESTBASE_DIR) $(DIST_DIR) $(DRIVER_DIR):
+$(TESTBASE_DIR) $(DIST_DIR) $(TESTBASE_DIR)/jdk/test/lib/jittester/jtreg:
 	$(shell if [ ! -d $@ ]; then mkdir -p $@; fi)