diff --git a/.hgtags-top-repo b/.hgtags-top-repo
index 3fbd35c6a228613e5ad05cf23641cff970d3ebdc..f99201f034e626dc87a1406579c1f48524e2f5ac 100644
--- a/.hgtags-top-repo
+++ b/.hgtags-top-repo
@@ -264,3 +264,4 @@ cf22a728521f91a4692b433d39d730a0a1b23155 jdk9-b16
 75a08df650eb3126bab0c4d15241f5886162393c jdk9-b19
 ee4fd72b2ec3d92497f37163352f294aa695c6fb jdk9-b20
 9052803f4d01feda28b3d65f2b64dd457d21c7b6 jdk9-b21
+8e4bdab4c362aadde2d321f968cd503a2f779e2f jdk9-b22
diff --git a/common/autoconf/hotspot-spec.gmk.in b/common/autoconf/hotspot-spec.gmk.in
index f7abdd40e0a56c2cbf9a71202d56b0c7cbc87c74..057d882c28eebf3066c11406e805548d650e0743 100644
--- a/common/autoconf/hotspot-spec.gmk.in
+++ b/common/autoconf/hotspot-spec.gmk.in
@@ -69,8 +69,8 @@ ISA_DIR=$(OPENJDK_TARGET_CPU_ISADIR)
 # Yet another name for arch used for an extra subdir below the jvm lib.
 # Uses i386 and amd64, instead of x86 and x86_64.
 LIBARCH=$(OPENJDK_TARGET_CPU_LEGACY_LIB)
-# Old name for OPENJDK_TARGET_CPU, uses i586 and amd64, instead of x86 and x86_64.
-ARCH=$(OPENJDK_TARGET_CPU_LEGACY)
+# Set the cpu architecture
+ARCH=$(OPENJDK_TARGET_CPU_ARCH)
 # Legacy setting for building for a 64 bit machine.
 # If yes then this expands to _LP64:=1
 @LP64@
diff --git a/corba/.hgtags b/corba/.hgtags
index cdc0dbb61f78c41502709b085712e40d08324553..e76e0325e2d8c4366d0e36fc9a205e376caf7bdf 100644
--- a/corba/.hgtags
+++ b/corba/.hgtags
@@ -264,3 +264,4 @@ e54022d0dd92106fff7f7fe670010cd7e6517ee3 jdk9-b15
 eecc1b6adc7e193d00a0641eb0963add5a4c06e8 jdk9-b19
 87f36eecb1665012d01c5cf102494e591c943ea6 jdk9-b20
 3615a4e7f0542ca7552ad6454b742c73ee211d8e jdk9-b21
+ddc07abf4307855c0dc904cc5c96cc764023a930 jdk9-b22
diff --git a/get_source.sh b/get_source.sh
index 21bafe05609045a7c13967484c1918ec8573f52f..5e874d1cb517005803da0046efaa65c0e181f827 100644
--- a/get_source.sh
+++ b/get_source.sh
@@ -25,11 +25,34 @@
 # questions.
 #
 
+to_stderr() {
+    echo "$@" >&2
+}
+
+error() {
+    to_stderr "ERROR: $1"
+    exit ${2:-126}
+}
+
+warning() {
+    to_stderr "WARNING: $1"
+}
+
+version_field() {
+  # rev is typically omitted for minor and major releases
+  field=`echo ${1}.0 | cut -f ${2} -d .`
+  if expr 1 + $field >/dev/null 2> /dev/null; then
+    echo $field
+  else
+    echo -1
+  fi
+}
+
 # Version check
 
 # required
 reqdmajor=1
-reqdminor=5
+reqdminor=4
 reqdrev=0
 
 # requested
@@ -37,34 +60,39 @@ rqstmajor=2
 rqstminor=6
 rqstrev=3
 
+
 # installed
-hgwhere="`which hg 2> /dev/null | grep -v '^no hg in '`"
+hgwhere="`command -v hg`"
 if [ "x$hgwhere" = "x" ]; then
-  echo "ERROR: Could not locate Mercurial command" >&2
-  exit 126
+  error "Could not locate Mercurial command"
 fi
 
-hgversion="`hg --version 2> /dev/null | sed -n -e 's@^Mercurial Distributed SCM (version \(.*\))\$@\1@p'`"
+hgversion="`hg --version 2> /dev/null | sed -n -e 's@^Mercurial Distributed SCM (version \([^+]*\).*)\$@\1@p'`"
 if [ "x${hgversion}" = "x" ] ; then
-  echo "ERROR: Could not determine Mercurial version" >&2
-  exit 126
+  error "Could not determine Mercurial version of $hgwhere"
+fi
+
+hgmajor="`version_field $hgversion 1`"
+hgminor="`version_field $hgversion 2`"
+hgrev="`version_field $hgversion 3`"
+
+if [ $hgmajor -eq -1 -o $hgminor -eq -1 -o $hgrev -eq -1 ] ; then
+  error "Could not determine Mercurial version of $hgwhere from \"$hgversion\""
 fi
 
-hgmajor="`echo $hgversion | cut -f 1 -d .`"
-hgminor="`echo $hgversion | cut -f 2 -d .`"
-hgrev="`echo $hgversion.0 | cut -f 3 -d .`" # rev is omitted for minor and major releases
 
 # Require
 if [ $hgmajor -lt $reqdmajor -o \( $hgmajor -eq $reqdmajor -a $hgminor -lt $reqdminor \) -o \( $hgmajor -eq $reqdmajor -a $hgminor -eq $reqdminor -a $hgrev -lt $reqdrev \) ] ; then
-  echo "ERROR: Mercurial version $reqdmajor.$reqdminor.$reqdrev or later is required. $hgwhere is version $hgversion" >&2
-  exit 126
+  error "Mercurial version $reqdmajor.$reqdminor.$reqdrev or later is required. $hgwhere is version $hgversion"
 fi
 
+
 # Request
 if [ $hgmajor -lt $rqstmajor -o \( $hgmajor -eq $rqstmajor -a $hgminor -lt $rqstminor \) -o \( $hgmajor -eq $rqstmajor -a $hgminor -eq $rqstminor -a $hgrev -lt $rqstrev \) ] ; then
-  echo "WARNING: Mercurial version $rqstmajor.$rqstminor.$rqstrev or later is recommended. $hgwhere is version $hgversion" >&2
+  warning "Mercurial version $rqstmajor.$rqstminor.$rqstrev or later is recommended. $hgwhere is version $hgversion"
 fi
 
+
 # Get clones of all absent nested repositories (harmless if already exist)
 sh ./common/bin/hgforest.sh clone "$@" || exit $?
 
diff --git a/hotspot/.hgtags b/hotspot/.hgtags
index bc44b8bd4018ad491c637e461177ee7617ca996d..882932d140ad465b8b5bfbbf61654006b4bfdc9e 100644
--- a/hotspot/.hgtags
+++ b/hotspot/.hgtags
@@ -424,3 +424,4 @@ b14e7c0b7d3ec04127f565cda1d84122e205680c jdk9-b16
 d4cffb3ae6213c66c7522ebffe0349360a45f0ef jdk9-b19
 c1af79d122ec9f715fa29312b5e91763f3a4dfc4 jdk9-b20
 17b4a5e831b398738feedb0afe75245744510153 jdk9-b21
+518d1fcc0799494f013e00e0a94a91b6f212d54f jdk9-b22
diff --git a/hotspot/src/cpu/ppc/vm/bytecodes_ppc.cpp b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/G1YCType.java
similarity index 66%
rename from hotspot/src/cpu/ppc/vm/bytecodes_ppc.cpp
rename to hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/G1YCType.java
index 6418951cee6761c2db1afb497aa57bcad3dfd5f0..d3d15512b04431c822626088ab9eca55291f0be5 100644
--- a/hotspot/src/cpu/ppc/vm/bytecodes_ppc.cpp
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/G1YCType.java
@@ -1,6 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -23,9 +22,24 @@
  *
  */
 
-#include "precompiled.hpp"
-#include "interpreter/bytecodes.hpp"
+package sun.jvm.hotspot.gc_interface;
 
-void Bytecodes::pd_initialize() {
-  // No ppc specific initialization.
+//These definitions should be kept in sync with the definitions in the HotSpot
+//code.
+
+public enum G1YCType {
+  Normal ("Normal"),
+  InitialMark ("Initial Mark"),
+  DuringMark ("During Mark"),
+  Mixed ("Mixed"),
+  G1YCTypeEndSentinel ("Unknown");
+
+  private final String value;
+
+  G1YCType(String val) {
+    this.value = val;
+  }
+  public String value() {
+    return value;
+  }
 }
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCCause.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCCause.java
new file mode 100644
index 0000000000000000000000000000000000000000..fc8f251f91999513fd6eb1b4b0e5735142e880e0
--- /dev/null
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCCause.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2014, 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.
+ *
+ */
+
+package sun.jvm.hotspot.gc_interface;
+
+//These definitions should be kept in sync with the definitions in the HotSpot code.
+
+public enum GCCause {
+  _java_lang_system_gc ("System.gc()"),
+  _full_gc_alot ("FullGCAlot"),
+  _scavenge_alot ("ScavengeAlot"),
+  _allocation_profiler ("Allocation Profiler"),
+  _jvmti_force_gc ("JvmtiEnv ForceGarbageCollection"),
+  _gc_locker ("GCLocker Initiated GC"),
+  _heap_inspection ("Heap Inspection Initiated GC"),
+  _heap_dump ("Heap Dump Initiated GC"),
+
+  _no_gc ("No GC"),
+  _no_cause_specified ("Unknown GCCause"),
+  _allocation_failure ("Allocation Failure"),
+
+  _tenured_generation_full ("Tenured Generation Full"),
+  _metadata_GC_threshold ("Metadata GC Threshold"),
+
+  _cms_generation_full ("CMS Generation Full"),
+  _cms_initial_mark ("CMS Initial Mark"),
+  _cms_final_remark ("CMS Final Remark"),
+  _cms_concurrent_mark ("CMS Concurrent Mark"),
+
+  _old_generation_expanded_on_last_scavenge ("Old Generation Expanded On Last Scavenge"),
+  _old_generation_too_full_to_scavenge ("Old Generation Too Full To Scavenge"),
+  _adaptive_size_policy ("Ergonomics"),
+
+  _g1_inc_collection_pause ("G1 Evacuation Pause"),
+  _g1_humongous_allocation ("G1 Humongous Allocation"),
+
+  _last_ditch_collection ("Last ditch collection"),
+  _last_gc_cause ("ILLEGAL VALUE - last gc cause - ILLEGAL VALUE");
+
+  private final String value;
+
+  GCCause(String val) {
+    this.value = val;
+  }
+  public String value() {
+    return value;
+  }
+}
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCName.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCName.java
new file mode 100644
index 0000000000000000000000000000000000000000..f8985778d355c71177b3a0aaca4c927336336703
--- /dev/null
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCName.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2014, 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.
+ *
+ */
+
+package sun.jvm.hotspot.gc_interface;
+
+//These definitions should be kept in sync with the definitions in the HotSpot code.
+
+public enum GCName {
+  ParallelOld ("ParallelOld"),
+  SerialOld ("SerialOld"),
+  PSMarkSweep ("PSMarkSweep"),
+  ParallelScavenge ("ParallelScavenge"),
+  DefNew ("DefNew"),
+  ParNew ("ParNew"),
+  G1New ("G1New"),
+  ConcurrentMarkSweep ("ConcurrentMarkSweep"),
+  G1Old ("G1Old"),
+  GCNameEndSentinel ("GCNameEndSentinel");
+
+  private final String value;
+
+  GCName(String val) {
+    this.value = val;
+  }
+  public String value() {
+    return value;
+  }
+}
+
diff --git a/hotspot/src/cpu/sparc/vm/bytecodes_sparc.cpp b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCWhen.java
similarity index 69%
rename from hotspot/src/cpu/sparc/vm/bytecodes_sparc.cpp
rename to hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCWhen.java
index 8874d8ca8cccfc9c6ee7cc96341cfdc2c6789ec0..74d4a83f7442aa9103bde346c5e9ef9175a6dcbe 100644
--- a/hotspot/src/cpu/sparc/vm/bytecodes_sparc.cpp
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/GCWhen.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -22,14 +22,24 @@
  *
  */
 
-#include "precompiled.hpp"
-#include "interpreter/bytecodes.hpp"
+package sun.jvm.hotspot.gc_interface;
 
+//These definitions should be kept in sync with the definitions in the HotSpot code.
 
-void Bytecodes::pd_initialize() {
-  // (nothing)
-}
+public enum GCWhen {
+  BeforeGC ("Before GC"),
+  AfterGC ("After GC"),
+  GCWhenEndSentinel ("GCWhenEndSentinel");
+
+  private final String value;
 
-Bytecodes::Code Bytecodes::pd_base_code_for(Code code) {
-  return code;
+  GCWhen(String val) {
+    this.value = val;
+  }
+  public String value() {
+    return value;
+  }
 }
+
+
+
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/ReferenceType.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/ReferenceType.java
new file mode 100644
index 0000000000000000000000000000000000000000..e8bb8bc2119dc0391f59c8f016a6c7da63ca428c
--- /dev/null
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_interface/ReferenceType.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2014, 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.
+ *
+ */
+
+package sun.jvm.hotspot.gc_interface;
+
+//These definitions should be kept in sync with the definitions in the HotSpot code.
+
+public enum ReferenceType {
+  REF_NONE ("None reference"),       // Regular class
+  REF_OTHER ("Other reference"),     // Subclass of java/lang/ref/Reference, but not subclass of one of the classes below
+  REF_SOFT ("Soft reference"),       // Subclass of java/lang/ref/SoftReference
+  REF_WEAK ("Weak reference"),       // Subclass of java/lang/ref/WeakReference
+  REF_FINAL ("Final reference"),     // Subclass of java/lang/ref/FinalReference
+  REF_PHANTOM ("Phantom reference"); // Subclass of java/lang/ref/PhantomReference
+
+  private final String value;
+
+  ReferenceType(String val) {
+    this.value = val;
+  }
+  public String value() {
+    return value;
+  }
+}
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/memory/Universe.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/memory/Universe.java
index c23ce3a409315dea45c523889015eb08a5a7760e..a66543402765cb4a687d27f432f70814c2ad1ce3 100644
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/memory/Universe.java
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/memory/Universe.java
@@ -56,6 +56,12 @@ public class Universe {
   private static AddressField narrowKlassBaseField;
   private static CIntegerField narrowKlassShiftField;
 
+  public enum NARROW_OOP_MODE {
+    UnscaledNarrowOop,
+    ZeroBasedNarrowOop,
+    HeapBasedNarrowOop
+  }
+
   static {
     VM.registerVMInitializedObserver(new Observer() {
         public void update(Observable o, Object data) {
@@ -94,7 +100,17 @@ public class Universe {
 
   public Universe() {
   }
-
+  public static String narrowOopModeToString(NARROW_OOP_MODE mode) {
+    switch (mode) {
+    case UnscaledNarrowOop:
+      return "32-bits Oops";
+    case ZeroBasedNarrowOop:
+      return "zero based Compressed Oops";
+    case HeapBasedNarrowOop:
+      return "Compressed Oops with base";
+    }
+    return "";
+  }
   public CollectedHeap heap() {
     try {
       return (CollectedHeap) heapConstructor.instantiateWrapperFor(collectedHeapField.getValue());
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/Klass.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/Klass.java
index 9e1561bd39052907222e375f5ed1ee267cdb56f9..c3f7b8cb88b61f2b66cda62f39dd38cf0c4354dd 100644
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/Klass.java
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/Klass.java
@@ -55,6 +55,7 @@ public class Klass extends Metadata implements ClassConstants {
     layoutHelper = new IntField(type.getJIntField("_layout_helper"), 0);
     name         = type.getAddressField("_name");
     accessFlags  = new CIntField(type.getCIntegerField("_access_flags"), 0);
+    traceIDField  = type.getField("_trace_id");
     subklass     = new MetadataField(type.getAddressField("_subklass"), 0);
     nextSibling  = new MetadataField(type.getAddressField("_next_sibling"), 0);
 
@@ -86,6 +87,7 @@ public class Klass extends Metadata implements ClassConstants {
   private static CIntField accessFlags;
   private static MetadataField  subklass;
   private static MetadataField  nextSibling;
+  private static sun.jvm.hotspot.types.Field traceIDField;
 
   private Address getValue(AddressField field) {
     return addr.getAddressAt(field.getOffset());
@@ -106,6 +108,7 @@ public class Klass extends Metadata implements ClassConstants {
   public AccessFlags getAccessFlagsObj(){ return new AccessFlags(getAccessFlags());      }
   public Klass    getSubklassKlass()    { return (Klass)    subklass.getValue(this);     }
   public Klass    getNextSiblingKlass() { return (Klass)    nextSibling.getValue(this);  }
+  public long     traceID() { return traceIDField.getJLong(addr);  }
 
   // computed access flags - takes care of inner classes etc.
   // This is closer to actual source level than getAccessFlags() etc.
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/OopUtilities.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/OopUtilities.java
index a42d8be68b5bd2caaf2b1bd0072fdcd0296bf578..fe93d6238a898ada3334f1d050b5e71b7163c6b5 100644
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/OopUtilities.java
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/OopUtilities.java
@@ -54,6 +54,8 @@ public class OopUtilities implements /* imports */ JVMTIThreadState {
   private static OopField threadNameField;
   private static OopField threadGroupField;
   private static LongField threadEETopField;
+  //tid field is new since 1.5
+  private static LongField threadTIDField;
   // threadStatus field is new since 1.5
   private static IntField threadStatusField;
   // parkBlocker field is new since 1.6
@@ -220,6 +222,7 @@ public class OopUtilities implements /* imports */ JVMTIThreadState {
       threadNameField  = (OopField) k.findField("name", "[C");
       threadGroupField = (OopField) k.findField("group", "Ljava/lang/ThreadGroup;");
       threadEETopField = (LongField) k.findField("eetop", "J");
+      threadTIDField = (LongField) k.findField("tid", "J");
       threadStatusField = (IntField) k.findField("threadStatus", "I");
       threadParkBlockerField = (OopField) k.findField("parkBlocker",
                                      "Ljava/lang/Object;");
@@ -268,6 +271,15 @@ public class OopUtilities implements /* imports */ JVMTIThreadState {
     return VM.getVM().getThreads().createJavaThreadWrapper(addr);
   }
 
+  public static long threadOopGetTID(Oop threadOop) {
+    initThreadFields();
+    if (threadTIDField != null) {
+      return threadTIDField.getValue(threadOop);
+    } else {
+      return 0;
+    }
+  }
+
   /** returns value of java.lang.Thread.threadStatus field */
   public static int threadOopGetThreadStatus(Oop threadOop) {
     initThreadFields();
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CompilerPhaseType.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CompilerPhaseType.java
new file mode 100644
index 0000000000000000000000000000000000000000..e0eb10942df94e1bc64588de9cc7aa954fb61ae3
--- /dev/null
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CompilerPhaseType.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2014, 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.
+ *
+ */
+
+package sun.jvm.hotspot.opto;
+
+//These definitions should be kept in sync with the definitions in the HotSpot code.
+
+public enum CompilerPhaseType {
+  PHASE_BEFORE_STRINGOPTS ("Before StringOpts"),
+  PHASE_AFTER_STRINGOPTS ("After StringOpts"),
+  PHASE_BEFORE_REMOVEUSELESS ("Before RemoveUseless"),
+  PHASE_AFTER_PARSING ("After Parsing"),
+  PHASE_ITER_GVN1 ("Iter GVN 1"),
+  PHASE_PHASEIDEAL_BEFORE_EA ("PhaseIdealLoop before EA"),
+  PHASE_ITER_GVN_AFTER_EA ("Iter GVN after EA"),
+  PHASE_ITER_GVN_AFTER_ELIMINATION ("Iter GVN after eliminating allocations and locks"),
+  PHASE_PHASEIDEALLOOP1 ("PhaseIdealLoop 1"),
+  PHASE_PHASEIDEALLOOP2 ("PhaseIdealLoop 2"),
+  PHASE_PHASEIDEALLOOP3 ("PhaseIdealLoop 3"),
+  PHASE_CPP1 ("PhaseCPP 1"),
+  PHASE_ITER_GVN2 ("Iter GVN 2"),
+  PHASE_PHASEIDEALLOOP_ITERATIONS ("PhaseIdealLoop iterations"),
+  PHASE_OPTIMIZE_FINISHED ("Optimize finished"),
+  PHASE_GLOBAL_CODE_MOTION ("Global code motion"),
+  PHASE_FINAL_CODE ("Final Code"),
+  PHASE_AFTER_EA ("After Escape Analysis"),
+  PHASE_BEFORE_CLOOPS ("Before CountedLoop"),
+  PHASE_AFTER_CLOOPS ("After CountedLoop"),
+  PHASE_BEFORE_BEAUTIFY_LOOPS ("Before beautify loops"),
+  PHASE_AFTER_BEAUTIFY_LOOPS ("After beautify loops"),
+  PHASE_BEFORE_MATCHING ("Before Matching"),
+  PHASE_INCREMENTAL_INLINE ("Incremental Inline"),
+  PHASE_INCREMENTAL_BOXING_INLINE ("Incremental Boxing Inline"),
+  PHASE_END ("End"),
+  PHASE_FAILURE ("Failure"),
+  PHASE_NUM_TYPES ("Number of Phase Types");
+
+  private final String value;
+
+  CompilerPhaseType(String val) {
+    this.value = val;
+  }
+  public String value() {
+    return value;
+  }
+}
diff --git a/hotspot/test/runtime/8001071/Test8001071.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/Flags.java
similarity index 62%
rename from hotspot/test/runtime/8001071/Test8001071.java
rename to hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/Flags.java
index df03e197de85d5f63229f0bd2f522ba902b22649..320dda27ee4a5f406bc0ed6b1f5b3b9edbfc7414 100644
--- a/hotspot/test/runtime/8001071/Test8001071.java
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/Flags.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -19,27 +19,30 @@
  * 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.
+ *
  */
 
-import sun.misc.Unsafe;
-import java.lang.reflect.Field;
+package sun.jvm.hotspot.runtime;
 
-@SuppressWarnings("sunapi")
-public class Test8001071 {
-    public static Unsafe unsafe;
+//These definitions should be kept in sync with the definitions in the HotSpot code.
 
-    static {
-        try {
-            Field f = Unsafe.class.getDeclaredField("theUnsafe");
-            f.setAccessible(true);
-            unsafe = (Unsafe) f.get(null);
-        } catch ( Exception e ) {
-            e.printStackTrace();
-        }
-    }
+public enum Flags {
+  // value origin
+  DEFAULT ("Default"),
+  COMMAND_LINE ("Command line"),
+  ENVIRON_VAR ("Environment variable"),
+  CONFIG_FILE ("Config file"),
+  MANAGEMENT ("Management"),
+  ERGONOMIC ("Ergonomic"),
+  ATTACH_ON_DEMAND ("Attach on demand"),
+  INTERNAL ("Internal");
 
-    public static void main(String args[]) {
-        unsafe.getObject(new Test8001071(), Short.MAX_VALUE);
-    }
+  private final String value;
 
+  Flags(String val) {
+    this.value = val;
+  }
+  public String value() {
+    return value;
+  }
 }
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/Thread.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/Thread.java
index 2948f7b95cac0167b65ad4d8e4c8ee5f7151f527..03c426ba84a8f04f71f9bd223c4a82670a287810 100644
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/Thread.java
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/Thread.java
@@ -41,6 +41,8 @@ public class Thread extends VMObject {
   private static AddressField currentPendingMonitorField;
   private static AddressField currentWaitingMonitorField;
 
+  private static JLongField allocatedBytesField;
+
   static {
     VM.registerVMInitializedObserver(new Observer() {
         public void update(Observable o, Object data) {
@@ -61,6 +63,7 @@ public class Thread extends VMObject {
     activeHandlesField = type.getAddressField("_active_handles");
     currentPendingMonitorField = type.getAddressField("_current_pending_monitor");
     currentWaitingMonitorField = type.getAddressField("_current_waiting_monitor");
+    allocatedBytesField = type.getJLongField("_allocated_bytes");
   }
 
   public Thread(Address addr) {
@@ -104,6 +107,10 @@ public class Thread extends VMObject {
     return new JNIHandleBlock(a);
   }
 
+  public long allocatedBytes() {
+    return allocatedBytesField.getValue(addr);
+  }
+
   public boolean   isVMThread()                { return false; }
   public boolean   isJavaThread()              { return false; }
   public boolean   isCompilerThread()          { return false; }
diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VMOps.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VMOps.java
new file mode 100644
index 0000000000000000000000000000000000000000..c2ab69f4b2f82245afd6d79e3033c24a63a97b42
--- /dev/null
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VMOps.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2014, 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.
+ *
+ */
+
+package sun.jvm.hotspot.runtime;
+
+//These definitions should be kept in sync with the definitions in the HotSpot code.
+
+public enum VMOps {
+  Dummy,
+  ThreadStop,
+  ThreadDump,
+  PrintThreads,
+  FindDeadlocks,
+  ForceSafepoint,
+  ForceAsyncSafepoint,
+  Deoptimize,
+  DeoptimizeFrame,
+  DeoptimizeAll,
+  ZombieAll,
+  UnlinkSymbols,
+  Verify,
+  PrintJNI,
+  HeapDumper,
+  DeoptimizeTheWorld,
+  CollectForMetadataAllocation,
+  GC_HeapInspection,
+  GenCollectFull,
+  GenCollectFullConcurrent,
+  GenCollectForAllocation,
+  ParallelGCFailedAllocation,
+  ParallelGCSystemGC,
+  CGC_Operation,
+  CMS_Initial_Mark,
+  CMS_Final_Remark,
+  G1CollectFull,
+  G1CollectForAllocation,
+  G1IncCollectionPause,
+  EnableBiasedLocking,
+  RevokeBias,
+  BulkRevokeBias,
+  PopulateDumpSharedSpace,
+  JNIFunctionTableCopier,
+  RedefineClasses,
+  GetOwnedMonitorInfo,
+  GetObjectMonitorUsage,
+  GetCurrentContendedMonitor,
+  GetStackTrace,
+  GetMultipleStackTraces,
+  GetAllStackTraces,
+  GetThreadListStackTraces,
+  GetFrameCount,
+  GetFrameLocation,
+  ChangeBreakpoints,
+  GetOrSetLocal,
+  GetCurrentLocation,
+  EnterInterpOnlyMode,
+  ChangeSingleStep,
+  HeapWalkOperation,
+  HeapIterateOperation,
+  ReportJavaOutOfMemory,
+  JFRCheckpoint,
+  Exit,
+  LinuxDllLoad,
+  Terminating
+}
diff --git a/hotspot/make/aix/makefiles/vm.make b/hotspot/make/aix/makefiles/vm.make
index b579babfffa32b972402c0248d13fb557e514fa1..1170b0477d65595f6057c1cf4f1dd604980a8177 100644
--- a/hotspot/make/aix/makefiles/vm.make
+++ b/hotspot/make/aix/makefiles/vm.make
@@ -82,14 +82,12 @@ VM_VER_DEFS   = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" \
 		-DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\""  \
 		$(JDK_VER_DEFS)
 HS_LIB_ARCH   = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\"
-BUILD_TARGET  = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\""
 BUILD_USER    = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\""
 VM_DISTRO     = -DHOTSPOT_VM_DISTRO="\"$(HOTSPOT_VM_DISTRO)\""
 
 CXXFLAGS =           \
   ${SYSDEFS}         \
   ${INCLUDES}        \
-  ${BUILD_TARGET}    \
   ${BUILD_USER}      \
   ${HS_LIB_ARCH}     \
   ${VM_DISTRO}
diff --git a/hotspot/make/bsd/makefiles/gcc.make b/hotspot/make/bsd/makefiles/gcc.make
index c96ff2a78b62b49f486531b53b27ca293d5d8548..b2b925b2e1c2ff03e9181365975c72d35a8702e9 100644
--- a/hotspot/make/bsd/makefiles/gcc.make
+++ b/hotspot/make/bsd/makefiles/gcc.make
@@ -280,7 +280,10 @@ endif
 
 # optimization control flags (Used by fastdebug and release variants)
 OPT_CFLAGS/NOOPT=-O0
-ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
+ifeq ($(USE_CLANG), true)
+  # Clang does not support -Og
+  OPT_CFLAGS/DEBUG=-O0
+else ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
   # Allow basic optimizations which don't distrupt debugging. (Principally dead code elimination)
   OPT_CFLAGS/DEBUG=-Og
 else
@@ -319,9 +322,20 @@ endif
 
 # Work around some compiler bugs.
 ifeq ($(USE_CLANG), true)
+  # Clang 4.2
   ifeq ($(shell expr $(CC_VER_MAJOR) = 4 \& $(CC_VER_MINOR) = 2), 1)
     OPT_CFLAGS/loopTransform.o += $(OPT_CFLAGS/NOOPT)
     OPT_CFLAGS/unsafe.o += -O1
+  # Clang 5.0
+  else ifeq ($(shell expr $(CC_VER_MAJOR) = 5 \& $(CC_VER_MINOR) = 0), 1)
+    OPT_CFLAGS/loopTransform.o += $(OPT_CFLAGS/NOOPT)
+    OPT_CFLAGS/unsafe.o += -O1
+  # Clang 5.1
+  else ifeq ($(shell expr $(CC_VER_MAJOR) = 5 \& $(CC_VER_MINOR) = 1), 1)
+    OPT_CFLAGS/loopTransform.o += $(OPT_CFLAGS/NOOPT)
+    OPT_CFLAGS/unsafe.o += -O1
+  else
+    $(error "Update compiler workarounds for Clang $(CC_VER_MAJOR).$(CC_VER_MINOR)")
   endif
 else
   # 6835796. Problem in GCC 4.3.0 with mulnode.o optimized compilation.
@@ -443,7 +457,10 @@ ifeq ($(USE_CLANG), true)
   CFLAGS += -flimit-debug-info
 endif
 
-ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
+ifeq ($(USE_CLANG), true)
+  # Clang does not support -Og
+  DEBUG_CFLAGS=-O0
+else ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
   # Allow basic optimizations which don't distrupt debugging. (Principally dead code elimination)
   DEBUG_CFLAGS=-Og
 else
diff --git a/hotspot/make/bsd/makefiles/vm.make b/hotspot/make/bsd/makefiles/vm.make
index 56beb6c6ba57bd1644abee54de27a062bd61b29c..3a658ab13738813a38ccd99827935a4b40dc4afe 100644
--- a/hotspot/make/bsd/makefiles/vm.make
+++ b/hotspot/make/bsd/makefiles/vm.make
@@ -81,14 +81,12 @@ VM_VER_DEFS   = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" \
 		-DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\""  \
 		$(JDK_VER_DEFS)
 HS_LIB_ARCH   = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\"
-BUILD_TARGET  = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\""
 BUILD_USER    = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\""
 VM_DISTRO     = -DHOTSPOT_VM_DISTRO="\"$(HOTSPOT_VM_DISTRO)\""
 
 CXXFLAGS =           \
   ${SYSDEFS}         \
   ${INCLUDES}        \
-  ${BUILD_TARGET}    \
   ${BUILD_USER}      \
   ${HS_LIB_ARCH}     \
   ${VM_DISTRO}
diff --git a/hotspot/make/defs.make b/hotspot/make/defs.make
index 65942d2b53f52fca51e55de060bdabd7ab26d6a0..70e050eb2e1769c615a88ba6fc4dddeaeb8abf7b 100644
--- a/hotspot/make/defs.make
+++ b/hotspot/make/defs.make
@@ -135,8 +135,12 @@ endif
 ifeq ($(JDK_MKTG_VERSION),)
   JDK_MKTG_VERSION=$(JDK_MINOR_VERSION).$(JDK_MICRO_VERSION)
 endif
-ifeq ($(JDK_VERSION),)
-  JDK_VERSION=$(JDK_MAJOR_VERSION).$(JDK_MINOR_VERSION).$(JDK_MICRO_VERSION)
+ifeq ($(JDK_VERSION),)  
+  ifeq ($(BUILD_FLAVOR), product)
+    JDK_VERSION=$(JDK_MAJOR_VERSION).$(JDK_MINOR_VERSION).$(JDK_MICRO_VERSION)
+  else
+    JDK_VERSION=$(JDK_MAJOR_VERSION).$(JDK_MINOR_VERSION).$(JDK_MICRO_VERSION)-$(BUILD_FLAVOR)
+  endif
 endif
 ifeq ($(FULL_VERSION),)
   FULL_VERSION="$(JDK_VERSION)"
diff --git a/hotspot/make/linux/makefiles/defs.make b/hotspot/make/linux/makefiles/defs.make
index 8922fdd8728e5139c4b9ccc7c87fa13190cf33ba..dc0bb08728dd4f5ee491d25ee65906ba5f73f4d3 100644
--- a/hotspot/make/linux/makefiles/defs.make
+++ b/hotspot/make/linux/makefiles/defs.make
@@ -69,7 +69,7 @@ ifeq ($(ARCH), ia64)
 endif
 
 # sparc
-ifeq ($(ARCH), sparc64)
+ifneq (,$(findstring $(ARCH), sparc))
   ifeq ($(ARCH_DATA_MODEL), 64)
     ARCH_DATA_MODEL  = 64
     MAKE_ARGS        += LP64=1
@@ -83,30 +83,20 @@ ifeq ($(ARCH), sparc64)
   HS_ARCH            = sparc
 endif
 
-# amd64/x86_64
-ifneq (,$(findstring $(ARCH), amd64 x86_64))
+# i686/i586 and amd64/x86_64
+ifneq (,$(findstring $(ARCH), amd64 x86_64 i686 i586))
   ifeq ($(ARCH_DATA_MODEL), 64)
     ARCH_DATA_MODEL = 64
     MAKE_ARGS       += LP64=1
     PLATFORM        = linux-amd64
     VM_PLATFORM     = linux_amd64
-    HS_ARCH         = x86
   else
     ARCH_DATA_MODEL = 32
     PLATFORM        = linux-i586
     VM_PLATFORM     = linux_i486
-    HS_ARCH         = x86
-    # We have to reset ARCH to i686 since SRCARCH relies on it
-    ARCH            = i686
   endif
-endif
 
-# i686/i586 ie 32-bit x86
-ifneq (,$(findstring $(ARCH), i686 i586))
-  ARCH_DATA_MODEL  = 32
-  PLATFORM         = linux-i586
-  VM_PLATFORM      = linux_i486
-  HS_ARCH          = x86
+  HS_ARCH           = x86
 endif
 
 # ARM
@@ -118,20 +108,18 @@ ifeq ($(ARCH), arm)
 endif
 
 # PPC
-ifeq ($(ARCH), ppc)
-  ARCH_DATA_MODEL  = 32
-  PLATFORM         = linux-ppc
-  VM_PLATFORM      = linux_ppc
-  HS_ARCH          = ppc
-endif
+ifneq (,$(findstring $(ARCH), ppc))
+  ifeq ($(ARCH_DATA_MODEL), 64)
+    MAKE_ARGS        += LP64=1
+    PLATFORM         = linux-ppc64
+    VM_PLATFORM      = linux_ppc64
+  else
+    ARCH_DATA_MODEL  = 32
+    PLATFORM         = linux-ppc
+    VM_PLATFORM      = linux_ppc
+  endif
 
-# PPC64
-ifeq ($(ARCH), ppc64)
-  ARCH_DATA_MODEL  = 64
-  MAKE_ARGS        += LP64=1
-  PLATFORM         = linux-ppc64
-  VM_PLATFORM      = linux_ppc64
-  HS_ARCH          = ppc
+  HS_ARCH = ppc
 endif
 
 # On 32 bit linux we build server and client, on 64 bit just server.
diff --git a/hotspot/make/linux/makefiles/vm.make b/hotspot/make/linux/makefiles/vm.make
index c91463aae133d74169359022340969f5b7e9ee2c..7e3e5f0f65c54fc0c62e1b81438d651b13790569 100644
--- a/hotspot/make/linux/makefiles/vm.make
+++ b/hotspot/make/linux/makefiles/vm.make
@@ -82,14 +82,12 @@ VM_VER_DEFS   = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" \
 		-DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\""  \
 		$(JDK_VER_DEFS)
 HS_LIB_ARCH   = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\"
-BUILD_TARGET  = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\""
 BUILD_USER    = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\""
 VM_DISTRO     = -DHOTSPOT_VM_DISTRO="\"$(HOTSPOT_VM_DISTRO)\""
 
 CXXFLAGS =           \
   ${SYSDEFS}         \
   ${INCLUDES}        \
-  ${BUILD_TARGET}    \
   ${BUILD_USER}      \
   ${HS_LIB_ARCH}     \
   ${VM_DISTRO}
diff --git a/hotspot/make/solaris/makefiles/sa.make b/hotspot/make/solaris/makefiles/sa.make
index 2c08b1c5170ccb82f5b581a0d535a361aef1509c..546e2630ce4162d800f59edf0434a9457a9780c0 100644
--- a/hotspot/make/solaris/makefiles/sa.make
+++ b/hotspot/make/solaris/makefiles/sa.make
@@ -29,8 +29,12 @@
 # and generate JNI header file for native methods.
 
 include $(GAMMADIR)/make/solaris/makefiles/rules.make
+include $(GAMMADIR)/make/defs.make
 AGENT_DIR = $(GAMMADIR)/agent
 include $(GAMMADIR)/make/sa.files
+
+-include $(HS_ALT_MAKE)/solaris/makefiles/sa.make
+
 GENERATED = ../generated
 
 # tools.jar is needed by the JDI - SA binding
diff --git a/hotspot/make/solaris/makefiles/vm.make b/hotspot/make/solaris/makefiles/vm.make
index 3e32a57cd92969b381dbd536b0a7b78b1b64c812..e0176bf66c2090af140781bffad9794331197136 100644
--- a/hotspot/make/solaris/makefiles/vm.make
+++ b/hotspot/make/solaris/makefiles/vm.make
@@ -77,14 +77,12 @@ VM_VER_DEFS   = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" \
 		-DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\""  \
 		$(JDK_VER_DEFS)
 HS_LIB_ARCH   = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\"
-BUILD_TARGET  = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\""
 BUILD_USER    = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\""
 VM_DISTRO     = -DHOTSPOT_VM_DISTRO="\"$(HOTSPOT_VM_DISTRO)\""
 
 CXXFLAGS =           \
   ${SYSDEFS}         \
   ${INCLUDES}        \
-  ${BUILD_TARGET}    \
   ${BUILD_USER}      \
   ${HS_LIB_ARCH}     \
   ${VM_DISTRO}
diff --git a/hotspot/make/windows/makefiles/sa.make b/hotspot/make/windows/makefiles/sa.make
index 13bb8130ef4c576fb9b5e6a71473984a11addf60..4ac5d89f5fa2193410f83b47cb60b5e306ad15ed 100644
--- a/hotspot/make/windows/makefiles/sa.make
+++ b/hotspot/make/windows/makefiles/sa.make
@@ -38,6 +38,22 @@ checkAndBuildSA::
 
 GENERATED = ../generated
 
+HS_COMMON_SRC_REL = src
+
+!if "$(OPENJDK)" != "true"
+HS_ALT_SRC_REL=src/closed
+HS_ALT_SRC = $(WorkSpace)/$(HS_ALT_SRC_REL)
+!ifndef HS_ALT_MAKE
+HS_ALT_MAKE=$(WorkSpace)/make/closed
+!endif
+!endif
+
+HS_COMMON_SRC = $(WorkSpace)/$(HS_COMMON_SRC_REL)
+
+!ifdef HS_ALT_MAKE
+!include $(HS_ALT_MAKE)/windows/makefiles/sa.make
+!endif
+
 # tools.jar is needed by the JDI - SA binding
 SA_CLASSPATH = $(BOOT_JAVA_HOME)/lib/tools.jar
 
diff --git a/hotspot/make/windows/projectfiles/common/Makefile b/hotspot/make/windows/projectfiles/common/Makefile
index 1fc1350706e7e89fbc33a3caffcd85c7662643cf..696b39257aa5430b706be57573720cb01c994003 100644
--- a/hotspot/make/windows/projectfiles/common/Makefile
+++ b/hotspot/make/windows/projectfiles/common/Makefile
@@ -116,7 +116,7 @@ JDK_MAJOR_VERSION="\\\"$(JDK_MAJOR_VER)\\\""
 JDK_MINOR_VERSION="\\\"$(JDK_MINOR_VER)\\\""
 JDK_MICRO_VERSION="\\\"$(JDK_MICRO_VER)\\\""
 
-ReleaseOptions = -define HOTSPOT_RELEASE_VERSION=$(HOTSPOT_RELEASE_VERSION) -define JRE_RELEASE_VERSION=$(JRE_RELEASE_VERSION) -define HOTSPOT_VM_DISTRO=$(HOTSPOT_VM_DISTRO) -define JDK_MAJOR_VERSION=$(JDK_MAJOR_VERSION) -define JDK_MINOR_VERSION=$(JDK_MINOR_VERSION) -define JDK_MICRO_VERSION=$(JDK_MICRO_VERSION) -define JDK_BUILD_NUMBER=$(JDK_BUILD_NUMBER)
+ReleaseOptions = -define HOTSPOT_RELEASE_VERSION=$(HOTSPOT_RELEASE_VERSION) -define JRE_RELEASE_VERSION=$(JRE_RELEASE_VERSION) -define HOTSPOT_VM_DISTRO=$(HOTSPOT_VM_DISTRO) -define JDK_MAJOR_VERSION=$(JDK_MAJOR_VERSION) -define JDK_MINOR_VERSION=$(JDK_MINOR_VERSION) -define JDK_MICRO_VERSION=$(JDK_MICRO_VERSION) -define JDK_BUILD_NUMBER=$(JDK_BUILD_NUMBER) -define VISUAL_STUDIO_BUILD=true
 ProjectCreatorIDEOptions = $(ProjectCreatorIDEOptions) $(ReleaseOptions)
 
 $(HOTSPOTBUILDSPACE)/$(ProjectFile): $(HOTSPOTBUILDSPACE)/classes/ProjectCreator.class
diff --git a/hotspot/src/cpu/ppc/vm/assembler_ppc.cpp b/hotspot/src/cpu/ppc/vm/assembler_ppc.cpp
index f9e49e1f4a8ae8d082d59901e93d8471f230942d..6ab0f8a61bda69a559a438e83ed74c3490edf85f 100644
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2012, 2014 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -693,7 +693,7 @@ void Assembler::test_asm() {
   // PPC 1, section 4.6.7 Floating-Point Compare Instructions
   fcmpu( CCR7, F24, F25);
 
-  tty->print_cr("\ntest_asm disassembly (0x%lx 0x%lx):", code()->insts_begin(), code()->insts_end());
+  tty->print_cr("\ntest_asm disassembly (0x%lx 0x%lx):", p2i(code()->insts_begin()), p2i(code()->insts_end()));
   code()->decode();
 }
 
diff --git a/hotspot/src/cpu/ppc/vm/compiledIC_ppc.cpp b/hotspot/src/cpu/ppc/vm/compiledIC_ppc.cpp
index b24b3c4c8958db8ab8f4023d4a0faca82b684304..1b54594d09cdf86c62c21d2c74adde1219085081 100644
--- a/hotspot/src/cpu/ppc/vm/compiledIC_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/compiledIC_ppc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -50,34 +50,6 @@ bool CompiledIC::is_icholder_call_site(virtual_call_Relocation* call_site) {
   return is_icholder_entry(call->destination());
 }
 
-//-----------------------------------------------------------------------------
-// High-level access to an inline cache. Guaranteed to be MT-safe.
-
-CompiledIC::CompiledIC(nmethod* nm, NativeCall* call)
-  : _ic_call(call)
-{
-  address ic_call = call->instruction_address();
-
-  assert(ic_call != NULL, "ic_call address must be set");
-  assert(nm != NULL, "must pass nmethod");
-  assert(nm->contains(ic_call), "must be in nmethod");
-
-  // Search for the ic_call at the given address.
-  RelocIterator iter(nm, ic_call, ic_call+1);
-  bool ret = iter.next();
-  assert(ret == true, "relocInfo must exist at this address");
-  assert(iter.addr() == ic_call, "must find ic_call");
-  if (iter.type() == relocInfo::virtual_call_type) {
-    virtual_call_Relocation* r = iter.virtual_call_reloc();
-    _is_optimized = false;
-    _value = nativeMovConstReg_at(r->cached_value());
-  } else {
-    assert(iter.type() == relocInfo::opt_virtual_call_type, "must be a virtual call");
-    _is_optimized = true;
-    _value = NULL;
-  }
-}
-
 // ----------------------------------------------------------------------------
 
 // A PPC CompiledStaticCall looks like this:
@@ -203,7 +175,7 @@ void CompiledStaticCall::set_to_interpreted(methodHandle callee, address entry)
   if (TraceICs) {
     ResourceMark rm;
     tty->print_cr("CompiledStaticCall@" INTPTR_FORMAT ": set_to_interpreted %s",
-                  instruction_address(),
+                  p2i(instruction_address()),
                   callee->name_and_sig_as_C_string());
   }
 
diff --git a/hotspot/src/cpu/ppc/vm/frame_ppc.cpp b/hotspot/src/cpu/ppc/vm/frame_ppc.cpp
index 6df316d1b8799ea8c408035e37784e3196034978..ff177e6231ab64ca033e1b418327e123fd7497e4 100644
--- a/hotspot/src/cpu/ppc/vm/frame_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/frame_ppc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2012, 2014 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -140,7 +140,7 @@ frame frame::sender(RegisterMap* map) const {
 void frame::patch_pc(Thread* thread, address pc) {
   if (TracePcPatching) {
     tty->print_cr("patch_pc at address " PTR_FORMAT " [" PTR_FORMAT " -> " PTR_FORMAT "]",
-                  &((address*) _sp)[-1], ((address*) _sp)[-1], pc);
+                  p2i(&((address*) _sp)[-1]), p2i(((address*) _sp)[-1]), p2i(pc));
   }
   own_abi()->lr = (uint64_t)pc;
   _cb = CodeCache::find_blob(pc);
diff --git a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp
index 8f026ac0d0c073be0822593ff8fe2e3c3a316294..ce10145ed905b7fa5cc183352c9fbfd4ebe4c29b 100644
--- a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2012, 2014 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -3099,7 +3099,7 @@ const char* stop_types[] = {
 };
 
 static void stop_on_request(int tp, const char* msg) {
-  tty->print("PPC assembly code requires stop: (%s) %s\n", (void *)stop_types[tp%/*stop_end*/4], msg);
+  tty->print("PPC assembly code requires stop: (%s) %s\n", stop_types[tp%/*stop_end*/4], msg);
   guarantee(false, err_msg("PPC assembly code requires stop: %s", msg));
 }
 
diff --git a/hotspot/src/cpu/ppc/vm/methodHandles_ppc.cpp b/hotspot/src/cpu/ppc/vm/methodHandles_ppc.cpp
index 4383d61f7fd1fc316e64d1f371b7eab5b1ef9176..89c0344a5fec0c1bdcdae77a65e59884f5384cc0 100644
--- a/hotspot/src/cpu/ppc/vm/methodHandles_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/methodHandles_ppc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2012, 2014 SAP AG. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -464,7 +464,7 @@ void trace_method_handle_stub(const char* adaptername,
                  strstr(adaptername, "linkTo") == NULL);    // static linkers don't have MH
   const char* mh_reg_name = has_mh ? "R23_method_handle" : "G23";
   tty->print_cr("MH %s %s="INTPTR_FORMAT " sp=" INTPTR_FORMAT,
-                adaptername, mh_reg_name, (intptr_t) mh, entry_sp);
+                adaptername, mh_reg_name, (intptr_t) mh, (intptr_t) entry_sp);
 
   if (Verbose) {
     tty->print_cr("Registers:");
diff --git a/hotspot/src/cpu/ppc/vm/nativeInst_ppc.cpp b/hotspot/src/cpu/ppc/vm/nativeInst_ppc.cpp
index f6249450de11424afb5c473f066edac55eb9da72..6f40af06f400d37318c9b60ea133f7d6a6ab1464 100644
--- a/hotspot/src/cpu/ppc/vm/nativeInst_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/nativeInst_ppc.cpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2012, 2014 SAP AG. 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
@@ -147,9 +147,9 @@ void NativeCall::verify() {
   address addr = addr_at(0);
 
   if (!NativeCall::is_call_at(addr)) {
-    tty->print_cr("not a NativeCall at " PTR_FORMAT, addr);
+    tty->print_cr("not a NativeCall at " PTR_FORMAT, p2i(addr));
     // TODO: PPC port: Disassembler::decode(addr - 20, addr + 20, tty);
-    fatal(err_msg("not a NativeCall at " PTR_FORMAT, addr));
+    fatal(err_msg("not a NativeCall at " PTR_FORMAT, p2i(addr)));
   }
 }
 #endif // ASSERT
@@ -160,9 +160,9 @@ void NativeFarCall::verify() {
 
   NativeInstruction::verify();
   if (!NativeFarCall::is_far_call_at(addr)) {
-    tty->print_cr("not a NativeFarCall at " PTR_FORMAT, addr);
+    tty->print_cr("not a NativeFarCall at " PTR_FORMAT, p2i(addr));
     // TODO: PPC port: Disassembler::decode(addr, 20, 20, tty);
-    fatal(err_msg("not a NativeFarCall at " PTR_FORMAT, addr));
+    fatal(err_msg("not a NativeFarCall at " PTR_FORMAT, p2i(addr)));
   }
 }
 #endif // ASSERT
@@ -306,9 +306,9 @@ void NativeMovConstReg::verify() {
     if (! (cb != NULL && MacroAssembler::is_calculate_address_from_global_toc_at(addr, cb->content_begin())) &&
         ! (cb != NULL && MacroAssembler::is_set_narrow_oop(addr, cb->content_begin())) &&
         ! MacroAssembler::is_bl(*((int*) addr))) {
-      tty->print_cr("not a NativeMovConstReg at " PTR_FORMAT, addr);
+      tty->print_cr("not a NativeMovConstReg at " PTR_FORMAT, p2i(addr));
       // TODO: PPC port: Disassembler::decode(addr, 20, 20, tty);
-      fatal(err_msg("not a NativeMovConstReg at " PTR_FORMAT, addr));
+      fatal(err_msg("not a NativeMovConstReg at " PTR_FORMAT, p2i(addr)));
     }
   }
 }
@@ -344,9 +344,9 @@ void NativeJump::verify() {
 
   NativeInstruction::verify();
   if (!NativeJump::is_jump_at(addr)) {
-    tty->print_cr("not a NativeJump at " PTR_FORMAT, addr);
+    tty->print_cr("not a NativeJump at " PTR_FORMAT, p2i(addr));
     // TODO: PPC port: Disassembler::decode(addr, 20, 20, tty);
-    fatal(err_msg("not a NativeJump at " PTR_FORMAT, addr));
+    fatal(err_msg("not a NativeJump at " PTR_FORMAT, p2i(addr)));
   }
 }
 #endif // ASSERT
diff --git a/hotspot/src/cpu/ppc/vm/ppc.ad b/hotspot/src/cpu/ppc/vm/ppc.ad
index d2d51379a221e9e9e2c4b0f3257307335a399a9d..9087959fe1eea418ce0bec13340e045f13970b00 100644
--- a/hotspot/src/cpu/ppc/vm/ppc.ad
+++ b/hotspot/src/cpu/ppc/vm/ppc.ad
@@ -1329,7 +1329,7 @@ void MachPrologNode::format(PhaseRegAlloc *ra_, outputStream *st) const {
 
   if (!false /* TODO: PPC port C->is_frameless_method()*/) {
     st->print("save return pc\n\t");
-    st->print("push frame %d\n\t", -framesize);
+    st->print("push frame %ld\n\t", -framesize);
   }
 }
 #endif
diff --git a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
index 32fb22ce22962e65c5e019a66eb5f21110eeccfa..28f992f41b83685807995ff9a3f2f6725df69a82 100644
--- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
@@ -352,7 +352,7 @@ void VM_Version::determine_section_size() {
 
   if (PrintAssembly) {
     ttyLocker ttyl;
-    tty->print_cr("Decoding section size detection stub at " INTPTR_FORMAT " before execution:", code);
+    tty->print_cr("Decoding section size detection stub at " INTPTR_FORMAT " before execution:", p2i(code));
     Disassembler::decode((u_char*)code, (u_char*)code_end, tty);
     tty->print_cr("Time loop1 :%f", loop1_seconds);
     tty->print_cr("Time loop2 :%f", loop2_seconds);
@@ -435,7 +435,7 @@ void VM_Version::determine_features() {
   // Print the detection code.
   if (PrintAssembly) {
     ttyLocker ttyl;
-    tty->print_cr("Decoding cpu-feature detection stub at " INTPTR_FORMAT " before execution:", code);
+    tty->print_cr("Decoding cpu-feature detection stub at " INTPTR_FORMAT " before execution:", p2i(code));
     Disassembler::decode((u_char*)code, (u_char*)code_end, tty);
   }
 
@@ -468,7 +468,7 @@ void VM_Version::determine_features() {
   // Print the detection code.
   if (PrintAssembly) {
     ttyLocker ttyl;
-    tty->print_cr("Decoding cpu-feature detection stub at " INTPTR_FORMAT " after execution:", code);
+    tty->print_cr("Decoding cpu-feature detection stub at " INTPTR_FORMAT " after execution:", p2i(code));
     Disassembler::decode((u_char*)code, (u_char*)code_end, tty);
   }
 
diff --git a/hotspot/src/cpu/sparc/vm/compiledIC_sparc.cpp b/hotspot/src/cpu/sparc/vm/compiledIC_sparc.cpp
index 92d494fc0cae44b0ee31fda18be7d1ad42dca08e..a4b2a094a5bf55544f3e9e8e1ab7875658632548 100644
--- a/hotspot/src/cpu/sparc/vm/compiledIC_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/compiledIC_sparc.cpp
@@ -50,34 +50,6 @@ bool CompiledIC::is_icholder_call_site(virtual_call_Relocation* call_site) {
   return is_icholder_entry(call->destination());
 }
 
-//-----------------------------------------------------------------------------
-// High-level access to an inline cache. Guaranteed to be MT-safe.
-
-CompiledIC::CompiledIC(nmethod* nm, NativeCall* call)
-  : _ic_call(call)
-{
-  address ic_call = call->instruction_address();
-
-  assert(ic_call != NULL, "ic_call address must be set");
-  assert(nm != NULL, "must pass nmethod");
-  assert(nm->contains(ic_call), "must be in nmethod");
-
-  // Search for the ic_call at the given address.
-  RelocIterator iter(nm, ic_call, ic_call+1);
-  bool ret = iter.next();
-  assert(ret == true, "relocInfo must exist at this address");
-  assert(iter.addr() == ic_call, "must find ic_call");
-  if (iter.type() == relocInfo::virtual_call_type) {
-    virtual_call_Relocation* r = iter.virtual_call_reloc();
-    _is_optimized = false;
-    _value = nativeMovConstReg_at(r->cached_value());
-  } else {
-    assert(iter.type() == relocInfo::opt_virtual_call_type, "must be a virtual call");
-    _is_optimized = true;
-    _value = NULL;
-  }
-}
-
 // ----------------------------------------------------------------------------
 
 #define __ _masm.
diff --git a/hotspot/src/cpu/sparc/vm/frame_sparc.cpp b/hotspot/src/cpu/sparc/vm/frame_sparc.cpp
index 2feb5eb09255ffb874bc57c85f74898bb58cf073..17b4d9e05acaa31ff34ca8651372dc328ca94263 100644
--- a/hotspot/src/cpu/sparc/vm/frame_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/frame_sparc.cpp
@@ -436,32 +436,6 @@ void frame::set_interpreter_frame_sender_sp(intptr_t* sender_sp) {
 }
 #endif // CC_INTERP
 
-
-#ifdef ASSERT
-// Debugging aid
-static frame nth_sender(int n) {
-  frame f = JavaThread::current()->last_frame();
-
-  for(int i = 0; i < n; ++i)
-    f = f.sender((RegisterMap*)NULL);
-
-  printf("first frame %d\n",          f.is_first_frame()       ? 1 : 0);
-  printf("interpreted frame %d\n",    f.is_interpreted_frame() ? 1 : 0);
-  printf("java frame %d\n",           f.is_java_frame()        ? 1 : 0);
-  printf("entry frame %d\n",          f.is_entry_frame()       ? 1 : 0);
-  printf("native frame %d\n",         f.is_native_frame()      ? 1 : 0);
-  if (f.is_compiled_frame()) {
-    if (f.is_deoptimized_frame())
-      printf("deoptimized frame 1\n");
-    else
-      printf("compiled frame 1\n");
-  }
-
-  return f;
-}
-#endif
-
-
 frame frame::sender_for_entry_frame(RegisterMap *map) const {
   assert(map != NULL, "map must be set");
   // Java frame called from C; skip all C frames and return top C
diff --git a/hotspot/src/cpu/x86/vm/bytecodes_x86.hpp b/hotspot/src/cpu/x86/vm/bytecodes_x86.hpp
deleted file mode 100644
index e21c16a09ae012a033ef42d6f0de7b24d44e4ec1..0000000000000000000000000000000000000000
--- a/hotspot/src/cpu/x86/vm/bytecodes_x86.hpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 1998, 2010, 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 CPU_X86_VM_BYTECODES_X86_HPP
-#define CPU_X86_VM_BYTECODES_X86_HPP
-
-// No i486 specific bytecodes
-
-#endif // CPU_X86_VM_BYTECODES_X86_HPP
diff --git a/hotspot/src/cpu/x86/vm/compiledIC_x86.cpp b/hotspot/src/cpu/x86/vm/compiledIC_x86.cpp
index 26d56b86ab38bc17d6336da48dd73717f5431004..9537ef971f7a22adcde0593566ac0cff48f08c7e 100644
--- a/hotspot/src/cpu/x86/vm/compiledIC_x86.cpp
+++ b/hotspot/src/cpu/x86/vm/compiledIC_x86.cpp
@@ -47,34 +47,6 @@ bool CompiledIC::is_icholder_call_site(virtual_call_Relocation* call_site) {
   return is_icholder_entry(call->destination());
 }
 
-//-----------------------------------------------------------------------------
-// High-level access to an inline cache. Guaranteed to be MT-safe.
-
-CompiledIC::CompiledIC(nmethod* nm, NativeCall* call)
-  : _ic_call(call)
-{
-  address ic_call = call->instruction_address();
-
-  assert(ic_call != NULL, "ic_call address must be set");
-  assert(nm != NULL, "must pass nmethod");
-  assert(nm->contains(ic_call), "must be in nmethod");
-
-  // Search for the ic_call at the given address.
-  RelocIterator iter(nm, ic_call, ic_call+1);
-  bool ret = iter.next();
-  assert(ret == true, "relocInfo must exist at this address");
-  assert(iter.addr() == ic_call, "must find ic_call");
-  if (iter.type() == relocInfo::virtual_call_type) {
-    virtual_call_Relocation* r = iter.virtual_call_reloc();
-    _is_optimized = false;
-    _value = nativeMovConstReg_at(r->cached_value());
-  } else {
-    assert(iter.type() == relocInfo::opt_virtual_call_type, "must be a virtual call");
-    _is_optimized = true;
-    _value = NULL;
-  }
-}
-
 // ----------------------------------------------------------------------------
 
 #define __ _masm.
diff --git a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp
index 265455bf28501aaf0dede5222690bd58b8404c1f..1e49ce1c6a4bb9d5d599968461bbb4d5fc1c5ba3 100644
--- a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp
+++ b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp
@@ -280,6 +280,8 @@ address TemplateInterpreterGenerator::generate_result_handler_for(BasicType type
     case T_BYTE   : __ sign_extend_byte (rax); break;
     case T_SHORT  : __ sign_extend_short(rax); break;
     case T_INT    : /* nothing to do */        break;
+    case T_LONG   : /* nothing to do */        break;
+    case T_VOID   : /* nothing to do */        break;
     case T_DOUBLE :
     case T_FLOAT  :
       { const Register t = InterpreterRuntime::SignatureHandlerGenerator::temp();
diff --git a/hotspot/src/cpu/zero/vm/bytecodes_zero.cpp b/hotspot/src/cpu/zero/vm/bytecodes_zero.cpp
deleted file mode 100644
index e3f801f400af1f1c400d0eda1bbfb04c609b1244..0000000000000000000000000000000000000000
--- a/hotspot/src/cpu/zero/vm/bytecodes_zero.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2007 Red Hat, Inc.
- * 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 "interpreter/bytecodes.hpp"
-
-void Bytecodes::pd_initialize() {
-  // No zero specific initialization
-}
diff --git a/hotspot/src/cpu/zero/vm/bytecodes_zero.hpp b/hotspot/src/cpu/zero/vm/bytecodes_zero.hpp
deleted file mode 100644
index f214bb745123c0e106b5ec7b2cb5e4230b5aa4c7..0000000000000000000000000000000000000000
--- a/hotspot/src/cpu/zero/vm/bytecodes_zero.hpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2009 Red Hat, Inc.
- * 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 CPU_ZERO_VM_BYTECODES_ZERO_HPP
-#define CPU_ZERO_VM_BYTECODES_ZERO_HPP
-
-// This file is intentionally empty
-
-#endif // CPU_ZERO_VM_BYTECODES_ZERO_HPP
diff --git a/hotspot/src/cpu/zero/vm/compiledIC_zero.cpp b/hotspot/src/cpu/zero/vm/compiledIC_zero.cpp
index 6fa39ea078b7d5c94e5bfe5b53bd429b9dd0d725..143dc31738090153bdd93fee47e33e3153919db0 100644
--- a/hotspot/src/cpu/zero/vm/compiledIC_zero.cpp
+++ b/hotspot/src/cpu/zero/vm/compiledIC_zero.cpp
@@ -58,34 +58,6 @@ bool CompiledIC::is_icholder_call_site(virtual_call_Relocation* call_site) {
   return is_icholder_entry(call->destination());
 }
 
-//-----------------------------------------------------------------------------
-// High-level access to an inline cache. Guaranteed to be MT-safe.
-
-CompiledIC::CompiledIC(nmethod* nm, NativeCall* call)
-  : _ic_call(call)
-{
-  address ic_call = call->instruction_address();
-
-  assert(ic_call != NULL, "ic_call address must be set");
-  assert(nm != NULL, "must pass nmethod");
-  assert(nm->contains(ic_call), "must be in nmethod");
-
-  // Search for the ic_call at the given address.
-  RelocIterator iter(nm, ic_call, ic_call+1);
-  bool ret = iter.next();
-  assert(ret == true, "relocInfo must exist at this address");
-  assert(iter.addr() == ic_call, "must find ic_call");
-  if (iter.type() == relocInfo::virtual_call_type) {
-    virtual_call_Relocation* r = iter.virtual_call_reloc();
-    _is_optimized = false;
-    _value = nativeMovConstReg_at(r->cached_value());
-  } else {
-    assert(iter.type() == relocInfo::opt_virtual_call_type, "must be a virtual call");
-    _is_optimized = true;
-    _value = NULL;
-  }
-}
-
 // ----------------------------------------------------------------------------
 
 void CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
diff --git a/hotspot/src/cpu/zero/vm/cppInterpreter_zero.cpp b/hotspot/src/cpu/zero/vm/cppInterpreter_zero.cpp
index 9272724addcc49c4f703c1cf3d12e082ae9f59df..fe9115be9eca3bac3ce0f5dfe1b75d1e99fed97c 100644
--- a/hotspot/src/cpu/zero/vm/cppInterpreter_zero.cpp
+++ b/hotspot/src/cpu/zero/vm/cppInterpreter_zero.cpp
@@ -37,6 +37,7 @@
 #include "prims/jvmtiExport.hpp"
 #include "prims/jvmtiThreadState.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/deoptimization.hpp"
 #include "runtime/frame.inline.hpp"
 #include "runtime/interfaceSupport.hpp"
diff --git a/hotspot/src/os/aix/vm/osThread_aix.cpp b/hotspot/src/os/aix/vm/osThread_aix.cpp
index 11f9c39168e4bce668241d1feae9f429f9aada83..5c56387163c9fe4551b16fd4f01497555481a71a 100644
--- a/hotspot/src/os/aix/vm/osThread_aix.cpp
+++ b/hotspot/src/os/aix/vm/osThread_aix.cpp
@@ -24,17 +24,13 @@
  */
 
 // no precompiled headers
-#include "runtime/atomic.hpp"
+
 #include "runtime/handles.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/os.hpp"
 #include "runtime/osThread.hpp"
 #include "runtime/safepoint.hpp"
 #include "runtime/vmThread.hpp"
-#ifdef TARGET_ARCH_ppc
-# include "assembler_ppc.inline.hpp"
-#endif
-
 
 void OSThread::pd_initialize() {
   assert(this != NULL, "check");
diff --git a/hotspot/src/os/aix/vm/os_aix.cpp b/hotspot/src/os/aix/vm/os_aix.cpp
index e9d57c580ceeaf38ccf9d13e8470cca3251991f9..febc7260c48dd6927c2406bd1e4fd5625ed9e8bf 100644
--- a/hotspot/src/os/aix/vm/os_aix.cpp
+++ b/hotspot/src/os/aix/vm/os_aix.cpp
@@ -48,6 +48,7 @@
 #include "prims/jvm.h"
 #include "prims/jvm_misc.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/extendedPC.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/interfaceSupport.hpp"
@@ -2812,13 +2813,6 @@ void os::yield() {
 
 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; }
 
-void os::yield_all() {
-  // Yields to all threads, including threads with lower priorities
-  // Threads on Linux are all with same priority. The Solaris style
-  // os::yield_all() with nanosleep(1ms) is not necessary.
-  sched_yield();
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // thread priority support
 
@@ -3075,7 +3069,7 @@ static bool do_suspend(OSThread* osthread) {
 
   for (int n = 0; !osthread->sr.is_suspended(); n++) {
     for (int i = 0; i < RANDOMLY_LARGE_INTEGER2 && !osthread->sr.is_suspended(); i++) {
-      os::yield_all();
+      os::yield();
     }
 
     // timeout, try to cancel the request
@@ -3109,7 +3103,7 @@ static void do_resume(OSThread* osthread) {
     if (sr_notify(osthread) == 0) {
       for (int n = 0; n < RANDOMLY_LARGE_INTEGER && !osthread->sr.is_running(); n++) {
         for (int i = 0; i < 100 && !osthread->sr.is_running(); i++) {
-          os::yield_all();
+          os::yield();
         }
       }
     } else {
diff --git a/hotspot/src/os/bsd/vm/os_bsd.cpp b/hotspot/src/os/bsd/vm/os_bsd.cpp
index 7facffe684d0fd20744ffa6497e1738a71e28ce2..0c3a047f4608fada7fdfb47e39625d647244a8b1 100644
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp
@@ -41,6 +41,7 @@
 #include "prims/jvm.h"
 #include "prims/jvm_misc.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/extendedPC.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/interfaceSupport.hpp"
@@ -2600,13 +2601,6 @@ void os::yield() {
 
 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; }
 
-void os::yield_all() {
-  // Yields to all threads, including threads with lower priorities
-  // Threads on Bsd are all with same priority. The Solaris style
-  // os::yield_all() with nanosleep(1ms) is not necessary.
-  sched_yield();
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // thread priority support
 
diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp
index 7057bcd557b39f3a251c7a899a21d19cf529292c..847095fc77273dd2cfa75e8b5e910dc8c614459a 100644
--- a/hotspot/src/os/linux/vm/os_linux.cpp
+++ b/hotspot/src/os/linux/vm/os_linux.cpp
@@ -41,6 +41,7 @@
 #include "prims/jvm.h"
 #include "prims/jvm_misc.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/extendedPC.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/interfaceSupport.hpp"
@@ -3795,13 +3796,6 @@ void os::yield() {
 
 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; }
 
-void os::yield_all() {
-  // Yields to all threads, including threads with lower priorities
-  // Threads on Linux are all with same priority. The Solaris style
-  // os::yield_all() with nanosleep(1ms) is not necessary.
-  sched_yield();
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // thread priority support
 
diff --git a/hotspot/src/os/solaris/vm/osThread_solaris.cpp b/hotspot/src/os/solaris/vm/osThread_solaris.cpp
index 2ccd164e15b75ff14b25b519ada2a337af6b0e0d..d0e945c0246b34cf15ffdfe399d819a5d7d0d374 100644
--- a/hotspot/src/os/solaris/vm/osThread_solaris.cpp
+++ b/hotspot/src/os/solaris/vm/osThread_solaris.cpp
@@ -23,7 +23,6 @@
  */
 
 // no precompiled headers
-#include "runtime/atomic.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/os.hpp"
diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp
index 77cc8abb192f5502e70541cd5102aa1d372b7a50..5946fa258210ec3af4970594cf75de5180d0f13f 100644
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp
@@ -41,6 +41,7 @@
 #include "prims/jvm.h"
 #include "prims/jvm_misc.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/extendedPC.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/interfaceSupport.hpp"
@@ -3186,11 +3187,6 @@ void os::yield() {
 
 os::YieldResult os::NakedYield() { thr_yield(); return os::YIELD_UNKNOWN; }
 
-void os::yield_all() {
-  // Yields to all threads, including threads with lower priorities
-  os::sleep(Thread::current(), 1, false);
-}
-
 // Interface for setting lwp priorities.  If we are using T2 libthread,
 // which forces the use of BoundThreads or we manually set UseBoundThreads,
 // all of our threads will be assigned to real lwp's.  Using the thr_setprio
diff --git a/hotspot/src/os/solaris/vm/thread_solaris.inline.hpp b/hotspot/src/os/solaris/vm/thread_solaris.inline.hpp
index d7d6d378f1a6f34d88edce87d5769e32571423cc..b5355335f39e5974c6269c2935e5b0f6b59e1393 100644
--- a/hotspot/src/os/solaris/vm/thread_solaris.inline.hpp
+++ b/hotspot/src/os/solaris/vm/thread_solaris.inline.hpp
@@ -29,7 +29,6 @@
 #error "This file should only be included from thread.inline.hpp"
 #endif
 
-#include "runtime/atomic.inline.hpp"
 #include "runtime/thread.hpp"
 #include "runtime/threadLocalStorage.hpp"
 
diff --git a/hotspot/src/os/windows/vm/osThread_windows.cpp b/hotspot/src/os/windows/vm/osThread_windows.cpp
index d65d0d6f55741780e2c13d5b40be5207b3996919..7e8877a209914fb7b5daef013e4e577e8076a646 100644
--- a/hotspot/src/os/windows/vm/osThread_windows.cpp
+++ b/hotspot/src/os/windows/vm/osThread_windows.cpp
@@ -23,7 +23,6 @@
  */
 
 // no precompiled headers
-#include "runtime/atomic.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/os.hpp"
diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp
index e3ca08a747eec887c42a9c9af0dc92647404c33e..b16362421b76d2a56fd13520c9a5c7cb7be1bf85 100644
--- a/hotspot/src/os/windows/vm/os_windows.cpp
+++ b/hotspot/src/os/windows/vm/os_windows.cpp
@@ -44,6 +44,7 @@
 #include "prims/jvm.h"
 #include "prims/jvm_misc.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/extendedPC.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/interfaceSupport.hpp"
@@ -3526,11 +3527,6 @@ os::YieldResult os::NakedYield() {
 
 void os::yield() {  os::NakedYield(); }
 
-void os::yield_all() {
-  // Yields to all threads, including threads with lower priorities
-  Sleep(1);
-}
-
 // Win32 only gives you access to seven real priorities at a time,
 // so we compress Java's ten down to seven.  It would be better
 // if we dynamically adjusted relative priorities.
diff --git a/hotspot/src/os/windows/vm/threadCritical_windows.cpp b/hotspot/src/os/windows/vm/threadCritical_windows.cpp
index c61a29617101a214323306f55689c2d70f16d80e..3ea83c1acb635f0e9b91b82a827209bbe904293b 100644
--- a/hotspot/src/os/windows/vm/threadCritical_windows.cpp
+++ b/hotspot/src/os/windows/vm/threadCritical_windows.cpp
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/thread.inline.hpp"
 #include "runtime/threadCritical.hpp"
 
diff --git a/hotspot/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp b/hotspot/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp
index ccfd54ba9deed7c3c4bca48711de9ee4f0b1b49f..d7fd74d219a681ff964e4ebfd550264282d0e112 100644
--- a/hotspot/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp
+++ b/hotspot/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2012, 2014 SAP AG. 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
@@ -307,7 +307,7 @@ JVM_handle_linux_signal(int sig,
                // doesn't work for us. We use:
                ((NativeInstruction*)pc)->is_safepoint_poll()) {
         if (TraceTraps) {
-          tty->print_cr("trap: safepoint_poll at " INTPTR_FORMAT " (SIGSEGV)", pc);
+          tty->print_cr("trap: safepoint_poll at " INTPTR_FORMAT " (SIGSEGV)", p2i(pc));
         }
         stub = SharedRuntime::get_poll_stub(pc);
       }
@@ -316,7 +316,7 @@ JVM_handle_linux_signal(int sig,
       else if (sig == SIGTRAP && TrapBasedICMissChecks &&
                nativeInstruction_at(pc)->is_sigtrap_ic_miss_check()) {
         if (TraceTraps) {
-          tty->print_cr("trap: ic_miss_check at " INTPTR_FORMAT " (SIGTRAP)", pc);
+          tty->print_cr("trap: ic_miss_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
         }
         stub = SharedRuntime::get_ic_miss_stub();
       }
@@ -325,7 +325,7 @@ JVM_handle_linux_signal(int sig,
       else if (sig == SIGTRAP && TrapBasedNullChecks &&
                nativeInstruction_at(pc)->is_sigtrap_null_check()) {
         if (TraceTraps) {
-          tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGTRAP)", pc);
+          tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
         }
         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
       }
@@ -335,7 +335,7 @@ JVM_handle_linux_signal(int sig,
                CodeCache::contains((void*) pc) &&
                !MacroAssembler::needs_explicit_null_check((intptr_t) info->si_addr)) {
         if (TraceTraps) {
-          tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGSEGV)", pc);
+          tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGSEGV)", p2i(pc));
         }
         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
       }
@@ -345,7 +345,7 @@ JVM_handle_linux_signal(int sig,
       else if (sig == SIGTRAP && TrapBasedRangeChecks &&
                nativeInstruction_at(pc)->is_sigtrap_range_check()) {
         if (TraceTraps) {
-          tty->print_cr("trap: range_check at " INTPTR_FORMAT " (SIGTRAP)", pc);
+          tty->print_cr("trap: range_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
         }
         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
       }
@@ -572,7 +572,7 @@ void os::print_context(outputStream *st, void *context) {
   st->cr();
 
   intptr_t *sp = (intptr_t *)os::Linux::ucontext_get_sp(uc);
-  st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", sp);
+  st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", p2i(sp));
   print_hex_dump(st, (address)sp, (address)(sp + 128), sizeof(intptr_t));
   st->cr();
 
@@ -580,7 +580,7 @@ void os::print_context(outputStream *st, void *context) {
   // point to garbage if entry point in an nmethod is corrupted. Leave
   // this at the end, and hope for the best.
   address pc = os::Linux::ucontext_get_pc(uc);
-  st->print_cr("Instructions: (pc=" PTR_FORMAT ")", pc);
+  st->print_cr("Instructions: (pc=" PTR_FORMAT ")", p2i(pc));
   print_hex_dump(st, pc - 64, pc + 64, /*instrsize=*/4);
   st->cr();
 }
diff --git a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp
index e78a2dba30bb4ee7591101ce7e340da11f9373fe..7eccbe47013c4d6a103b4f36b8a23c2c1bfd0e31 100644
--- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp
+++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp
@@ -38,6 +38,7 @@
 #include "prims/jvm.h"
 #include "prims/jvm_misc.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/extendedPC.hpp"
 #include "runtime/frame.inline.hpp"
 #include "runtime/interfaceSupport.hpp"
diff --git a/hotspot/src/share/vm/asm/assembler.cpp b/hotspot/src/share/vm/asm/assembler.cpp
index 274aa872e6f29098fcd605691e3c0fa2a0d89bea..2141d93b0dac634a44c3ba8983aeb19171ee3deb 100644
--- a/hotspot/src/share/vm/asm/assembler.cpp
+++ b/hotspot/src/share/vm/asm/assembler.cpp
@@ -26,7 +26,6 @@
 #include "asm/macroAssembler.hpp"
 #include "asm/macroAssembler.inline.hpp"
 #include "asm/codeBuffer.hpp"
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/icache.hpp"
 #include "runtime/os.hpp"
diff --git a/hotspot/src/share/vm/c1/c1_Runtime1.cpp b/hotspot/src/share/vm/c1/c1_Runtime1.cpp
index 3c2e2ecf8feee46fb3169da64acfc5b55bea1a2b..a472718a64ecb291e78ce2aa959cc712748e6624 100644
--- a/hotspot/src/share/vm/c1/c1_Runtime1.cpp
+++ b/hotspot/src/share/vm/c1/c1_Runtime1.cpp
@@ -47,6 +47,7 @@
 #include "memory/resourceArea.hpp"
 #include "oops/objArrayKlass.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/compilationPolicy.hpp"
 #include "runtime/interfaceSupport.hpp"
diff --git a/hotspot/src/share/vm/ci/ciConstantPoolCache.cpp b/hotspot/src/share/vm/ci/ciConstantPoolCache.cpp
index a277e421a32609430b562b5e7bb7566aea21ae8e..6ceacdc5a5a9ba50a9d46290c3d142e8d8ecc159 100644
--- a/hotspot/src/share/vm/ci/ciConstantPoolCache.cpp
+++ b/hotspot/src/share/vm/ci/ciConstantPoolCache.cpp
@@ -38,7 +38,7 @@ ciConstantPoolCache::ciConstantPoolCache(Arena* arena,
                                  int expected_size) {
   _elements =
     new (arena) GrowableArray<void*>(arena, expected_size, 0, 0);
-  _keys = new (arena) GrowableArray<intptr_t>(arena, expected_size, 0, 0);
+  _keys = new (arena) GrowableArray<int>(arena, expected_size, 0, 0);
 }
 
 // ------------------------------------------------------------------
diff --git a/hotspot/src/share/vm/ci/ciConstantPoolCache.hpp b/hotspot/src/share/vm/ci/ciConstantPoolCache.hpp
index 30ebcac20795f8e67d0d12416750f5a68ab8250c..17cf77681e0d66b443e1d7e39df43cc6d30c2442 100644
--- a/hotspot/src/share/vm/ci/ciConstantPoolCache.hpp
+++ b/hotspot/src/share/vm/ci/ciConstantPoolCache.hpp
@@ -35,7 +35,7 @@
 // Usage note: this klass has nothing to do with ConstantPoolCache*.
 class ciConstantPoolCache : public ResourceObj {
 private:
-  GrowableArray<intptr_t>*   _keys;
+  GrowableArray<int>*   _keys;
   GrowableArray<void*>* _elements;
 
   int find(int index);
diff --git a/hotspot/src/share/vm/ci/ciEnv.cpp b/hotspot/src/share/vm/ci/ciEnv.cpp
index fbe7bbbd83c2c3e97179f99e0dd824d508d6e1d5..18cf9add331dcc9e75d22f102d8777814e0c2366 100644
--- a/hotspot/src/share/vm/ci/ciEnv.cpp
+++ b/hotspot/src/share/vm/ci/ciEnv.cpp
@@ -512,24 +512,9 @@ ciKlass* ciEnv::get_klass_by_index_impl(constantPoolHandle cpool,
   } else {
     // Check if it's resolved if it's not a symbol constant pool entry.
     klass = KlassHandle(THREAD, ConstantPool::klass_at_if_loaded(cpool, index));
-
-  if (klass.is_null()) {
-    // The klass has not been inserted into the constant pool.
     // Try to look it up by name.
-    {
-      // We have to lock the cpool to keep the oop from being resolved
-      // while we are accessing it.
-        MonitorLockerEx ml(cpool->lock());
-      constantTag tag = cpool->tag_at(index);
-      if (tag.is_klass()) {
-        // The klass has been inserted into the constant pool
-        // very recently.
-        klass = KlassHandle(THREAD, cpool->resolved_klass_at(index));
-      } else {
-        assert(cpool->tag_at(index).is_unresolved_klass(), "wrong tag");
-        klass_name = cpool->unresolved_klass_at(index);
-      }
-    }
+  if (klass.is_null()) {
+      klass_name = cpool->klass_name_at(index);
   }
   }
 
diff --git a/hotspot/src/share/vm/ci/ciReplay.cpp b/hotspot/src/share/vm/ci/ciReplay.cpp
index 51897b26300662c018041a343b14f44d9bff589c..99b742d61dde92517ab95b4f330095bddc2f556c 100644
--- a/hotspot/src/share/vm/ci/ciReplay.cpp
+++ b/hotspot/src/share/vm/ci/ciReplay.cpp
@@ -1,4 +1,4 @@
-/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2013, 2014, 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
@@ -686,7 +686,7 @@ class CompileReplay : public StackObj {
       switch (cp->tag_at(i).value()) {
         case JVM_CONSTANT_UnresolvedClass: {
           if (tag == JVM_CONSTANT_Class) {
-            tty->print_cr("Resolving klass %s at %d", cp->unresolved_klass_at(i)->as_utf8(), i);
+            tty->print_cr("Resolving klass %s at %d", cp->klass_name_at(i)->as_utf8(), i);
             Klass* k = cp->klass_at(i, CHECK);
           }
           break;
diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp
index 3ea6d0c9aee6ea1f1b12f97238d7ad1189759641..e58b280b07bb576bc1a5f440a8900f026472bf7c 100644
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp
@@ -510,7 +510,7 @@ constantPoolHandle ClassFileParser::parse_constant_pool(TRAPS) {
     jbyte tag = cp->tag_at(index).value();
     switch (tag) {
       case JVM_CONSTANT_UnresolvedClass: {
-        Symbol*  class_name = cp->unresolved_klass_at(index);
+        Symbol*  class_name = cp->klass_name_at(index);
         // check the name, even if _cp_patches will overwrite it
         verify_legal_class_name(class_name, CHECK_(nullHandle));
         break;
@@ -3161,7 +3161,7 @@ instanceKlassHandle ClassFileParser::parse_super_class(int super_class_index,
       if (_need_verify)
         is_array = super_klass->oop_is_array();
     } else if (_need_verify) {
-      is_array = (_cp->unresolved_klass_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
+      is_array = (_cp->klass_name_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
     }
     if (_need_verify) {
       guarantee_property(!is_array,
@@ -3855,7 +3855,7 @@ instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name,
     "Invalid this class index %u in constant pool in class file %s",
     this_class_index, CHECK_(nullHandle));
 
-  Symbol*  class_name  = cp->unresolved_klass_at(this_class_index);
+  Symbol*  class_name  = cp->klass_name_at(this_class_index);
   assert(class_name != NULL, "class_name can't be null");
 
   // It's important to set parsed_name *before* resolving the super class.
@@ -4139,8 +4139,8 @@ instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name,
     }
 
     // Allocate mirror and initialize static fields
-    java_lang_Class::create_mirror(this_klass, protection_domain, CHECK_(nullHandle));
-
+    java_lang_Class::create_mirror(this_klass, class_loader, protection_domain,
+                                   CHECK_(nullHandle));
 
     // Generate any default methods - default methods are interface methods
     // that have a default implementation.  This is new with Lambda project.
diff --git a/hotspot/src/share/vm/classfile/classLoaderData.cpp b/hotspot/src/share/vm/classfile/classLoaderData.cpp
index efbde89ee30a8fe593106543ff994fd2e6bb9284..d04c46b7dde2da23ebeb44d4789541147344440c 100644
--- a/hotspot/src/share/vm/classfile/classLoaderData.cpp
+++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp
@@ -57,6 +57,7 @@
 #include "memory/metadataFactory.hpp"
 #include "memory/metaspaceShared.hpp"
 #include "memory/oopFactory.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/jniHandles.hpp"
 #include "runtime/mutex.hpp"
 #include "runtime/safepoint.hpp"
@@ -549,6 +550,7 @@ bool ClassLoaderData::contains_klass(Klass* klass) {
 // GC root of class loader data created.
 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
+ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 
 bool ClassLoaderDataGraph::_should_purge = false;
@@ -656,7 +658,9 @@ void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
 
 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
-  for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
+  // Only walk the head until any clds not purged from prior unloading
+  // (CMS doesn't purge right away).
+  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
     cld->classes_do(f);
   }
 }
@@ -704,6 +708,11 @@ bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure) {
   ClassLoaderData* data = _head;
   ClassLoaderData* prev = NULL;
   bool seen_dead_loader = false;
+
+  // Save previous _unloading pointer for CMS which may add to unloading list before
+  // purging and we don't want to rewalk the previously unloaded class loader data.
+  _saved_unloading = _unloading;
+
   // mark metadata seen on the stack and code cache so we can delete
   // unneeded entries.
   bool has_redefined_a_class = JvmtiExport::has_redefined_a_class();
diff --git a/hotspot/src/share/vm/classfile/classLoaderData.hpp b/hotspot/src/share/vm/classfile/classLoaderData.hpp
index 964e4289ffea4f987cfb1f7013fc46c2d5122a8c..35088a7fbbe8ffca9f6695419646085e20f3c21b 100644
--- a/hotspot/src/share/vm/classfile/classLoaderData.hpp
+++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp
@@ -66,6 +66,7 @@ class ClassLoaderDataGraph : public AllStatic {
   static ClassLoaderData* _unloading;
   // CMS support.
   static ClassLoaderData* _saved_head;
+  static ClassLoaderData* _saved_unloading;
   static bool _should_purge;
 
   static ClassLoaderData* add(Handle class_loader, bool anonymous, TRAPS);
@@ -187,8 +188,6 @@ class ClassLoaderData : public CHeapObj<mtClass> {
   JNIHandleBlock* handles() const;
   void set_handles(JNIHandleBlock* handles);
 
-  Mutex* metaspace_lock() const { return _metaspace_lock; }
-
   // GC interface.
   void clear_claimed()          { _claimed = 0; }
   bool claimed() const          { return _claimed == 1; }
@@ -216,6 +215,8 @@ class ClassLoaderData : public CHeapObj<mtClass> {
     return _the_null_class_loader_data;
   }
 
+  Mutex* metaspace_lock() const { return _metaspace_lock; }
+
   bool is_anonymous() const { return _is_anonymous; }
 
   static void init_null_class_loader_data() {
diff --git a/hotspot/src/share/vm/classfile/javaClasses.cpp b/hotspot/src/share/vm/classfile/javaClasses.cpp
index 0e61ff9f391ca13c68c8b859827f9b29e0fb9a8f..d4fa4642661f0118015aba53928041a69fe977d3 100644
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp
@@ -558,7 +558,7 @@ void java_lang_Class::fixup_mirror(KlassHandle k, TRAPS) {
       }
     }
   }
-  create_mirror(k, Handle(NULL), CHECK);
+  create_mirror(k, Handle(NULL), Handle(NULL), CHECK);
 }
 
 void java_lang_Class::initialize_mirror_fields(KlassHandle k,
@@ -578,7 +578,8 @@ void java_lang_Class::initialize_mirror_fields(KlassHandle k,
   InstanceKlass::cast(k())->do_local_static_fields(&initialize_static_field, mirror, CHECK);
 }
 
-void java_lang_Class::create_mirror(KlassHandle k, Handle protection_domain, TRAPS) {
+void java_lang_Class::create_mirror(KlassHandle k, Handle class_loader,
+                                    Handle protection_domain, TRAPS) {
   assert(k->java_mirror() == NULL, "should only assign mirror once");
   // Use this moment of initialization to cache modifier_flags also,
   // to support Class.getModifiers().  Instance classes recalculate
@@ -633,6 +634,9 @@ void java_lang_Class::create_mirror(KlassHandle k, Handle protection_domain, TRA
       }
     }
 
+    // set the classLoader field in the java_lang_Class instance
+    set_class_loader(mirror(), class_loader());
+
     // Setup indirection from klass->mirror last
     // after any exceptions can happen during allocations.
     if (!k.is_null()) {
@@ -694,6 +698,18 @@ void java_lang_Class::set_signers(oop java_class, objArrayOop signers) {
 }
 
 
+void java_lang_Class::set_class_loader(oop java_class, oop loader) {
+  // jdk7 runs Queens in bootstrapping and jdk8-9 has no coordinated pushes yet.
+  if (_class_loader_offset != 0) {
+    java_class->obj_field_put(_class_loader_offset, loader);
+  }
+}
+
+oop java_lang_Class::class_loader(oop java_class) {
+  assert(_class_loader_offset != 0, "must be set");
+  return java_class->obj_field(_class_loader_offset);
+}
+
 oop java_lang_Class::create_basic_type_mirror(const char* basic_type_name, BasicType type, TRAPS) {
   // This should be improved by adding a field at the Java level or by
   // introducing a new VM klass (see comment in ClassFileParser)
@@ -853,6 +869,12 @@ void java_lang_Class::compute_offsets() {
   compute_optional_offset(classRedefinedCount_offset,
                           klass_oop, vmSymbols::classRedefinedCount_name(), vmSymbols::int_signature());
 
+  // Needs to be optional because the old build runs Queens during bootstrapping
+  // and jdk8-9 doesn't have coordinated pushes yet.
+  compute_optional_offset(_class_loader_offset,
+                 klass_oop, vmSymbols::classLoader_name(),
+                 vmSymbols::classloader_signature());
+
   CLASS_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
@@ -3073,6 +3095,7 @@ int java_lang_Class::_klass_offset;
 int java_lang_Class::_array_klass_offset;
 int java_lang_Class::_oop_size_offset;
 int java_lang_Class::_static_oop_field_count_offset;
+int java_lang_Class::_class_loader_offset;
 int java_lang_Class::_protection_domain_offset;
 int java_lang_Class::_init_lock_offset;
 int java_lang_Class::_signers_offset;
diff --git a/hotspot/src/share/vm/classfile/javaClasses.hpp b/hotspot/src/share/vm/classfile/javaClasses.hpp
index 60c65fe968af08bb875c2800b4d341a660603a00..2c25b6e6c51e7c7c5b3de42495543307ae287342 100644
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp
@@ -240,19 +240,23 @@ class java_lang_Class : AllStatic {
   static int _protection_domain_offset;
   static int _init_lock_offset;
   static int _signers_offset;
+  static int _class_loader_offset;
 
   static bool offsets_computed;
   static int classRedefinedCount_offset;
+
   static GrowableArray<Klass*>* _fixup_mirror_list;
 
   static void set_init_lock(oop java_class, oop init_lock);
   static void set_protection_domain(oop java_class, oop protection_domain);
+  static void set_class_loader(oop java_class, oop class_loader);
   static void initialize_mirror_fields(KlassHandle k, Handle mirror, Handle protection_domain, TRAPS);
  public:
   static void compute_offsets();
 
   // Instance creation
-  static void create_mirror(KlassHandle k, Handle protection_domain, TRAPS);
+  static void create_mirror(KlassHandle k, Handle class_loader,
+                            Handle protection_domain, TRAPS);
   static void fixup_mirror(KlassHandle k, TRAPS);
   static oop  create_basic_type_mirror(const char* basic_type_name, BasicType type, TRAPS);
   // Conversion
@@ -290,6 +294,8 @@ class java_lang_Class : AllStatic {
   static objArrayOop  signers(oop java_class);
   static void set_signers(oop java_class, objArrayOop signers);
 
+  static oop class_loader(oop java_class);
+
   static int oop_size(oop java_class);
   static void set_oop_size(oop java_class, int size);
   static int static_oop_field_count(oop java_class);
diff --git a/hotspot/src/share/vm/classfile/stringTable.cpp b/hotspot/src/share/vm/classfile/stringTable.cpp
index 07ccbd354dc4edf72a2aa0ef32104fabb36b8ac6..4958e5ce7ee92882b6e58325e7fc135783bb39cf 100644
--- a/hotspot/src/share/vm/classfile/stringTable.cpp
+++ b/hotspot/src/share/vm/classfile/stringTable.cpp
@@ -33,6 +33,7 @@
 #include "memory/gcLocker.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oop.inline2.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "utilities/hashtable.inline.hpp"
 #if INCLUDE_ALL_GCS
diff --git a/hotspot/src/share/vm/classfile/symbolTable.cpp b/hotspot/src/share/vm/classfile/symbolTable.cpp
index dddf271e42a64b3b4652c699cdfda571d62ad019..00761e478ad5754085dca38e37e3c64608f0de26 100644
--- a/hotspot/src/share/vm/classfile/symbolTable.cpp
+++ b/hotspot/src/share/vm/classfile/symbolTable.cpp
@@ -33,6 +33,7 @@
 #include "memory/gcLocker.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oop.inline2.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "utilities/hashtable.inline.hpp"
 
diff --git a/hotspot/src/share/vm/classfile/vmSymbols.hpp b/hotspot/src/share/vm/classfile/vmSymbols.hpp
index 2a15564bdbf8d386ece223631dd82fd5532ef507..d583ea5876e9c0cf76b43fd54a9fd337eb3406be 100644
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp
@@ -572,6 +572,7 @@
   template(serializePropertiesToByteArray_signature,   "()[B")                                                    \
   template(serializeAgentPropertiesToByteArray_name,   "serializeAgentPropertiesToByteArray")                     \
   template(classRedefinedCount_name,                   "classRedefinedCount")                                     \
+  template(classLoader_name,                           "classLoader")                                             \
                                                                                                                   \
   /* trace signatures */                                                                                          \
   TRACE_TEMPLATES(template)                                                                                       \
diff --git a/hotspot/src/share/vm/code/compiledIC.cpp b/hotspot/src/share/vm/code/compiledIC.cpp
index 9a038164689390f12c5571f12129787cd2e580b1..2ce7c3c67934021c1a703a6a0ee1354ccf2c9809 100644
--- a/hotspot/src/share/vm/code/compiledIC.cpp
+++ b/hotspot/src/share/vm/code/compiledIC.cpp
@@ -159,6 +159,30 @@ address CompiledIC::stub_address() const {
 //-----------------------------------------------------------------------------
 // High-level access to an inline cache. Guaranteed to be MT-safe.
 
+CompiledIC::CompiledIC(nmethod* nm, NativeCall* call)
+  : _ic_call(call)
+{
+  address ic_call = call->instruction_address();
+
+  assert(ic_call != NULL, "ic_call address must be set");
+  assert(nm != NULL, "must pass nmethod");
+  assert(nm->contains(ic_call), "must be in nmethod");
+
+  // Search for the ic_call at the given address.
+  RelocIterator iter(nm, ic_call, ic_call+1);
+  bool ret = iter.next();
+  assert(ret == true, "relocInfo must exist at this address");
+  assert(iter.addr() == ic_call, "must find ic_call");
+  if (iter.type() == relocInfo::virtual_call_type) {
+    virtual_call_Relocation* r = iter.virtual_call_reloc();
+    _is_optimized = false;
+    _value = nativeMovConstReg_at(r->cached_value());
+  } else {
+    assert(iter.type() == relocInfo::opt_virtual_call_type, "must be a virtual call");
+    _is_optimized = true;
+    _value = NULL;
+  }
+}
 
 bool CompiledIC::set_to_megamorphic(CallInfo* call_info, Bytecodes::Code bytecode, TRAPS) {
   assert(CompiledIC_lock->is_locked() || SafepointSynchronize::is_at_safepoint(), "");
diff --git a/hotspot/src/share/vm/code/nmethod.cpp b/hotspot/src/share/vm/code/nmethod.cpp
index 86264436755ebc366e391beca69d457b1630011d..795c700fa1b6208feaaaee629b12d983f8e44336 100644
--- a/hotspot/src/share/vm/code/nmethod.cpp
+++ b/hotspot/src/share/vm/code/nmethod.cpp
@@ -37,6 +37,7 @@
 #include "oops/methodData.hpp"
 #include "prims/jvmtiRedefineClassesTrace.hpp"
 #include "prims/jvmtiImpl.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.inline.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/sweeper.hpp"
@@ -363,27 +364,30 @@ void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
   set_exception_cache(new_entry);
 }
 
-void nmethod::remove_from_exception_cache(ExceptionCache* ec) {
+void nmethod::clean_exception_cache(BoolObjectClosure* is_alive) {
   ExceptionCache* prev = NULL;
   ExceptionCache* curr = exception_cache();
-  assert(curr != NULL, "nothing to remove");
-  // find the previous and next entry of ec
-  while (curr != ec) {
-    prev = curr;
-    curr = curr->next();
-    assert(curr != NULL, "ExceptionCache not found");
-  }
-  // now: curr == ec
-  ExceptionCache* next = curr->next();
-  if (prev == NULL) {
-    set_exception_cache(next);
-  } else {
-    prev->set_next(next);
+
+  while (curr != NULL) {
+    ExceptionCache* next = curr->next();
+
+    Klass* ex_klass = curr->exception_type();
+    if (ex_klass != NULL && !ex_klass->is_loader_alive(is_alive)) {
+      if (prev == NULL) {
+        set_exception_cache(next);
+      } else {
+        prev->set_next(next);
+      }
+      delete curr;
+      // prev stays the same.
+    } else {
+      prev = curr;
+    }
+
+    curr = next;
   }
-  delete curr;
 }
 
-
 // public method for accessing the exception cache
 // These are the public access methods.
 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
@@ -668,8 +672,10 @@ nmethod::nmethod(
     _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
 
     code_buffer->copy_values_to(this);
-    if (ScavengeRootsInCode && detect_scavenge_root_oops()) {
-      CodeCache::add_scavenge_root_nmethod(this);
+    if (ScavengeRootsInCode) {
+      if (detect_scavenge_root_oops()) {
+        CodeCache::add_scavenge_root_nmethod(this);
+      }
       Universe::heap()->register_nmethod(this);
     }
     debug_only(verify_scavenge_root_oops());
@@ -753,8 +759,10 @@ nmethod::nmethod(
     _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
 
     code_buffer->copy_values_to(this);
-    if (ScavengeRootsInCode && detect_scavenge_root_oops()) {
-      CodeCache::add_scavenge_root_nmethod(this);
+    if (ScavengeRootsInCode) {
+      if (detect_scavenge_root_oops()) {
+        CodeCache::add_scavenge_root_nmethod(this);
+      }
       Universe::heap()->register_nmethod(this);
     }
     DEBUG_ONLY(verify_scavenge_root_oops();)
@@ -869,8 +877,10 @@ nmethod::nmethod(
     code_buffer->copy_values_to(this);
     debug_info->copy_to(this);
     dependencies->copy_to(this);
-    if (ScavengeRootsInCode && detect_scavenge_root_oops()) {
-      CodeCache::add_scavenge_root_nmethod(this);
+    if (ScavengeRootsInCode) {
+      if (detect_scavenge_root_oops()) {
+        CodeCache::add_scavenge_root_nmethod(this);
+      }
       Universe::heap()->register_nmethod(this);
     }
     debug_only(verify_scavenge_root_oops());
@@ -1612,15 +1622,7 @@ void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred)
   }
 
   // Exception cache
-  ExceptionCache* ec = exception_cache();
-  while (ec != NULL) {
-    Klass* ex_klass = ec->exception_type();
-    ExceptionCache* next_ec = ec->next();
-    if (ex_klass != NULL && !ex_klass->is_loader_alive(is_alive)) {
-      remove_from_exception_cache(ec);
-    }
-    ec = next_ec;
-  }
+  clean_exception_cache(is_alive);
 
   // If class unloading occurred we first iterate over all inline caches and
   // clear ICs where the cached oop is referring to an unloaded klass or method.
diff --git a/hotspot/src/share/vm/code/nmethod.hpp b/hotspot/src/share/vm/code/nmethod.hpp
index fa57e9e504df2c006dd41b028eff4af1c5e84ea6..5ffbde6ad70433af2fbce6ebb5104a5a44a79e94 100644
--- a/hotspot/src/share/vm/code/nmethod.hpp
+++ b/hotspot/src/share/vm/code/nmethod.hpp
@@ -529,7 +529,7 @@ public:
   void set_exception_cache(ExceptionCache *ec)    { _exception_cache = ec; }
   address handler_for_exception_and_pc(Handle exception, address pc);
   void add_handler_for_exception_and_pc(Handle exception, address pc, address handler);
-  void remove_from_exception_cache(ExceptionCache* ec);
+  void clean_exception_cache(BoolObjectClosure* is_alive);
 
   // implicit exceptions support
   address continuation_for_implicit_exception(address pc);
diff --git a/hotspot/src/share/vm/compiler/compileBroker.cpp b/hotspot/src/share/vm/compiler/compileBroker.cpp
index ff292fbd747fdf655ad9b7f626f454c9a4522dad..b97a554192d0b5161c6bbd3db0129f5d571cccf5 100644
--- a/hotspot/src/share/vm/compiler/compileBroker.cpp
+++ b/hotspot/src/share/vm/compiler/compileBroker.cpp
@@ -36,6 +36,7 @@
 #include "oops/oop.inline.hpp"
 #include "prims/nativeLookup.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/compilationPolicy.hpp"
 #include "runtime/init.hpp"
 #include "runtime/interfaceSupport.hpp"
@@ -589,11 +590,10 @@ void CompileTask::log_task_done(CompileLog* log) {
 
 
 /**
- * Add a CompileTask to a CompileQueue
+ * Add a CompileTask to a CompileQueue.
  */
 void CompileQueue::add(CompileTask* task) {
   assert(lock()->owned_by_self(), "must own lock");
-  assert(!CompileBroker::is_compilation_disabled_forever(), "Do not add task if compilation is turned off forever");
 
   task->set_next(NULL);
   task->set_prev(NULL);
@@ -639,8 +639,11 @@ void CompileQueue::free_all() {
   while (next != NULL) {
     CompileTask* current = next;
     next = current->next();
-    // Wake up thread that blocks on the compile task.
-    current->lock()->notify();
+    {
+      // Wake up thread that blocks on the compile task.
+      MutexLocker ct_lock(current->lock());
+      current->lock()->notify();
+    }
     // Put the task back on the freelist.
     CompileTask::free(current);
   }
diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp
index 1c9f4cba5f27117236cbfb856249ffd9734fdac8..5f2b6a6b523451e22810fe7de4d2c2feed11534c 100644
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp
@@ -26,6 +26,7 @@
 #define SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSOOPCLOSURES_HPP
 
 #include "memory/genOopClosures.hpp"
+#include "memory/iterator.hpp"
 
 /////////////////////////////////////////////////////////////////
 // Closures used by ConcurrentMarkSweepGeneration's collector
@@ -48,52 +49,13 @@ class Par_MarkFromRootsClosure;
     }                                                     \
   }
 
-// Applies the given oop closure to all oops in all klasses visited.
-class CMKlassClosure : public KlassClosure {
-  friend class CMSOopClosure;
-  friend class CMSOopsInGenClosure;
-
-  OopClosure* _oop_closure;
-
-  // Used when _oop_closure couldn't be set in an initialization list.
-  void initialize(OopClosure* oop_closure) {
-    assert(_oop_closure == NULL, "Should only be called once");
-    _oop_closure = oop_closure;
-  }
- public:
-  CMKlassClosure(OopClosure* oop_closure = NULL) : _oop_closure(oop_closure) { }
-
-  void do_klass(Klass* k);
-};
-
-// The base class for all CMS marking closures.
-// It's used to proxy through the metadata to the oops defined in them.
-class CMSOopClosure: public ExtendedOopClosure {
-  CMKlassClosure      _klass_closure;
- public:
-  CMSOopClosure() : ExtendedOopClosure() {
-    _klass_closure.initialize(this);
-  }
-  CMSOopClosure(ReferenceProcessor* rp) : ExtendedOopClosure(rp) {
-    _klass_closure.initialize(this);
-  }
-
-  virtual bool do_metadata()    { return do_metadata_nv(); }
-  inline  bool do_metadata_nv() { return true; }
-
-  virtual void do_klass(Klass* k);
-  void do_klass_nv(Klass* k);
-
-  virtual void do_class_loader_data(ClassLoaderData* cld);
-};
-
-// TODO: This duplication of the CMSOopClosure class is only needed because
-//       some CMS OopClosures derive from OopsInGenClosure. It would be good
-//       to get rid of them completely.
-class CMSOopsInGenClosure: public OopsInGenClosure {
-  CMKlassClosure _klass_closure;
+// TODO: This duplication of the MetadataAwareOopClosure class is only needed
+//       because some CMS OopClosures derive from OopsInGenClosure. It would be
+//       good to get rid of them completely.
+class MetadataAwareOopsInGenClosure: public OopsInGenClosure {
+  KlassToOopClosure _klass_closure;
  public:
-  CMSOopsInGenClosure() {
+  MetadataAwareOopsInGenClosure() {
     _klass_closure.initialize(this);
   }
 
@@ -106,7 +68,7 @@ class CMSOopsInGenClosure: public OopsInGenClosure {
   virtual void do_class_loader_data(ClassLoaderData* cld);
 };
 
-class MarkRefsIntoClosure: public CMSOopsInGenClosure {
+class MarkRefsIntoClosure: public MetadataAwareOopsInGenClosure {
  private:
   const MemRegion _span;
   CMSBitMap*      _bitMap;
@@ -118,7 +80,7 @@ class MarkRefsIntoClosure: public CMSOopsInGenClosure {
   virtual void do_oop(narrowOop* p);
 };
 
-class Par_MarkRefsIntoClosure: public CMSOopsInGenClosure {
+class Par_MarkRefsIntoClosure: public MetadataAwareOopsInGenClosure {
  private:
   const MemRegion _span;
   CMSBitMap*      _bitMap;
@@ -132,7 +94,7 @@ class Par_MarkRefsIntoClosure: public CMSOopsInGenClosure {
 
 // A variant of the above used in certain kinds of CMS
 // marking verification.
-class MarkRefsIntoVerifyClosure: public CMSOopsInGenClosure {
+class MarkRefsIntoVerifyClosure: public MetadataAwareOopsInGenClosure {
  private:
   const MemRegion _span;
   CMSBitMap*      _verification_bm;
@@ -147,7 +109,7 @@ class MarkRefsIntoVerifyClosure: public CMSOopsInGenClosure {
 };
 
 // The non-parallel version (the parallel version appears further below).
-class PushAndMarkClosure: public CMSOopClosure {
+class PushAndMarkClosure: public MetadataAwareOopClosure {
  private:
   CMSCollector* _collector;
   MemRegion     _span;
@@ -177,7 +139,7 @@ class PushAndMarkClosure: public CMSOopClosure {
 // synchronization (for instance, via CAS). The marking stack
 // used in the non-parallel case above is here replaced with
 // an OopTaskQueue structure to allow efficient work stealing.
-class Par_PushAndMarkClosure: public CMSOopClosure {
+class Par_PushAndMarkClosure: public MetadataAwareOopClosure {
  private:
   CMSCollector* _collector;
   MemRegion     _span;
@@ -198,7 +160,7 @@ class Par_PushAndMarkClosure: public CMSOopClosure {
 };
 
 // The non-parallel version (the parallel version appears further below).
-class MarkRefsIntoAndScanClosure: public CMSOopsInGenClosure {
+class MarkRefsIntoAndScanClosure: public MetadataAwareOopsInGenClosure {
  private:
   MemRegion          _span;
   CMSBitMap*         _bit_map;
@@ -239,7 +201,7 @@ class MarkRefsIntoAndScanClosure: public CMSOopsInGenClosure {
 // stack and the bitMap are shared, so access needs to be suitably
 // synchronized. An OopTaskQueue structure, supporting efficient
 // work stealing, replaces a CMSMarkStack for storing grey objects.
-class Par_MarkRefsIntoAndScanClosure: public CMSOopsInGenClosure {
+class Par_MarkRefsIntoAndScanClosure: public MetadataAwareOopsInGenClosure {
  private:
   MemRegion              _span;
   CMSBitMap*             _bit_map;
@@ -265,7 +227,7 @@ class Par_MarkRefsIntoAndScanClosure: public CMSOopsInGenClosure {
 // This closure is used during the concurrent marking phase
 // following the first checkpoint. Its use is buried in
 // the closure MarkFromRootsClosure.
-class PushOrMarkClosure: public CMSOopClosure {
+class PushOrMarkClosure: public MetadataAwareOopClosure {
  private:
   CMSCollector*   _collector;
   MemRegion       _span;
@@ -298,7 +260,7 @@ class PushOrMarkClosure: public CMSOopClosure {
 // This closure is used during the concurrent marking phase
 // following the first checkpoint. Its use is buried in
 // the closure Par_MarkFromRootsClosure.
-class Par_PushOrMarkClosure: public CMSOopClosure {
+class Par_PushOrMarkClosure: public MetadataAwareOopClosure {
  private:
   CMSCollector*    _collector;
   MemRegion        _whole_span;
@@ -338,7 +300,7 @@ class Par_PushOrMarkClosure: public CMSOopClosure {
 // processing phase of the CMS final checkpoint step, as
 // well as during the concurrent precleaning of the discovered
 // reference lists.
-class CMSKeepAliveClosure: public CMSOopClosure {
+class CMSKeepAliveClosure: public MetadataAwareOopClosure {
  private:
   CMSCollector* _collector;
   const MemRegion _span;
@@ -358,7 +320,7 @@ class CMSKeepAliveClosure: public CMSOopClosure {
   inline void do_oop_nv(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); }
 };
 
-class CMSInnerParMarkAndPushClosure: public CMSOopClosure {
+class CMSInnerParMarkAndPushClosure: public MetadataAwareOopClosure {
  private:
   CMSCollector* _collector;
   MemRegion     _span;
@@ -379,7 +341,7 @@ class CMSInnerParMarkAndPushClosure: public CMSOopClosure {
 // A parallel (MT) version of the above, used when
 // reference processing is parallel; the only difference
 // is in the do_oop method.
-class CMSParKeepAliveClosure: public CMSOopClosure {
+class CMSParKeepAliveClosure: public MetadataAwareOopClosure {
  private:
   MemRegion     _span;
   OopTaskQueue* _work_queue;
diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp
index 499ba4b3bea193324f9df87d27b30049b4c8019e..2980f0d272f50985050c671fdf0fea00b750dbfc 100644
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp
@@ -44,33 +44,20 @@ inline void Par_MarkRefsIntoAndScanClosure::trim_queue(uint max) {
   }
 }
 
-// CMSOopClosure and CMSoopsInGenClosure are duplicated,
+// MetadataAwareOopClosure and MetadataAwareOopsInGenClosure are duplicated,
 // until we get rid of OopsInGenClosure.
 
-inline void CMSOopClosure::do_klass(Klass* k)       { do_klass_nv(k); }
-inline void CMSOopsInGenClosure::do_klass(Klass* k) { do_klass_nv(k); }
-
-inline void CMSOopClosure::do_klass_nv(Klass* k) {
+inline void MetadataAwareOopsInGenClosure::do_klass_nv(Klass* k) {
   ClassLoaderData* cld = k->class_loader_data();
   do_class_loader_data(cld);
 }
-inline void CMSOopsInGenClosure::do_klass_nv(Klass* k) {
-  ClassLoaderData* cld = k->class_loader_data();
-  do_class_loader_data(cld);
-}
-
-inline void CMSOopClosure::do_class_loader_data(ClassLoaderData* cld) {
-  assert(_klass_closure._oop_closure == this, "Must be");
+inline void MetadataAwareOopsInGenClosure::do_klass(Klass* k) { do_klass_nv(k); }
 
-  bool claim = true;  // Must claim the class loader data before processing.
-  cld->oops_do(_klass_closure._oop_closure, &_klass_closure, claim);
-}
-inline void CMSOopsInGenClosure::do_class_loader_data(ClassLoaderData* cld) {
+inline void MetadataAwareOopsInGenClosure::do_class_loader_data(ClassLoaderData* cld) {
   assert(_klass_closure._oop_closure == this, "Must be");
 
   bool claim = true;  // Must claim the class loader data before processing.
   cld->oops_do(_klass_closure._oop_closure, &_klass_closure, claim);
 }
 
-
 #endif // SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSOOPCLOSURES_INLINE_HPP
diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
index 8cd65e36dca47d321984c34b6f17a24b293df860..c0daf2c32ecfdb2a3d550702b7989f7a03ade104 100644
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
@@ -49,13 +49,14 @@
 #include "memory/genCollectedHeap.hpp"
 #include "memory/genMarkSweep.hpp"
 #include "memory/genOopClosures.inline.hpp"
-#include "memory/iterator.hpp"
+#include "memory/iterator.inline.hpp"
 #include "memory/padded.hpp"
 #include "memory/referencePolicy.hpp"
 #include "memory/resourceArea.hpp"
 #include "memory/tenuredGeneration.hpp"
 #include "oops/oop.inline.hpp"
 #include "prims/jvmtiExport.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/globals_extension.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/java.hpp"
@@ -2024,7 +2025,7 @@ void CMSCollector::do_compaction_work(bool clear_all_soft_refs) {
   SerialOldTracer* gc_tracer = GenMarkSweep::gc_tracer();
   gc_tracer->report_gc_start(gch->gc_cause(), gc_timer->gc_start());
 
-  GCTraceTime t("CMS:MSC ", PrintGCDetails && Verbose, true, NULL);
+  GCTraceTime t("CMS:MSC ", PrintGCDetails && Verbose, true, NULL, gc_tracer->gc_id());
   if (PrintGC && Verbose && !(GCCause::is_user_requested_gc(gch->gc_cause()))) {
     gclog_or_tty->print_cr("Compact ConcurrentMarkSweepGeneration after %d "
       "collections passed to foreground collector", _full_gcs_since_conc_gc);
@@ -2534,8 +2535,10 @@ void CMSCollector::collect_in_foreground(bool clear_all_soft_refs, GCCause::Caus
   assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
          "VM thread should have CMS token");
 
+  // The gc id is created in register_foreground_gc_start if this collection is synchronous
+  const GCId gc_id = _collectorState == InitialMarking ? GCId::peek() : _gc_tracer_cm->gc_id();
   NOT_PRODUCT(GCTraceTime t("CMS:MS (foreground) ", PrintGCDetails && Verbose,
-    true, NULL);)
+    true, NULL, gc_id);)
   if (UseAdaptiveSizePolicy) {
     size_policy()->ms_collection_begin();
   }
@@ -3120,7 +3123,7 @@ void CMSCollector::verify_after_remark_work_2() {
   // Mark from roots one level into CMS
   MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(),
                                      markBitMap());
-  CMKlassClosure klass_closure(&notOlder);
+  KlassToOopClosure klass_closure(&notOlder);
 
   gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
   gch->gen_process_strong_roots(_cmsGen->level(),
@@ -3538,6 +3541,7 @@ class CMSPhaseAccounting: public StackObj {
  public:
   CMSPhaseAccounting(CMSCollector *collector,
                      const char *phase,
+                     const GCId gc_id,
                      bool print_cr = true);
   ~CMSPhaseAccounting();
 
@@ -3546,6 +3550,7 @@ class CMSPhaseAccounting: public StackObj {
   const char *_phase;
   elapsedTimer _wallclock;
   bool _print_cr;
+  const GCId _gc_id;
 
  public:
   // Not MT-safe; so do not pass around these StackObj's
@@ -3561,15 +3566,15 @@ class CMSPhaseAccounting: public StackObj {
 
 CMSPhaseAccounting::CMSPhaseAccounting(CMSCollector *collector,
                                        const char *phase,
+                                       const GCId gc_id,
                                        bool print_cr) :
-  _collector(collector), _phase(phase), _print_cr(print_cr) {
+  _collector(collector), _phase(phase), _print_cr(print_cr), _gc_id(gc_id) {
 
   if (PrintCMSStatistics != 0) {
     _collector->resetYields();
   }
   if (PrintGCDetails) {
-    gclog_or_tty->date_stamp(PrintGCDateStamps);
-    gclog_or_tty->stamp(PrintGCTimeStamps);
+    gclog_or_tty->gclog_stamp(_gc_id);
     gclog_or_tty->print_cr("[%s-concurrent-%s-start]",
       _collector->cmsGen()->short_name(), _phase);
   }
@@ -3583,8 +3588,7 @@ CMSPhaseAccounting::~CMSPhaseAccounting() {
   _collector->stopTimer();
   _wallclock.stop();
   if (PrintGCDetails) {
-    gclog_or_tty->date_stamp(PrintGCDateStamps);
-    gclog_or_tty->stamp(PrintGCTimeStamps);
+    gclog_or_tty->gclog_stamp(_gc_id);
     gclog_or_tty->print("[%s-concurrent-%s: %3.3f/%3.3f secs]",
                  _collector->cmsGen()->short_name(),
                  _phase, _collector->timerValue(), _wallclock.seconds());
@@ -3682,7 +3686,7 @@ void CMSCollector::checkpointRootsInitialWork(bool asynch) {
   setup_cms_unloading_and_verification_state();
 
   NOT_PRODUCT(GCTraceTime t("\ncheckpointRootsInitialWork",
-    PrintGCDetails && Verbose, true, _gc_timer_cm);)
+    PrintGCDetails && Verbose, true, _gc_timer_cm, _gc_tracer_cm->gc_id());)
   if (UseAdaptiveSizePolicy) {
     size_policy()->checkpoint_roots_initial_begin();
   }
@@ -3740,7 +3744,7 @@ void CMSCollector::checkpointRootsInitialWork(bool asynch) {
       gch->set_par_threads(0);
     } else {
       // The serial version.
-      CMKlassClosure klass_closure(&notOlder);
+      KlassToOopClosure klass_closure(&notOlder);
       gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
       gch->gen_process_strong_roots(_cmsGen->level(),
                                     true,   // younger gens are roots
@@ -3799,7 +3803,7 @@ bool CMSCollector::markFromRoots(bool asynch) {
 
     CMSTokenSyncWithLocks ts(true, bitMapLock());
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    CMSPhaseAccounting pa(this, "mark", !PrintGCDetails);
+    CMSPhaseAccounting pa(this, "mark", _gc_tracer_cm->gc_id(), !PrintGCDetails);
     res = markFromRootsWork(asynch);
     if (res) {
       _collectorState = Precleaning;
@@ -4202,7 +4206,7 @@ void CMSConcMarkingTask::do_scan_and_mark(int i, CompactibleFreeListSpace* sp) {
   pst->all_tasks_completed();
 }
 
-class Par_ConcMarkingClosure: public CMSOopClosure {
+class Par_ConcMarkingClosure: public MetadataAwareOopClosure {
  private:
   CMSCollector* _collector;
   CMSConcMarkingTask* _task;
@@ -4215,7 +4219,7 @@ class Par_ConcMarkingClosure: public CMSOopClosure {
  public:
   Par_ConcMarkingClosure(CMSCollector* collector, CMSConcMarkingTask* task, OopTaskQueue* work_queue,
                          CMSBitMap* bit_map, CMSMarkStack* overflow_stack):
-    CMSOopClosure(collector->ref_processor()),
+    MetadataAwareOopClosure(collector->ref_processor()),
     _collector(collector),
     _task(task),
     _span(collector->_span),
@@ -4522,7 +4526,7 @@ void CMSCollector::preclean() {
       _start_sampling = false;
     }
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    CMSPhaseAccounting pa(this, "preclean", !PrintGCDetails);
+    CMSPhaseAccounting pa(this, "preclean", _gc_tracer_cm->gc_id(), !PrintGCDetails);
     preclean_work(CMSPrecleanRefLists1, CMSPrecleanSurvivors1);
   }
   CMSTokenSync x(true); // is cms thread
@@ -4551,7 +4555,7 @@ void CMSCollector::abortable_preclean() {
   // we will never do an actual abortable preclean cycle.
   if (get_eden_used() > CMSScheduleRemarkEdenSizeThreshold) {
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    CMSPhaseAccounting pa(this, "abortable-preclean", !PrintGCDetails);
+    CMSPhaseAccounting pa(this, "abortable-preclean", _gc_tracer_cm->gc_id(), !PrintGCDetails);
     // We need more smarts in the abortable preclean
     // loop below to deal with cases where allocation
     // in young gen is very very slow, and our precleaning
@@ -4696,7 +4700,7 @@ size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) {
     GCTimer *gc_timer = NULL; // Currently not tracing concurrent phases
     rp->preclean_discovered_references(
           rp->is_alive_non_header(), &keep_alive, &complete_trace, &yield_cl,
-          gc_timer);
+          gc_timer, _gc_tracer_cm->gc_id());
   }
 
   if (clean_survivor) {  // preclean the active survivor space(s)
@@ -4986,7 +4990,7 @@ size_t CMSCollector::preclean_card_table(ConcurrentMarkSweepGeneration* gen,
 }
 
 class PrecleanKlassClosure : public KlassClosure {
-  CMKlassClosure _cm_klass_closure;
+  KlassToOopClosure _cm_klass_closure;
  public:
   PrecleanKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
   void do_klass(Klass* k) {
@@ -5039,7 +5043,7 @@ void CMSCollector::checkpointRootsFinal(bool asynch,
       // expect it to be false and set to true
       FlagSetting fl(gch->_is_gc_active, false);
       NOT_PRODUCT(GCTraceTime t("Scavenge-Before-Remark",
-        PrintGCDetails && Verbose, true, _gc_timer_cm);)
+        PrintGCDetails && Verbose, true, _gc_timer_cm, _gc_tracer_cm->gc_id());)
       int level = _cmsGen->level() - 1;
       if (level >= 0) {
         gch->do_collection(true,        // full (i.e. force, see below)
@@ -5068,7 +5072,7 @@ void CMSCollector::checkpointRootsFinal(bool asynch,
 void CMSCollector::checkpointRootsFinalWork(bool asynch,
   bool clear_all_soft_refs, bool init_mark_was_synchronous) {
 
-  NOT_PRODUCT(GCTraceTime tr("checkpointRootsFinalWork", PrintGCDetails, false, _gc_timer_cm);)
+  NOT_PRODUCT(GCTraceTime tr("checkpointRootsFinalWork", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());)
 
   assert(haveFreelistLocks(), "must have free list locks");
   assert_lock_strong(bitMapLock());
@@ -5123,11 +5127,11 @@ void CMSCollector::checkpointRootsFinalWork(bool asynch,
       // the most recent young generation GC, minus those cleaned up by the
       // concurrent precleaning.
       if (CMSParallelRemarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
-        GCTraceTime t("Rescan (parallel) ", PrintGCDetails, false, _gc_timer_cm);
+        GCTraceTime t("Rescan (parallel) ", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
         do_remark_parallel();
       } else {
         GCTraceTime t("Rescan (non-parallel) ", PrintGCDetails, false,
-                    _gc_timer_cm);
+                    _gc_timer_cm, _gc_tracer_cm->gc_id());
         do_remark_non_parallel();
       }
     }
@@ -5140,7 +5144,7 @@ void CMSCollector::checkpointRootsFinalWork(bool asynch,
   verify_overflow_empty();
 
   {
-    NOT_PRODUCT(GCTraceTime ts("refProcessingWork", PrintGCDetails, false, _gc_timer_cm);)
+    NOT_PRODUCT(GCTraceTime ts("refProcessingWork", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());)
     refProcessingWork(asynch, clear_all_soft_refs);
   }
   verify_work_stacks_empty();
@@ -5224,7 +5228,7 @@ void CMSParInitialMarkTask::work(uint worker_id) {
   _timer.start();
   GenCollectedHeap* gch = GenCollectedHeap::heap();
   Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap));
-  CMKlassClosure klass_closure(&par_mri_cl);
+  KlassToOopClosure klass_closure(&par_mri_cl);
 
   // ---------- young gen roots --------------
   {
@@ -5298,7 +5302,7 @@ class CMSParRemarkTask: public CMSParMarkTask {
 };
 
 class RemarkKlassClosure : public KlassClosure {
-  CMKlassClosure _cm_klass_closure;
+  KlassToOopClosure _cm_klass_closure;
  public:
   RemarkKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
   void do_klass(Klass* k) {
@@ -5921,7 +5925,7 @@ void CMSCollector::do_remark_non_parallel() {
                               NULL,  // space is set further below
                               &_markBitMap, &_markStack, &mrias_cl);
   {
-    GCTraceTime t("grey object rescan", PrintGCDetails, false, _gc_timer_cm);
+    GCTraceTime t("grey object rescan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
     // Iterate over the dirty cards, setting the corresponding bits in the
     // mod union table.
     {
@@ -5958,7 +5962,7 @@ void CMSCollector::do_remark_non_parallel() {
     Universe::verify();
   }
   {
-    GCTraceTime t("root rescan", PrintGCDetails, false, _gc_timer_cm);
+    GCTraceTime t("root rescan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
 
     verify_work_stacks_empty();
 
@@ -5978,7 +5982,7 @@ void CMSCollector::do_remark_non_parallel() {
   }
 
   {
-    GCTraceTime t("visit unhandled CLDs", PrintGCDetails, false, _gc_timer_cm);
+    GCTraceTime t("visit unhandled CLDs", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
 
     verify_work_stacks_empty();
 
@@ -5997,7 +6001,7 @@ void CMSCollector::do_remark_non_parallel() {
   }
 
   {
-    GCTraceTime t("dirty klass scan", PrintGCDetails, false, _gc_timer_cm);
+    GCTraceTime t("dirty klass scan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
 
     verify_work_stacks_empty();
 
@@ -6199,7 +6203,7 @@ void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
                                 _span, &_markBitMap, &_markStack,
                                 &cmsKeepAliveClosure, false /* !preclean */);
   {
-    GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm);
+    GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
 
     ReferenceProcessorStats stats;
     if (rp->processing_is_mt()) {
@@ -6224,13 +6228,15 @@ void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
                                         &cmsKeepAliveClosure,
                                         &cmsDrainMarkingStackClosure,
                                         &task_executor,
-                                        _gc_timer_cm);
+                                        _gc_timer_cm,
+                                        _gc_tracer_cm->gc_id());
     } else {
       stats = rp->process_discovered_references(&_is_alive_closure,
                                         &cmsKeepAliveClosure,
                                         &cmsDrainMarkingStackClosure,
                                         NULL,
-                                        _gc_timer_cm);
+                                        _gc_timer_cm,
+                                        _gc_tracer_cm->gc_id());
     }
     _gc_tracer_cm->report_gc_reference_stats(stats);
 
@@ -6241,7 +6247,7 @@ void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
 
   if (should_unload_classes()) {
     {
-      GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm);
+      GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
 
       // Unload classes and purge the SystemDictionary.
       bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure);
@@ -6254,7 +6260,7 @@ void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
     }
 
     {
-      GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm);
+      GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
       // Clean up unreferenced symbols in symbol table.
       SymbolTable::unlink();
     }
@@ -6263,7 +6269,7 @@ void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
   // CMS doesn't use the StringTable as hard roots when class unloading is turned off.
   // Need to check if we really scanned the StringTable.
   if ((roots_scanning_options() & SharedHeap::SO_Strings) == 0) {
-    GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm);
+    GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
     // Delete entries for dead interned strings.
     StringTable::unlink(&_is_alive_closure);
   }
@@ -6330,7 +6336,7 @@ void CMSCollector::sweep(bool asynch) {
   _intra_sweep_timer.start();
   if (asynch) {
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    CMSPhaseAccounting pa(this, "sweep", !PrintGCDetails);
+    CMSPhaseAccounting pa(this, "sweep", _gc_tracer_cm->gc_id(), !PrintGCDetails);
     // First sweep the old gen
     {
       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(),
@@ -6551,7 +6557,7 @@ void CMSCollector::reset(bool asynch) {
     // Clear the mark bitmap (no grey objects to start with)
     // for the next cycle.
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    CMSPhaseAccounting cmspa(this, "reset", !PrintGCDetails);
+    CMSPhaseAccounting cmspa(this, "reset", _gc_tracer_cm->gc_id(), !PrintGCDetails);
 
     HeapWord* curAddr = _markBitMap.startWord();
     while (curAddr < _markBitMap.endWord()) {
@@ -6617,7 +6623,7 @@ void CMSCollector::reset(bool asynch) {
 void CMSCollector::do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause) {
   gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-  GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL);
+  GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer_cm->gc_id());
   TraceCollectorStats tcs(counters());
 
   switch (op) {
@@ -7735,7 +7741,7 @@ PushAndMarkVerifyClosure::PushAndMarkVerifyClosure(
   CMSCollector* collector, MemRegion span,
   CMSBitMap* verification_bm, CMSBitMap* cms_bm,
   CMSMarkStack*  mark_stack):
-  CMSOopClosure(collector->ref_processor()),
+  MetadataAwareOopClosure(collector->ref_processor()),
   _collector(collector),
   _span(span),
   _verification_bm(verification_bm),
@@ -7788,7 +7794,7 @@ PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector,
                      MemRegion span,
                      CMSBitMap* bitMap, CMSMarkStack*  markStack,
                      HeapWord* finger, MarkFromRootsClosure* parent) :
-  CMSOopClosure(collector->ref_processor()),
+  MetadataAwareOopClosure(collector->ref_processor()),
   _collector(collector),
   _span(span),
   _bitMap(bitMap),
@@ -7805,7 +7811,7 @@ Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector,
                      HeapWord* finger,
                      HeapWord** global_finger_addr,
                      Par_MarkFromRootsClosure* parent) :
-  CMSOopClosure(collector->ref_processor()),
+  MetadataAwareOopClosure(collector->ref_processor()),
   _collector(collector),
   _whole_span(collector->_span),
   _span(span),
@@ -7854,11 +7860,6 @@ void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
   _overflow_stack->expand(); // expand the stack if possible
 }
 
-void CMKlassClosure::do_klass(Klass* k) {
-  assert(_oop_closure != NULL, "Not initialized?");
-  k->oops_do(_oop_closure);
-}
-
 void PushOrMarkClosure::do_oop(oop obj) {
   // Ignore mark word because we are running concurrent with mutators.
   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
@@ -7956,7 +7957,7 @@ PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector,
                                        CMSBitMap* mod_union_table,
                                        CMSMarkStack*  mark_stack,
                                        bool           concurrent_precleaning):
-  CMSOopClosure(rp),
+  MetadataAwareOopClosure(rp),
   _collector(collector),
   _span(span),
   _bit_map(bit_map),
@@ -8029,7 +8030,7 @@ Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector,
                                                ReferenceProcessor* rp,
                                                CMSBitMap* bit_map,
                                                OopTaskQueue* work_queue):
-  CMSOopClosure(rp),
+  MetadataAwareOopClosure(rp),
   _collector(collector),
   _span(span),
   _bit_map(bit_map),
diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp
index 09740b6d57cd5dc85854ef2e9643599e11655430..7e3ef58605f208aa36ea6979603db6ea6d9434e6 100644
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp
@@ -1444,7 +1444,7 @@ class Par_MarkFromRootsClosure: public BitMapClosure {
 
 // The following closures are used to do certain kinds of verification of
 // CMS marking.
-class PushAndMarkVerifyClosure: public CMSOopClosure {
+class PushAndMarkVerifyClosure: public MetadataAwareOopClosure {
   CMSCollector*    _collector;
   MemRegion        _span;
   CMSBitMap*       _verification_bm;
diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/vmCMSOperations.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/vmCMSOperations.cpp
index ca1a11246432f5ccd5d23f405858f991c471f41e..1b23ecbb5543b92f8a148941c99a976381754806 100644
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/vmCMSOperations.cpp
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/vmCMSOperations.cpp
@@ -56,7 +56,7 @@ void VM_CMS_Operation::release_and_notify_pending_list_lock() {
 void VM_CMS_Operation::verify_before_gc() {
   if (VerifyBeforeGC &&
       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
-    GCTraceTime tm("Verify Before", false, false, _collector->_gc_timer_cm);
+    GCTraceTime tm("Verify Before", false, false, _collector->_gc_timer_cm, _collector->_gc_tracer_cm->gc_id());
     HandleMark hm;
     FreelistLocker x(_collector);
     MutexLockerEx  y(_collector->bitMapLock(), Mutex::_no_safepoint_check_flag);
@@ -68,7 +68,7 @@ void VM_CMS_Operation::verify_before_gc() {
 void VM_CMS_Operation::verify_after_gc() {
   if (VerifyAfterGC &&
       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
-    GCTraceTime tm("Verify After", false, false, _collector->_gc_timer_cm);
+    GCTraceTime tm("Verify After", false, false, _collector->_gc_timer_cm, _collector->_gc_tracer_cm->gc_id());
     HandleMark hm;
     FreelistLocker x(_collector);
     MutexLockerEx  y(_collector->bitMapLock(), Mutex::_no_safepoint_check_flag);
diff --git a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp
index 07b92d0fbe5280061e7a330633ba85fd9fd763df..b1d255051bee298730fc15b9c7e13b0b5a4bb0b1 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp
@@ -28,6 +28,7 @@
 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
 #include "gc_implementation/g1/g1ErgoVerbose.hpp"
 #include "memory/space.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 
 // Even though we don't use the GC efficiency in our heuristics as
 // much as we used to, we still order according to GC efficiency. This
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
index 9d80a5c721246d6eea0aa88d51b291758c20a684..aba4dbb11f37a513d84c5e43d99b2adfd563ae9a 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
@@ -45,6 +45,7 @@
 #include "oops/oop.inline.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/java.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/prefetch.inline.hpp"
 #include "services/memTracker.hpp"
 
@@ -511,6 +512,7 @@ ConcurrentMark::ConcurrentMark(G1CollectedHeap* g1h, ReservedSpace heap_rs) :
   _has_overflown(false),
   _concurrent(false),
   _has_aborted(false),
+  _aborted_gc_id(GCId::undefined()),
   _restart_for_overflow(false),
   _concurrent_marking_in_progress(false),
 
@@ -1020,8 +1022,7 @@ void ConcurrentMark::enter_first_sync_barrier(uint worker_id) {
       force_overflow()->update();
 
       if (G1Log::fine()) {
-        gclog_or_tty->date_stamp(PrintGCDateStamps);
-        gclog_or_tty->stamp(PrintGCTimeStamps);
+        gclog_or_tty->gclog_stamp(concurrent_gc_id());
         gclog_or_tty->print_cr("[GC concurrent-mark-reset-for-overflow]");
       }
     }
@@ -2469,7 +2470,7 @@ void ConcurrentMark::weakRefsWork(bool clear_all_soft_refs) {
     if (G1Log::finer()) {
       gclog_or_tty->put(' ');
     }
-    GCTraceTime t("GC ref-proc", G1Log::finer(), false, g1h->gc_timer_cm());
+    GCTraceTime t("GC ref-proc", G1Log::finer(), false, g1h->gc_timer_cm(), concurrent_gc_id());
 
     ReferenceProcessor* rp = g1h->ref_processor_cm();
 
@@ -2526,7 +2527,8 @@ void ConcurrentMark::weakRefsWork(bool clear_all_soft_refs) {
                                           &g1_keep_alive,
                                           &g1_drain_mark_stack,
                                           executor,
-                                          g1h->gc_timer_cm());
+                                          g1h->gc_timer_cm(),
+                                          concurrent_gc_id());
     g1h->gc_tracer_cm()->report_gc_reference_stats(stats);
 
     // The do_oop work routines of the keep_alive and drain_marking_stack
@@ -3261,6 +3263,12 @@ void ConcurrentMark::abort() {
   }
   _first_overflow_barrier_sync.abort();
   _second_overflow_barrier_sync.abort();
+  const GCId& gc_id = _g1h->gc_tracer_cm()->gc_id();
+  if (!gc_id.is_undefined()) {
+    // We can do multiple full GCs before ConcurrentMarkThread::run() gets a chance
+    // to detect that it was aborted. Only keep track of the first GC id that we aborted.
+    _aborted_gc_id = gc_id;
+   }
   _has_aborted = true;
 
   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
@@ -3275,6 +3283,13 @@ void ConcurrentMark::abort() {
   _g1h->register_concurrent_cycle_end();
 }
 
+const GCId& ConcurrentMark::concurrent_gc_id() {
+  if (has_aborted()) {
+    return _aborted_gc_id;
+  }
+  return _g1h->gc_tracer_cm()->gc_id();
+}
+
 static void print_ms_time_info(const char* prefix, const char* name,
                                NumberSeq& ns) {
   gclog_or_tty->print_cr("%s%5d %12s: total time = %8.2f s (avg = %8.2f ms).",
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp
index 9d049a2a25534be5eab2fccd363c2fa379566084..1e4ad366c758969365552a8343bab303a3cceea6 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp
@@ -26,6 +26,7 @@
 #define SHARE_VM_GC_IMPLEMENTATION_G1_CONCURRENTMARK_HPP
 
 #include "gc_implementation/g1/heapRegionSet.hpp"
+#include "gc_implementation/shared/gcId.hpp"
 #include "utilities/taskqueue.hpp"
 
 class G1CollectedHeap;
@@ -444,6 +445,7 @@ protected:
   volatile bool           _concurrent;
   // Set at the end of a Full GC so that marking aborts
   volatile bool           _has_aborted;
+  GCId                    _aborted_gc_id;
 
   // Used when remark aborts due to an overflow to indicate that
   // another concurrent marking phase should start
@@ -824,6 +826,8 @@ public:
 
   bool has_aborted()      { return _has_aborted; }
 
+  const GCId& concurrent_gc_id();
+
   // This prints the global/local fingers. It is used for debugging.
   NOT_PRODUCT(void print_finger();)
 
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp
index ad11c016e66f99d4846b3b7970eea904555d4d9f..f8392143db84da6e7c533a45db50dabe8dc693f2 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp
@@ -1,4 +1,4 @@
-/*
+ /*
  * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -29,6 +29,7 @@
 #include "gc_implementation/g1/g1Log.hpp"
 #include "gc_implementation/g1/g1MMUTracker.hpp"
 #include "gc_implementation/g1/vm_operations_g1.hpp"
+#include "gc_implementation/shared/gcTrace.hpp"
 #include "memory/resourceArea.hpp"
 #include "runtime/vmThread.hpp"
 
@@ -111,8 +112,7 @@ void ConcurrentMarkThread::run() {
       double scan_start = os::elapsedTime();
       if (!cm()->has_aborted()) {
         if (G1Log::fine()) {
-          gclog_or_tty->date_stamp(PrintGCDateStamps);
-          gclog_or_tty->stamp(PrintGCTimeStamps);
+          gclog_or_tty->gclog_stamp(cm()->concurrent_gc_id());
           gclog_or_tty->print_cr("[GC concurrent-root-region-scan-start]");
         }
 
@@ -120,8 +120,7 @@ void ConcurrentMarkThread::run() {
 
         double scan_end = os::elapsedTime();
         if (G1Log::fine()) {
-          gclog_or_tty->date_stamp(PrintGCDateStamps);
-          gclog_or_tty->stamp(PrintGCTimeStamps);
+          gclog_or_tty->gclog_stamp(cm()->concurrent_gc_id());
           gclog_or_tty->print_cr("[GC concurrent-root-region-scan-end, %1.7lf secs]",
                                  scan_end - scan_start);
         }
@@ -129,8 +128,7 @@ void ConcurrentMarkThread::run() {
 
       double mark_start_sec = os::elapsedTime();
       if (G1Log::fine()) {
-        gclog_or_tty->date_stamp(PrintGCDateStamps);
-        gclog_or_tty->stamp(PrintGCTimeStamps);
+        gclog_or_tty->gclog_stamp(cm()->concurrent_gc_id());
         gclog_or_tty->print_cr("[GC concurrent-mark-start]");
       }
 
@@ -153,8 +151,7 @@ void ConcurrentMarkThread::run() {
           }
 
           if (G1Log::fine()) {
-            gclog_or_tty->date_stamp(PrintGCDateStamps);
-            gclog_or_tty->stamp(PrintGCTimeStamps);
+            gclog_or_tty->gclog_stamp(cm()->concurrent_gc_id());
             gclog_or_tty->print_cr("[GC concurrent-mark-end, %1.7lf secs]",
                                       mark_end_sec - mark_start_sec);
           }
@@ -169,8 +166,7 @@ void ConcurrentMarkThread::run() {
                                    "in remark (restart #%d).", iter);
           }
           if (G1Log::fine()) {
-            gclog_or_tty->date_stamp(PrintGCDateStamps);
-            gclog_or_tty->stamp(PrintGCTimeStamps);
+            gclog_or_tty->gclog_stamp(cm()->concurrent_gc_id());
             gclog_or_tty->print_cr("[GC concurrent-mark-restart-for-overflow]");
           }
         }
@@ -213,8 +209,7 @@ void ConcurrentMarkThread::run() {
 
         double cleanup_start_sec = os::elapsedTime();
         if (G1Log::fine()) {
-          gclog_or_tty->date_stamp(PrintGCDateStamps);
-          gclog_or_tty->stamp(PrintGCTimeStamps);
+          gclog_or_tty->gclog_stamp(cm()->concurrent_gc_id());
           gclog_or_tty->print_cr("[GC concurrent-cleanup-start]");
         }
 
@@ -234,8 +229,7 @@ void ConcurrentMarkThread::run() {
 
         double cleanup_end_sec = os::elapsedTime();
         if (G1Log::fine()) {
-          gclog_or_tty->date_stamp(PrintGCDateStamps);
-          gclog_or_tty->stamp(PrintGCTimeStamps);
+          gclog_or_tty->gclog_stamp(cm()->concurrent_gc_id());
           gclog_or_tty->print_cr("[GC concurrent-cleanup-end, %1.7lf secs]",
                                  cleanup_end_sec - cleanup_start_sec);
         }
@@ -276,8 +270,7 @@ void ConcurrentMarkThread::run() {
 
       if (cm()->has_aborted()) {
         if (G1Log::fine()) {
-          gclog_or_tty->date_stamp(PrintGCDateStamps);
-          gclog_or_tty->stamp(PrintGCTimeStamps);
+          gclog_or_tty->gclog_stamp(cm()->concurrent_gc_id());
           gclog_or_tty->print_cr("[GC concurrent-mark-abort]");
         }
       }
diff --git a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp
index 6e84e514aa7ec78afef8cd219f0f26d5ca7cbb9b..32b1f763f25f851735f48e1a53f556075e17ec8d 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp
@@ -26,7 +26,7 @@
 #include "gc_implementation/g1/dirtyCardQueue.hpp"
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/heapRegionRemSet.hpp"
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/safepoint.hpp"
 #include "runtime/thread.inline.hpp"
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp
index 14d0126e224818da0810499d275b940a2f9e0990..c07fa50f04d5755546cfea670ca1947e032e60cd 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "gc_implementation/g1/g1BlockOffsetTable.inline.hpp"
+#include "gc_implementation/g1/heapRegion.hpp"
 #include "memory/space.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/java.hpp"
@@ -98,6 +99,20 @@ bool G1BlockOffsetSharedArray::is_card_boundary(HeapWord* p) const {
   return (delta & right_n_bits(LogN_words)) == (size_t)NoBits;
 }
 
+void G1BlockOffsetSharedArray::set_offset_array(HeapWord* left, HeapWord* right, u_char offset) {
+  check_index(index_for(right - 1), "right address out of range");
+  assert(left  < right, "Heap addresses out of order");
+  size_t num_cards = pointer_delta(right, left) >> LogN_words;
+  if (UseMemSetInBOT) {
+    memset(&_offset_array[index_for(left)], offset, num_cards);
+  } else {
+    size_t i = index_for(left);
+    const size_t end = i + num_cards;
+    for (; i < end; i++) {
+      _offset_array[i] = offset;
+    }
+  }
+}
 
 //////////////////////////////////////////////////////////////////////
 // G1BlockOffsetArray
@@ -107,7 +122,7 @@ G1BlockOffsetArray::G1BlockOffsetArray(G1BlockOffsetSharedArray* array,
                                        MemRegion mr, bool init_to_zero) :
   G1BlockOffsetTable(mr.start(), mr.end()),
   _unallocated_block(_bottom),
-  _array(array), _csp(NULL),
+  _array(array), _gsp(NULL),
   _init_to_zero(init_to_zero) {
   assert(_bottom <= _end, "arguments out of order");
   if (!_init_to_zero) {
@@ -117,9 +132,8 @@ G1BlockOffsetArray::G1BlockOffsetArray(G1BlockOffsetSharedArray* array,
   }
 }
 
-void G1BlockOffsetArray::set_space(Space* sp) {
-  _sp = sp;
-  _csp = sp->toContiguousSpace();
+void G1BlockOffsetArray::set_space(G1OffsetTableContigSpace* sp) {
+  _gsp = sp;
 }
 
 // The arguments follow the normal convention of denoting
@@ -378,7 +392,7 @@ G1BlockOffsetArray::block_start_unsafe_const(const void* addr) const {
   }
   // Otherwise, find the block start using the table.
   HeapWord* q = block_at_or_preceding(addr, false, 0);
-  HeapWord* n = q + _sp->block_size(q);
+  HeapWord* n = q + block_size(q);
   return forward_to_block_containing_addr_const(q, n, addr);
 }
 
@@ -406,31 +420,17 @@ G1BlockOffsetArray::forward_to_block_containing_addr_slow(HeapWord* q,
          err_msg("next_boundary is beyond the end of the covered region "
                  " next_boundary " PTR_FORMAT " _array->_end " PTR_FORMAT,
                  next_boundary, _array->_end));
-  if (csp() != NULL) {
-    if (addr >= csp()->top()) return csp()->top();
-    while (next_boundary < addr) {
-      while (n <= next_boundary) {
-        q = n;
-        oop obj = oop(q);
-        if (obj->klass_or_null() == NULL) return q;
-        n += obj->size();
-      }
-      assert(q <= next_boundary && n > next_boundary, "Consequence of loop");
-      // [q, n) is the block that crosses the boundary.
-      alloc_block_work2(&next_boundary, &next_index, q, n);
-    }
-  } else {
-    while (next_boundary < addr) {
-      while (n <= next_boundary) {
-        q = n;
-        oop obj = oop(q);
-        if (obj->klass_or_null() == NULL) return q;
-        n += _sp->block_size(q);
-      }
-      assert(q <= next_boundary && n > next_boundary, "Consequence of loop");
-      // [q, n) is the block that crosses the boundary.
-      alloc_block_work2(&next_boundary, &next_index, q, n);
+  if (addr >= gsp()->top()) return gsp()->top();
+  while (next_boundary < addr) {
+    while (n <= next_boundary) {
+      q = n;
+      oop obj = oop(q);
+      if (obj->klass_or_null() == NULL) return q;
+      n += obj->size();
     }
+    assert(q <= next_boundary && n > next_boundary, "Consequence of loop");
+    // [q, n) is the block that crosses the boundary.
+    alloc_block_work2(&next_boundary, &next_index, q, n);
   }
   return forward_to_block_containing_addr_const(q, n, addr);
 }
@@ -637,7 +637,7 @@ block_start_unsafe_const(const void* addr) const {
   assert(_bottom <= addr && addr < _end,
          "addr must be covered by this Array");
   HeapWord* q = block_at_or_preceding(addr, true, _next_offset_index-1);
-  HeapWord* n = q + _sp->block_size(q);
+  HeapWord* n = q + block_size(q);
   return forward_to_block_containing_addr_const(q, n, addr);
 }
 
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.hpp
index 56dca4d26f8a641dd7a3fb96dbf107c49abe71db..5395899f1439196c0feaca428ba2dc08083ecfd8 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.hpp
@@ -52,8 +52,8 @@
 // consolidation.
 
 // Forward declarations
-class ContiguousSpace;
 class G1BlockOffsetSharedArray;
+class G1OffsetTableContigSpace;
 
 class G1BlockOffsetTable VALUE_OBJ_CLASS_SPEC {
   friend class VMStructs;
@@ -157,6 +157,8 @@ private:
     return _offset_array[index];
   }
 
+  void set_offset_array(HeapWord* left, HeapWord* right, u_char offset);
+
   void set_offset_array(size_t index, u_char offset) {
     check_index(index, "index out of range");
     check_offset(offset, "offset too large");
@@ -170,21 +172,6 @@ private:
     _offset_array[index] = (u_char) pointer_delta(high, low);
   }
 
-  void set_offset_array(HeapWord* left, HeapWord* right, u_char offset) {
-    check_index(index_for(right - 1), "right address out of range");
-    assert(left  < right, "Heap addresses out of order");
-    size_t num_cards = pointer_delta(right, left) >> LogN_words;
-    if (UseMemSetInBOT) {
-      memset(&_offset_array[index_for(left)], offset, num_cards);
-    } else {
-      size_t i = index_for(left);
-      const size_t end = i + num_cards;
-      for (; i < end; i++) {
-        _offset_array[i] = offset;
-      }
-    }
-  }
-
   void set_offset_array(size_t left, size_t right, u_char offset) {
     check_index(right, "right index out of range");
     assert(left <= right, "indexes out of order");
@@ -281,11 +268,7 @@ private:
   G1BlockOffsetSharedArray* _array;
 
   // The space that owns this subregion.
-  Space* _sp;
-
-  // If "_sp" is a contiguous space, the field below is the view of "_sp"
-  // as a contiguous space, else NULL.
-  ContiguousSpace* _csp;
+  G1OffsetTableContigSpace* _gsp;
 
   // If true, array entries are initialized to 0; otherwise, they are
   // initialized to point backwards to the beginning of the covered region.
@@ -310,7 +293,9 @@ private:
 
 protected:
 
-  ContiguousSpace* csp() const { return _csp; }
+  G1OffsetTableContigSpace* gsp() const { return _gsp; }
+
+  inline size_t block_size(const HeapWord* p) const;
 
   // Returns the address of a block whose start is at most "addr".
   // If "has_max_index" is true, "assumes "max_index" is the last valid one
@@ -363,7 +348,7 @@ public:
   // "this" to be passed as a parameter to a member constructor for
   // the containing concrete subtype of Space.
   // This would be legal C++, but MS VC++ doesn't allow it.
-  void set_space(Space* sp);
+  void set_space(G1OffsetTableContigSpace* sp);
 
   // Resets the covered region to the given "mr".
   void set_region(MemRegion mr);
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.inline.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.inline.hpp
index 5ae3bc1cdeb49f449901315eb9559b8cd5321af6..24f97f35dcbdf5bbaf60bb8c085c162d8e112203 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.inline.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.inline.hpp
@@ -26,6 +26,7 @@
 #define SHARE_VM_GC_IMPLEMENTATION_G1_G1BLOCKOFFSETTABLE_INLINE_HPP
 
 #include "gc_implementation/g1/g1BlockOffsetTable.hpp"
+#include "gc_implementation/g1/heapRegion.hpp"
 #include "memory/space.hpp"
 
 inline HeapWord* G1BlockOffsetTable::block_start(const void* addr) {
@@ -69,6 +70,11 @@ G1BlockOffsetSharedArray::address_for_index(size_t index) const {
   return result;
 }
 
+inline size_t
+G1BlockOffsetArray::block_size(const HeapWord* p) const {
+  return gsp()->block_size(p);
+}
+
 inline HeapWord*
 G1BlockOffsetArray::block_at_or_preceding(const void* addr,
                                           bool has_max_index,
@@ -88,7 +94,7 @@ G1BlockOffsetArray::block_at_or_preceding(const void* addr,
     // to go back by.
     size_t n_cards_back = BlockOffsetArray::entry_to_cards_back(offset);
     q -= (N_words * n_cards_back);
-    assert(q >= _sp->bottom(), "Went below bottom!");
+    assert(q >= gsp()->bottom(), "Went below bottom!");
     index -= n_cards_back;
     offset = _array->offset_array(index);
   }
@@ -101,21 +107,12 @@ inline HeapWord*
 G1BlockOffsetArray::
 forward_to_block_containing_addr_const(HeapWord* q, HeapWord* n,
                                        const void* addr) const {
-  if (csp() != NULL) {
-    if (addr >= csp()->top()) return csp()->top();
-    while (n <= addr) {
-      q = n;
-      oop obj = oop(q);
-      if (obj->klass_or_null() == NULL) return q;
-      n += obj->size();
-    }
-  } else {
-    while (n <= addr) {
-      q = n;
-      oop obj = oop(q);
-      if (obj->klass_or_null() == NULL) return q;
-      n += _sp->block_size(q);
-    }
+  if (addr >= gsp()->top()) return gsp()->top();
+  while (n <= addr) {
+    q = n;
+    oop obj = oop(q);
+    if (obj->klass_or_null() == NULL) return q;
+    n += obj->size();
   }
   assert(q <= n, "wrong order for q and addr");
   assert(addr < n, "wrong order for addr and n");
@@ -126,7 +123,7 @@ inline HeapWord*
 G1BlockOffsetArray::forward_to_block_containing_addr(HeapWord* q,
                                                      const void* addr) {
   if (oop(q)->klass_or_null() == NULL) return q;
-  HeapWord* n = q + _sp->block_size(q);
+  HeapWord* n = q + block_size(q);
   // In the normal case, where the query "addr" is a card boundary, and the
   // offset table chunks are the same size as cards, the block starting at
   // "q" will contain addr, so the test below will fail, and we'll fall
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
index 2f259ea1beb05ea7c6f0a3f92800a29e8227cdf7..f020f0d53a14efaec0da13fafaea6436dec392ef 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
@@ -62,6 +62,7 @@
 #include "memory/referenceProcessor.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/prefetch.inline.hpp"
 #include "runtime/orderAccess.inline.hpp"
 #include "runtime/vmThread.hpp"
@@ -1298,7 +1299,7 @@ bool G1CollectedHeap::do_collection(bool explicit_gc,
     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
 
     {
-      GCTraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, NULL);
+      GCTraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, NULL, gc_tracer->gc_id());
       TraceCollectorStats tcs(g1mm()->full_collection_counters());
       TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
 
@@ -3858,8 +3859,7 @@ void G1CollectedHeap::log_gc_header() {
     return;
   }
 
-  gclog_or_tty->date_stamp(PrintGCDateStamps);
-  gclog_or_tty->stamp(PrintGCTimeStamps);
+  gclog_or_tty->gclog_stamp(_gc_tracer_stw->gc_id());
 
   GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())
     .append(g1_policy()->gcs_are_young() ? "(young)" : "(mixed)")
@@ -5340,17 +5340,14 @@ public:
 class G1CopyingKeepAliveClosure: public OopClosure {
   G1CollectedHeap*         _g1h;
   OopClosure*              _copy_non_heap_obj_cl;
-  OopsInHeapRegionClosure* _copy_metadata_obj_cl;
   G1ParScanThreadState*    _par_scan_state;
 
 public:
   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
                             OopClosure* non_heap_obj_cl,
-                            OopsInHeapRegionClosure* metadata_obj_cl,
                             G1ParScanThreadState* pss):
     _g1h(g1h),
     _copy_non_heap_obj_cl(non_heap_obj_cl),
-    _copy_metadata_obj_cl(metadata_obj_cl),
     _par_scan_state(pss)
   {}
 
@@ -5383,7 +5380,7 @@ public:
         _par_scan_state->push_on_queue(p);
       } else {
         assert(!Metaspace::contains((const void*)p),
-               err_msg("Otherwise need to call _copy_metadata_obj_cl->do_oop(p) "
+               err_msg("Unexpectedly found a pointer from metadata: "
                               PTR_FORMAT, p));
           _copy_non_heap_obj_cl->do_oop(p);
         }
@@ -5478,22 +5475,18 @@ public:
     pss.set_evac_failure_closure(&evac_failure_cl);
 
     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
-    G1ParScanMetadataClosure       only_copy_metadata_cl(_g1h, &pss, NULL);
 
     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
-    G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(_g1h, &pss, NULL);
 
     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
-    OopsInHeapRegionClosure*       copy_metadata_cl = &only_copy_metadata_cl;
 
     if (_g1h->g1_policy()->during_initial_mark_pause()) {
       // We also need to mark copied objects.
       copy_non_heap_cl = &copy_mark_non_heap_cl;
-      copy_metadata_cl = &copy_mark_metadata_cl;
     }
 
     // Keep alive closure.
-    G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, copy_metadata_cl, &pss);
+    G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);
 
     // Complete GC closure
     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator);
@@ -5588,18 +5581,14 @@ public:
 
 
     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
-    G1ParScanMetadataClosure       only_copy_metadata_cl(_g1h, &pss, NULL);
 
     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
-    G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(_g1h, &pss, NULL);
 
     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
-    OopsInHeapRegionClosure*       copy_metadata_cl = &only_copy_metadata_cl;
 
     if (_g1h->g1_policy()->during_initial_mark_pause()) {
       // We also need to mark copied objects.
       copy_non_heap_cl = &copy_mark_non_heap_cl;
-      copy_metadata_cl = &copy_mark_metadata_cl;
     }
 
     // Is alive closure
@@ -5607,7 +5596,7 @@ public:
 
     // Copying keep alive closure. Applied to referent objects that need
     // to be copied.
-    G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, copy_metadata_cl, &pss);
+    G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);
 
     ReferenceProcessor* rp = _g1h->ref_processor_cm();
 
@@ -5713,22 +5702,18 @@ void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
   assert(pss.refs()->is_empty(), "pre-condition");
 
   G1ParScanExtRootClosure        only_copy_non_heap_cl(this, &pss, NULL);
-  G1ParScanMetadataClosure       only_copy_metadata_cl(this, &pss, NULL);
 
   G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL);
-  G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(this, &pss, NULL);
 
   OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
-  OopsInHeapRegionClosure*       copy_metadata_cl = &only_copy_metadata_cl;
 
   if (_g1h->g1_policy()->during_initial_mark_pause()) {
     // We also need to mark copied objects.
     copy_non_heap_cl = &copy_mark_non_heap_cl;
-    copy_metadata_cl = &copy_mark_metadata_cl;
   }
 
   // Keep alive closure.
-  G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, copy_metadata_cl, &pss);
+  G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, &pss);
 
   // Serial Complete GC closure
   G1STWDrainQueueClosure drain_queue(this, &pss);
@@ -5743,7 +5728,8 @@ void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
                                               &keep_alive,
                                               &drain_queue,
                                               NULL,
-                                              _gc_timer_stw);
+                                              _gc_timer_stw,
+                                              _gc_tracer_stw->gc_id());
   } else {
     // Parallel reference processing
     assert(rp->num_q() == no_of_gc_workers, "sanity");
@@ -5754,7 +5740,8 @@ void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
                                               &keep_alive,
                                               &drain_queue,
                                               &par_task_executor,
-                                              _gc_timer_stw);
+                                              _gc_timer_stw,
+                                              _gc_tracer_stw->gc_id());
   }
 
   _gc_tracer_stw->report_gc_reference_stats(stats);
@@ -6993,7 +6980,7 @@ public:
       return;
     }
 
-    if (ScavengeRootsInCode && nm->detect_scavenge_root_oops()) {
+    if (ScavengeRootsInCode) {
       _g1h->register_nmethod(nm);
     }
   }
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
index 8e361b63638396d5bf339f17357c565c7b48eb39..3dc72522c07e3dd3dbc7022196080d5972c933f7 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
@@ -28,6 +28,7 @@
 #include "gc_implementation/g1/g1GCPhaseTimes.hpp"
 #include "gc_implementation/g1/g1Log.hpp"
 #include "gc_implementation/g1/g1StringDedup.hpp"
+#include "runtime/atomic.inline.hpp"
 
 // Helper class for avoiding interleaved logging
 class LineBuffer: public StackObj {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1HotCardCache.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1HotCardCache.cpp
index 9020961df8827f2ffcfb45b21c7cef54f9cfc2f2..a75ba66e06f2a4fcb647d5f4f04d9262829c1c62 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1HotCardCache.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1HotCardCache.cpp
@@ -28,7 +28,7 @@
 #include "gc_implementation/g1/g1HotCardCache.hpp"
 #include "gc_implementation/g1/g1RemSet.hpp"
 #include "gc_implementation/g1/heapRegion.hpp"
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 
 G1HotCardCache::G1HotCardCache(G1CollectedHeap *g1h):
   _g1h(g1h), _hot_cache(NULL), _use_cache(false), _card_counts(g1h) {}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp
index d8bda059bb8202001a16f93e645852d3873c1c5d..ae3b83072da158c3392ef090e8c36af05b55428d 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp
@@ -44,6 +44,7 @@
 #include "oops/instanceRefKlass.hpp"
 #include "oops/oop.inline.hpp"
 #include "prims/jvmtiExport.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/fprofiler.hpp"
 #include "runtime/synchronizer.hpp"
@@ -123,7 +124,7 @@ void G1MarkSweep::allocate_stacks() {
 void G1MarkSweep::mark_sweep_phase1(bool& marked_for_unloading,
                                     bool clear_all_softrefs) {
   // Recursively traverse all live objects and mark them
-  GCTraceTime tm("phase 1", G1Log::fine() && Verbose, true, gc_timer());
+  GCTraceTime tm("phase 1", G1Log::fine() && Verbose, true, gc_timer(), gc_tracer()->gc_id());
   GenMarkSweep::trace(" 1");
 
   SharedHeap* sh = SharedHeap::heap();
@@ -146,7 +147,8 @@ void G1MarkSweep::mark_sweep_phase1(bool& marked_for_unloading,
                                       &GenMarkSweep::keep_alive,
                                       &GenMarkSweep::follow_stack_closure,
                                       NULL,
-                                      gc_timer());
+                                      gc_timer(),
+                                      gc_tracer()->gc_id());
   gc_tracer()->report_gc_reference_stats(stats);
 
 
@@ -260,7 +262,7 @@ void G1MarkSweep::mark_sweep_phase2() {
 
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 
-  GCTraceTime tm("phase 2", G1Log::fine() && Verbose, true, gc_timer());
+  GCTraceTime tm("phase 2", G1Log::fine() && Verbose, true, gc_timer(), gc_tracer()->gc_id());
   GenMarkSweep::trace("2");
 
   // find the first region
@@ -297,7 +299,7 @@ void G1MarkSweep::mark_sweep_phase3() {
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 
   // Adjust the pointers to reflect the new locations
-  GCTraceTime tm("phase 3", G1Log::fine() && Verbose, true, gc_timer());
+  GCTraceTime tm("phase 3", G1Log::fine() && Verbose, true, gc_timer(), gc_tracer()->gc_id());
   GenMarkSweep::trace("3");
 
   SharedHeap* sh = SharedHeap::heap();
@@ -358,7 +360,7 @@ void G1MarkSweep::mark_sweep_phase4() {
   // to use a higher index (saved from phase2) when verifying perm_gen.
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 
-  GCTraceTime tm("phase 4", G1Log::fine() && Verbose, true, gc_timer());
+  GCTraceTime tm("phase 4", G1Log::fine() && Verbose, true, gc_timer(), gc_tracer()->gc_id());
   GenMarkSweep::trace("4");
 
   G1SpaceCompactClosure blk;
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp
index e741a0f79519f610e30fbd860c61b07c986324b2..53d88d9cb642e3cb1fd1e57766d3618979c306e3 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp
@@ -26,6 +26,7 @@
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc_implementation/g1/heapRegion.hpp"
 #include "gc_implementation/g1/satbQueue.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/orderAccess.inline.hpp"
 #include "runtime/thread.inline.hpp"
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.cpp
index d353d7ebd2d06ff76307923963d93bb691c6aeeb..4bf636594e26bd3140456c313105a1fd2973ea0a 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.cpp
@@ -31,6 +31,7 @@
 #include "gc_implementation/g1/g1StringDedupStat.hpp"
 #include "gc_implementation/g1/g1StringDedupTable.hpp"
 #include "gc_implementation/g1/g1StringDedupThread.hpp"
+#include "runtime/atomic.inline.hpp"
 
 bool G1StringDedup::_enabled = false;
 
@@ -211,3 +212,16 @@ G1StringDedupUnlinkOrOopsDoClosure::~G1StringDedupUnlinkOrOopsDoClosure() {
     G1StringDedupTable::finish_rehash(_rehashed_table);
   }
 }
+
+// Atomically claims the next available queue for exclusive access by
+// the current thread. Returns the queue number of the claimed queue.
+size_t G1StringDedupUnlinkOrOopsDoClosure::claim_queue() {
+  return (size_t)Atomic::add_ptr(1, &_next_queue) - 1;
+}
+
+// Atomically claims the next available table partition for exclusive
+// access by the current thread. Returns the table bucket number where
+// the claimed partition starts.
+size_t G1StringDedupUnlinkOrOopsDoClosure::claim_table_partition(size_t partition_size) {
+  return (size_t)Atomic::add_ptr(partition_size, &_next_bucket) - partition_size;
+}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.hpp
index 68f700f6585ed4c6ccdb43949635a8adf70dfd08..80ee1fd02addee8d779dbaf42cc280424590cd3a 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.hpp
@@ -84,6 +84,7 @@
 
 #include "memory/allocation.hpp"
 #include "oops/oop.hpp"
+#include "runtime/atomic.hpp"
 
 class OopClosure;
 class BoolObjectClosure;
@@ -174,16 +175,12 @@ public:
 
   // Atomically claims the next available queue for exclusive access by
   // the current thread. Returns the queue number of the claimed queue.
-  size_t claim_queue() {
-    return (size_t)Atomic::add_ptr(1, &_next_queue) - 1;
-  }
+  size_t claim_queue();
 
   // Atomically claims the next available table partition for exclusive
   // access by the current thread. Returns the table bucket number where
   // the claimed partition starts.
-  size_t claim_table_partition(size_t partition_size) {
-    return (size_t)Atomic::add_ptr(partition_size, &_next_bucket) - partition_size;
-  }
+  size_t claim_table_partition(size_t partition_size);
 
   // Applies and returns the result from the is_alive closure, or
   // returns true if no such closure was provided.
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
index 8ae53e353bc051d65093a55495cbe07631627bad..723abbae0950e1a077bbd08577839a12b8b2e4e4 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
@@ -26,6 +26,7 @@
 #include "classfile/javaClasses.hpp"
 #include "gc_implementation/g1/g1StringDedupQueue.hpp"
 #include "memory/gcLocker.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "utilities/stack.inline.hpp"
 
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
index 2187fbe89b3ae8067e0ab161807afbd36cb20b8b..3069770313e445a1194f7f924d0c59240becb2ed 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
@@ -28,6 +28,7 @@
 #include "gc_implementation/g1/g1StringDedupTable.hpp"
 #include "gc_implementation/g1/g1StringDedupThread.hpp"
 #include "gc_implementation/g1/g1StringDedupQueue.hpp"
+#include "runtime/atomic.inline.hpp"
 
 G1StringDedupThread* G1StringDedupThread::_thread = NULL;
 
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp
index c12e3fe840cc1c8b69ea00aee387a2774b039977..037d76ca8aa16804cde5fa325f840ec7a6624686 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp
@@ -34,6 +34,7 @@
 #include "memory/iterator.hpp"
 #include "memory/space.inline.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.inline.hpp"
 
 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
@@ -48,7 +49,7 @@ HeapRegionDCTOC::HeapRegionDCTOC(G1CollectedHeap* g1,
                                  HeapRegion* hr, ExtendedOopClosure* cl,
                                  CardTableModRefBS::PrecisionStyle precision,
                                  FilterKind fk) :
-  ContiguousSpaceDCTOC(hr, cl, precision, NULL),
+  DirtyCardToOopClosure(hr, cl, precision, NULL),
   _hr(hr), _fk(fk), _g1(g1) { }
 
 FilterOutOfRegionClosure::FilterOutOfRegionClosure(HeapRegion* r,
@@ -77,19 +78,18 @@ HeapWord* walk_mem_region_loop(ClosureType* cl, G1CollectedHeap* g1h,
   return cur;
 }
 
-void HeapRegionDCTOC::walk_mem_region_with_cl(MemRegion mr,
-                                              HeapWord* bottom,
-                                              HeapWord* top,
-                                              ExtendedOopClosure* cl) {
+void HeapRegionDCTOC::walk_mem_region(MemRegion mr,
+                                      HeapWord* bottom,
+                                      HeapWord* top) {
   G1CollectedHeap* g1h = _g1;
   int oop_size;
   ExtendedOopClosure* cl2 = NULL;
 
-  FilterIntoCSClosure intoCSFilt(this, g1h, cl);
-  FilterOutOfRegionClosure outOfRegionFilt(_hr, cl);
+  FilterIntoCSClosure intoCSFilt(this, g1h, _cl);
+  FilterOutOfRegionClosure outOfRegionFilt(_hr, _cl);
 
   switch (_fk) {
-  case NoFilterKind:          cl2 = cl; break;
+  case NoFilterKind:          cl2 = _cl; break;
   case IntoCSFilterKind:      cl2 = &intoCSFilt; break;
   case OutOfRegionFilterKind: cl2 = &outOfRegionFilt; break;
   default:                    ShouldNotReachHere();
@@ -111,17 +111,17 @@ void HeapRegionDCTOC::walk_mem_region_with_cl(MemRegion mr,
     // We replicate the loop below for several kinds of possible filters.
     switch (_fk) {
     case NoFilterKind:
-      bottom = walk_mem_region_loop(cl, g1h, _hr, bottom, top);
+      bottom = walk_mem_region_loop(_cl, g1h, _hr, bottom, top);
       break;
 
     case IntoCSFilterKind: {
-      FilterIntoCSClosure filt(this, g1h, cl);
+      FilterIntoCSClosure filt(this, g1h, _cl);
       bottom = walk_mem_region_loop(&filt, g1h, _hr, bottom, top);
       break;
     }
 
     case OutOfRegionFilterKind: {
-      FilterOutOfRegionClosure filt(_hr, cl);
+      FilterOutOfRegionClosure filt(_hr, _cl);
       bottom = walk_mem_region_loop(&filt, g1h, _hr, bottom, top);
       break;
     }
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp
index 25ffe1c8264a4cb2e18cf62110061eba48e3096c..0b9fce740fba829c62948eb2118fda3df9d4b8cc 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp
@@ -25,7 +25,7 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGION_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGION_HPP
 
-#include "gc_implementation/g1/g1BlockOffsetTable.inline.hpp"
+#include "gc_implementation/g1/g1BlockOffsetTable.hpp"
 #include "gc_implementation/g1/g1_specialized_oop_closures.hpp"
 #include "gc_implementation/g1/survRateGroup.hpp"
 #include "gc_implementation/shared/ageTable.hpp"
@@ -71,7 +71,7 @@ class nmethod;
 // in the concurrent marker used by G1 to filter remembered
 // sets.
 
-class HeapRegionDCTOC : public ContiguousSpaceDCTOC {
+class HeapRegionDCTOC : public DirtyCardToOopClosure {
 public:
   // Specification of possible DirtyCardToOopClosure filtering.
   enum FilterKind {
@@ -85,39 +85,13 @@ protected:
   FilterKind _fk;
   G1CollectedHeap* _g1;
 
-  void walk_mem_region_with_cl(MemRegion mr,
-                               HeapWord* bottom, HeapWord* top,
-                               ExtendedOopClosure* cl);
-
-  // We don't specialize this for FilteringClosure; filtering is handled by
-  // the "FilterKind" mechanism.  But we provide this to avoid a compiler
-  // warning.
-  void walk_mem_region_with_cl(MemRegion mr,
-                               HeapWord* bottom, HeapWord* top,
-                               FilteringClosure* cl) {
-    HeapRegionDCTOC::walk_mem_region_with_cl(mr, bottom, top,
-                                             (ExtendedOopClosure*)cl);
-  }
-
-  // Get the actual top of the area on which the closure will
-  // operate, given where the top is assumed to be (the end of the
-  // memory region passed to do_MemRegion) and where the object
-  // at the top is assumed to start. For example, an object may
-  // start at the top but actually extend past the assumed top,
-  // in which case the top becomes the end of the object.
-  HeapWord* get_actual_top(HeapWord* top, HeapWord* top_obj) {
-    return ContiguousSpaceDCTOC::get_actual_top(top, top_obj);
-  }
-
   // Walk the given memory region from bottom to (actual) top
   // looking for objects and applying the oop closure (_cl) to
   // them. The base implementation of this treats the area as
   // blocks, where a block may or may not be an object. Sub-
   // classes should override this to provide more accurate
   // or possibly more efficient walking.
-  void walk_mem_region(MemRegion mr, HeapWord* bottom, HeapWord* top) {
-    Filtering_DCTOC::walk_mem_region(mr, bottom, top);
-  }
+  void walk_mem_region(MemRegion mr, HeapWord* bottom, HeapWord* top);
 
 public:
   HeapRegionDCTOC(G1CollectedHeap* g1,
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp
index d88bc07ad0780fb14c5bc148e9ede59e55324b24..b85c448d161e62e7d21c8e72af10998512ccc516 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp
@@ -25,6 +25,8 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGION_INLINE_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGION_INLINE_HPP
 
+#include "gc_implementation/g1/g1BlockOffsetTable.inline.hpp"
+
 inline HeapWord* G1OffsetTableContigSpace::allocate(size_t size) {
   HeapWord* res = ContiguousSpace::allocate(size);
   if (res != NULL) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
index 382a3fb32ec1628cda8bb7517d5d348038732b4d..08f016d83d9c013f95fbb16276bbe570eae0e142 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
@@ -32,6 +32,7 @@
 #include "memory/padded.inline.hpp"
 #include "memory/space.inline.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "utilities/bitMap.inline.hpp"
 #include "utilities/globalDefinitions.hpp"
 #include "utilities/growableArray.hpp"
diff --git a/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp b/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp
index fe33cef7d28e1ae54f35c45e012c816cfd339b67..bdb5899c9286dc194e5d981864fa4cfe7ae878d0 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp
@@ -29,6 +29,7 @@
 #include "memory/allocation.inline.hpp"
 #include "memory/cardTableModRefBS.hpp"
 #include "memory/space.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 
 #define SPARSE_PRT_VERBOSE 0
diff --git a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp
index 9f298da3873015d5a6da24d19af8f39dbc76e9a4..1c3c17b5ccfcb3a6dc21c239bb1af5661166890b 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp
@@ -226,7 +226,7 @@ void VM_CGC_Operation::release_and_notify_pending_list_lock() {
 void VM_CGC_Operation::doit() {
   gclog_or_tty->date_stamp(G1Log::fine() && PrintGCDateStamps);
   TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
-  GCTraceTime t(_printGCMessage, G1Log::fine(), true, G1CollectedHeap::heap()->gc_timer_cm());
+  GCTraceTime t(_printGCMessage, G1Log::fine(), true, G1CollectedHeap::heap()->gc_timer_cm(), G1CollectedHeap::heap()->concurrent_mark()->concurrent_gc_id());
   SharedHeap* sh = SharedHeap::heap();
   // This could go away if CollectedHeap gave access to _gc_is_active...
   if (sh != NULL) {
diff --git a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp
index 5e979965731744d2424044ec097748699b41a758..c97f97516f125109325e5c75a77e0175c0afd63a 100644
--- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp
@@ -47,6 +47,7 @@
 #include "oops/objArrayOop.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/handles.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/java.hpp"
@@ -955,7 +956,7 @@ void ParNewGeneration::collect(bool   full,
     size_policy->minor_collection_begin();
   }
 
-  GCTraceTime t1(GCCauseString("GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL);
+  GCTraceTime t1(GCCauseString("GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL, gc_tracer.gc_id());
   // Capture heap used before collection (for printing).
   size_t gch_prev_used = gch->used();
 
@@ -1013,14 +1014,14 @@ void ParNewGeneration::collect(bool   full,
     ParNewRefProcTaskExecutor task_executor(*this, thread_state_set);
     stats = rp->process_discovered_references(&is_alive, &keep_alive,
                                               &evacuate_followers, &task_executor,
-                                              _gc_timer);
+                                              _gc_timer, gc_tracer.gc_id());
   } else {
     thread_state_set.flush();
     gch->set_par_threads(0);  // 0 ==> non-parallel.
     gch->save_marks();
     stats = rp->process_discovered_references(&is_alive, &keep_alive,
                                               &evacuate_followers, NULL,
-                                              _gc_timer);
+                                              _gc_timer, gc_tracer.gc_id());
   }
   gc_tracer.report_gc_reference_stats(stats);
   if (!promotion_failed()) {
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp
index 19a055cc040ce12f950931c93c97aa2d4008e93a..320e649e7c9abdba680facb90b4d7b0eca646f3f 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp
@@ -26,6 +26,7 @@
 #include "gc_implementation/parallelScavenge/parMarkBitMap.hpp"
 #include "gc_implementation/parallelScavenge/psParallelCompact.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 #include "utilities/bitMap.inline.hpp"
 #include "services/memTracker.hpp"
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
index 5037c207c625041b8d4195638329008e12f0945c..01790ef931000428ae05dc3d68ecf093381113f1 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
@@ -53,7 +53,7 @@ void ThreadRootsMarkingTask::do_it(GCTaskManager* manager, uint which) {
   ResourceMark rm;
 
   NOT_PRODUCT(GCTraceTime tm("ThreadRootsMarkingTask",
-    PrintGCDetails && TraceParallelOldGCTasks, true, NULL));
+    PrintGCDetails && TraceParallelOldGCTasks, true, NULL, PSParallelCompact::gc_tracer()->gc_id()));
   ParCompactionManager* cm =
     ParCompactionManager::gc_thread_compaction_manager(which);
 
@@ -82,7 +82,7 @@ void MarkFromRootsTask::do_it(GCTaskManager* manager, uint which) {
   assert(Universe::heap()->is_gc_active(), "called outside gc");
 
   NOT_PRODUCT(GCTraceTime tm("MarkFromRootsTask",
-    PrintGCDetails && TraceParallelOldGCTasks, true, NULL));
+    PrintGCDetails && TraceParallelOldGCTasks, true, NULL, PSParallelCompact::gc_tracer()->gc_id()));
   ParCompactionManager* cm =
     ParCompactionManager::gc_thread_compaction_manager(which);
   PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);
@@ -153,7 +153,7 @@ void RefProcTaskProxy::do_it(GCTaskManager* manager, uint which)
   assert(Universe::heap()->is_gc_active(), "called outside gc");
 
   NOT_PRODUCT(GCTraceTime tm("RefProcTask",
-    PrintGCDetails && TraceParallelOldGCTasks, true, NULL));
+    PrintGCDetails && TraceParallelOldGCTasks, true, NULL, PSParallelCompact::gc_tracer()->gc_id()));
   ParCompactionManager* cm =
     ParCompactionManager::gc_thread_compaction_manager(which);
   PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);
@@ -209,7 +209,7 @@ void StealMarkingTask::do_it(GCTaskManager* manager, uint which) {
   assert(Universe::heap()->is_gc_active(), "called outside gc");
 
   NOT_PRODUCT(GCTraceTime tm("StealMarkingTask",
-    PrintGCDetails && TraceParallelOldGCTasks, true, NULL));
+    PrintGCDetails && TraceParallelOldGCTasks, true, NULL, PSParallelCompact::gc_tracer()->gc_id()));
 
   ParCompactionManager* cm =
     ParCompactionManager::gc_thread_compaction_manager(which);
@@ -242,7 +242,7 @@ void StealRegionCompactionTask::do_it(GCTaskManager* manager, uint which) {
   assert(Universe::heap()->is_gc_active(), "called outside gc");
 
   NOT_PRODUCT(GCTraceTime tm("StealRegionCompactionTask",
-    PrintGCDetails && TraceParallelOldGCTasks, true, NULL));
+    PrintGCDetails && TraceParallelOldGCTasks, true, NULL, PSParallelCompact::gc_tracer()->gc_id()));
 
   ParCompactionManager* cm =
     ParCompactionManager::gc_thread_compaction_manager(which);
@@ -309,7 +309,7 @@ UpdateDensePrefixTask::UpdateDensePrefixTask(
 void UpdateDensePrefixTask::do_it(GCTaskManager* manager, uint which) {
 
   NOT_PRODUCT(GCTraceTime tm("UpdateDensePrefixTask",
-    PrintGCDetails && TraceParallelOldGCTasks, true, NULL));
+    PrintGCDetails && TraceParallelOldGCTasks, true, NULL, PSParallelCompact::gc_tracer()->gc_id()));
 
   ParCompactionManager* cm =
     ParCompactionManager::gc_thread_compaction_manager(which);
@@ -324,7 +324,7 @@ void DrainStacksCompactionTask::do_it(GCTaskManager* manager, uint which) {
   assert(Universe::heap()->is_gc_active(), "called outside gc");
 
   NOT_PRODUCT(GCTraceTime tm("DrainStacksCompactionTask",
-    PrintGCDetails && TraceParallelOldGCTasks, true, NULL));
+    PrintGCDetails && TraceParallelOldGCTasks, true, NULL, PSParallelCompact::gc_tracer()->gc_id()));
 
   ParCompactionManager* cm =
     ParCompactionManager::gc_thread_compaction_manager(which);
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psCompactionManager.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psCompactionManager.cpp
index 415d62947952aaac6b2ca979c530251645df2f4b..f838787bfdccf9791daed788018fd1a11eacbb43 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psCompactionManager.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psCompactionManager.cpp
@@ -34,6 +34,7 @@
 #include "oops/objArrayKlass.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "utilities/stack.inline.hpp"
 
 PSOldGen*            ParCompactionManager::_old_gen = NULL;
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp
index bb829f996026ffd3e8499976e9c1e2a51bad469c..51867d1622fbb1e8814da69e1e5e3c40f9cdba3d 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp
@@ -170,7 +170,7 @@ bool PSMarkSweep::invoke_no_policy(bool clear_all_softrefs) {
 
     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    GCTraceTime t1(GCCauseString("Full GC", gc_cause), PrintGC, !PrintGCDetails, NULL);
+    GCTraceTime t1(GCCauseString("Full GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer->gc_id());
     TraceCollectorStats tcs(counters());
     TraceMemoryManagerStats tms(true /* Full GC */,gc_cause);
 
@@ -521,7 +521,7 @@ void PSMarkSweep::deallocate_stacks() {
 
 void PSMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
   // Recursively traverse all live objects and mark them
-  GCTraceTime tm("phase 1", PrintGCDetails && Verbose, true, _gc_timer);
+  GCTraceTime tm("phase 1", PrintGCDetails && Verbose, true, _gc_timer, _gc_tracer->gc_id());
   trace(" 1");
 
   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
@@ -556,7 +556,7 @@ void PSMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
     ref_processor()->setup_policy(clear_all_softrefs);
     const ReferenceProcessorStats& stats =
       ref_processor()->process_discovered_references(
-        is_alive_closure(), mark_and_push_closure(), follow_stack_closure(), NULL, _gc_timer);
+        is_alive_closure(), mark_and_push_closure(), follow_stack_closure(), NULL, _gc_timer, _gc_tracer->gc_id());
     gc_tracer()->report_gc_reference_stats(stats);
   }
 
@@ -582,7 +582,7 @@ void PSMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
 
 
 void PSMarkSweep::mark_sweep_phase2() {
-  GCTraceTime tm("phase 2", PrintGCDetails && Verbose, true, _gc_timer);
+  GCTraceTime tm("phase 2", PrintGCDetails && Verbose, true, _gc_timer, _gc_tracer->gc_id());
   trace("2");
 
   // Now all live objects are marked, compute the new object addresses.
@@ -612,7 +612,7 @@ static PSAlwaysTrueClosure always_true;
 
 void PSMarkSweep::mark_sweep_phase3() {
   // Adjust the pointers to reflect the new locations
-  GCTraceTime tm("phase 3", PrintGCDetails && Verbose, true, _gc_timer);
+  GCTraceTime tm("phase 3", PrintGCDetails && Verbose, true, _gc_timer, _gc_tracer->gc_id());
   trace("3");
 
   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
@@ -655,7 +655,7 @@ void PSMarkSweep::mark_sweep_phase3() {
 
 void PSMarkSweep::mark_sweep_phase4() {
   EventMark m("4 compact heap");
-  GCTraceTime tm("phase 4", PrintGCDetails && Verbose, true, _gc_timer);
+  GCTraceTime tm("phase 4", PrintGCDetails && Verbose, true, _gc_timer, _gc_tracer->gc_id());
   trace("4");
 
   // All pointers are now adjusted, move objects accordingly
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
index cba23adae9fb71fd03d97e7951cfb33596967b6d..9f552fd1874468554d9a7907c4a485b11b2365cd 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
@@ -51,6 +51,7 @@
 #include "oops/methodData.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/fprofiler.hpp"
 #include "runtime/safepoint.hpp"
 #include "runtime/vmThread.hpp"
@@ -979,7 +980,7 @@ void PSParallelCompact::pre_compact(PreGCValues* pre_gc_values)
   // at each young gen gc.  Do the update unconditionally (even though a
   // promotion failure does not swap spaces) because an unknown number of minor
   // collections will have swapped the spaces an unknown number of times.
-  GCTraceTime tm("pre compact", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("pre compact", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
   ParallelScavengeHeap* heap = gc_heap();
   _space_info[from_space_id].set_space(heap->young_gen()->from_space());
   _space_info[to_space_id].set_space(heap->young_gen()->to_space());
@@ -1022,7 +1023,7 @@ void PSParallelCompact::pre_compact(PreGCValues* pre_gc_values)
 
 void PSParallelCompact::post_compact()
 {
-  GCTraceTime tm("post compact", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("post compact", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
     // Clear the marking bitmap, summary data and split info.
@@ -1848,7 +1849,7 @@ void PSParallelCompact::summary_phase_msg(SpaceId dst_space_id,
 void PSParallelCompact::summary_phase(ParCompactionManager* cm,
                                       bool maximum_compaction)
 {
-  GCTraceTime tm("summary phase", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("summary phase", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
   // trace("2");
 
 #ifdef  ASSERT
@@ -2057,7 +2058,7 @@ bool PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {
 
     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    GCTraceTime t1(GCCauseString("Full GC", gc_cause), PrintGC, !PrintGCDetails, NULL);
+    GCTraceTime t1(GCCauseString("Full GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer.gc_id());
     TraceCollectorStats tcs(counters());
     TraceMemoryManagerStats tms(true /* Full GC */,gc_cause);
 
@@ -2359,7 +2360,7 @@ void PSParallelCompact::marking_phase(ParCompactionManager* cm,
                                       bool maximum_heap_compaction,
                                       ParallelOldTracer *gc_tracer) {
   // Recursively traverse all live objects and mark them
-  GCTraceTime tm("marking phase", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("marking phase", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
   ParallelScavengeHeap* heap = gc_heap();
   uint parallel_gc_threads = heap->gc_task_manager()->workers();
@@ -2374,7 +2375,7 @@ void PSParallelCompact::marking_phase(ParCompactionManager* cm,
   ClassLoaderDataGraph::clear_claimed_marks();
 
   {
-    GCTraceTime tm_m("par mark", print_phases(), true, &_gc_timer);
+    GCTraceTime tm_m("par mark", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
     ParallelScavengeHeap::ParStrongRootsScope psrs;
 
@@ -2403,24 +2404,24 @@ void PSParallelCompact::marking_phase(ParCompactionManager* cm,
 
   // Process reference objects found during marking
   {
-    GCTraceTime tm_r("reference processing", print_phases(), true, &_gc_timer);
+    GCTraceTime tm_r("reference processing", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
     ReferenceProcessorStats stats;
     if (ref_processor()->processing_is_mt()) {
       RefProcTaskExecutor task_executor;
       stats = ref_processor()->process_discovered_references(
         is_alive_closure(), &mark_and_push_closure, &follow_stack_closure,
-        &task_executor, &_gc_timer);
+        &task_executor, &_gc_timer, _gc_tracer.gc_id());
     } else {
       stats = ref_processor()->process_discovered_references(
         is_alive_closure(), &mark_and_push_closure, &follow_stack_closure, NULL,
-        &_gc_timer);
+        &_gc_timer, _gc_tracer.gc_id());
     }
 
     gc_tracer->report_gc_reference_stats(stats);
   }
 
-  GCTraceTime tm_c("class unloading", print_phases(), true, &_gc_timer);
+  GCTraceTime tm_c("class unloading", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
   // This is the point where the entire marking should have completed.
   assert(cm->marking_stacks_empty(), "Marking should have completed");
@@ -2459,7 +2460,7 @@ static PSAlwaysTrueClosure always_true;
 
 void PSParallelCompact::adjust_roots() {
   // Adjust the pointers to reflect the new locations
-  GCTraceTime tm("adjust roots", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("adjust roots", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
   // Need new claim bits when tracing through and adjusting pointers.
   ClassLoaderDataGraph::clear_claimed_marks();
@@ -2495,7 +2496,7 @@ void PSParallelCompact::adjust_roots() {
 void PSParallelCompact::enqueue_region_draining_tasks(GCTaskQueue* q,
                                                       uint parallel_gc_threads)
 {
-  GCTraceTime tm("drain task setup", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("drain task setup", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
   // Find the threads that are active
   unsigned int which = 0;
@@ -2569,7 +2570,7 @@ void PSParallelCompact::enqueue_region_draining_tasks(GCTaskQueue* q,
 
 void PSParallelCompact::enqueue_dense_prefix_tasks(GCTaskQueue* q,
                                                     uint parallel_gc_threads) {
-  GCTraceTime tm("dense prefix task setup", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("dense prefix task setup", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
   ParallelCompactData& sd = PSParallelCompact::summary_data();
 
@@ -2651,7 +2652,7 @@ void PSParallelCompact::enqueue_region_stealing_tasks(
                                      GCTaskQueue* q,
                                      ParallelTaskTerminator* terminator_ptr,
                                      uint parallel_gc_threads) {
-  GCTraceTime tm("steal task setup", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("steal task setup", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
   // Once a thread has drained it's stack, it should try to steal regions from
   // other threads.
@@ -2699,7 +2700,7 @@ void PSParallelCompact::write_block_fill_histogram(outputStream* const out)
 
 void PSParallelCompact::compact() {
   // trace("5");
-  GCTraceTime tm("compaction phase", print_phases(), true, &_gc_timer);
+  GCTraceTime tm("compaction phase", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
@@ -2716,7 +2717,7 @@ void PSParallelCompact::compact() {
   enqueue_region_stealing_tasks(q, &terminator, active_gc_threads);
 
   {
-    GCTraceTime tm_pc("par compact", print_phases(), true, &_gc_timer);
+    GCTraceTime tm_pc("par compact", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
 
     gc_task_manager()->execute_and_wait(q);
 
@@ -2730,7 +2731,7 @@ void PSParallelCompact::compact() {
 
   {
     // Update the deferred objects, if any.  Any compaction manager can be used.
-    GCTraceTime tm_du("deferred updates", print_phases(), true, &_gc_timer);
+    GCTraceTime tm_du("deferred updates", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());
     ParCompactionManager* cm = ParCompactionManager::manager_array(0);
     for (unsigned int id = old_space_id; id < last_space_id; ++id) {
       update_deferred_objects(cm, SpaceId(id));
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp
index 9d37b133b05fa9f0edab8ad148add0ce93940242..c098e4557416c5de3614e35d52c75ede18cecdc6 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp
@@ -1004,6 +1004,10 @@ class PSParallelCompact : AllStatic {
   static bool   _dwl_initialized;
 #endif  // #ifdef ASSERT
 
+
+ public:
+  static ParallelOldTracer* gc_tracer() { return &_gc_tracer; }
+
  private:
 
   static void initialize_space_info();
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp
index e71122529b12c11553bc5adee654288a971758ff..7371832d5a3056e2178be2211b37c4a0e29d642f 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp
@@ -332,7 +332,7 @@ bool PSScavenge::invoke_no_policy() {
 
     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    GCTraceTime t1(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL);
+    GCTraceTime t1(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer.gc_id());
     TraceCollectorStats tcs(counters());
     TraceMemoryManagerStats tms(false /* not full GC */,gc_cause);
 
@@ -398,7 +398,7 @@ bool PSScavenge::invoke_no_policy() {
     // We'll use the promotion manager again later.
     PSPromotionManager* promotion_manager = PSPromotionManager::vm_thread_promotion_manager();
     {
-      GCTraceTime tm("Scavenge", false, false, &_gc_timer);
+      GCTraceTime tm("Scavenge", false, false, &_gc_timer, _gc_tracer.gc_id());
       ParallelScavengeHeap::ParStrongRootsScope psrs;
 
       GCTaskQueue* q = GCTaskQueue::create();
@@ -440,7 +440,7 @@ bool PSScavenge::invoke_no_policy() {
 
     // Process reference objects discovered during scavenge
     {
-      GCTraceTime tm("References", false, false, &_gc_timer);
+      GCTraceTime tm("References", false, false, &_gc_timer, _gc_tracer.gc_id());
 
       reference_processor()->setup_policy(false); // not always_clear
       reference_processor()->set_active_mt_degree(active_workers);
@@ -451,10 +451,10 @@ bool PSScavenge::invoke_no_policy() {
         PSRefProcTaskExecutor task_executor;
         stats = reference_processor()->process_discovered_references(
           &_is_alive_closure, &keep_alive, &evac_followers, &task_executor,
-          &_gc_timer);
+          &_gc_timer, _gc_tracer.gc_id());
       } else {
         stats = reference_processor()->process_discovered_references(
-          &_is_alive_closure, &keep_alive, &evac_followers, NULL, &_gc_timer);
+          &_is_alive_closure, &keep_alive, &evac_followers, NULL, &_gc_timer, _gc_tracer.gc_id());
       }
 
       _gc_tracer.report_gc_reference_stats(stats);
@@ -469,7 +469,7 @@ bool PSScavenge::invoke_no_policy() {
     }
 
     {
-      GCTraceTime tm("StringTable", false, false, &_gc_timer);
+      GCTraceTime tm("StringTable", false, false, &_gc_timer, _gc_tracer.gc_id());
       // Unlink any dead interned Strings and process the remaining live ones.
       PSScavengeRootsClosure root_closure(promotion_manager);
       StringTable::unlink_or_oops_do(&_is_alive_closure, &root_closure);
@@ -641,7 +641,7 @@ bool PSScavenge::invoke_no_policy() {
     NOT_PRODUCT(reference_processor()->verify_no_references_recorded());
 
     {
-      GCTraceTime tm("Prune Scavenge Root Methods", false, false, &_gc_timer);
+      GCTraceTime tm("Prune Scavenge Root Methods", false, false, &_gc_timer, _gc_tracer.gc_id());
 
       CodeCache::prune_scavenge_root_nmethods();
     }
diff --git a/hotspot/src/share/vm/gc_implementation/shared/ageTable.cpp b/hotspot/src/share/vm/gc_implementation/shared/ageTable.cpp
index 634d0a5ddc51c5f881b69f2faf751048fe940030..d69035625adf581731a9dcf76cb94a805319ba8e 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/ageTable.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/ageTable.cpp
@@ -28,6 +28,7 @@
 #include "memory/collectorPolicy.hpp"
 #include "memory/resourceArea.hpp"
 #include "memory/sharedHeap.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "utilities/copy.hpp"
 
 /* Copyright (c) 1992-2009 Oracle and/or its affiliates, and Stanford University.
diff --git a/hotspot/src/cpu/x86/vm/bytecodes_x86.cpp b/hotspot/src/share/vm/gc_implementation/shared/gcId.cpp
similarity index 71%
rename from hotspot/src/cpu/x86/vm/bytecodes_x86.cpp
rename to hotspot/src/share/vm/gc_implementation/shared/gcId.cpp
index 4e6993548c90b165ec281aaf3d56623f1d763171..ced64a46204e0952c4c33aa83ddb0d0eea7857eb 100644
--- a/hotspot/src/cpu/x86/vm/bytecodes_x86.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/gcId.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -23,15 +23,20 @@
  */
 
 #include "precompiled.hpp"
-#include "interpreter/bytecodes.hpp"
+#include "gc_implementation/shared/gcId.hpp"
+#include "runtime/safepoint.hpp"
 
+uint GCId::_next_id = 0;
 
-void Bytecodes::pd_initialize() {
-  // No i486 specific initialization
+const GCId GCId::create() {
+  return GCId(_next_id++);
 }
-
-
-Bytecodes::Code Bytecodes::pd_base_code_for(Code code) {
-  // No i486 specific bytecodes
-  return code;
+const GCId GCId::peek() {
+  return GCId(_next_id);
+}
+const GCId GCId::undefined() {
+  return GCId(UNDEFINED);
+}
+bool GCId::is_undefined() const {
+  return _id == UNDEFINED;
 }
diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcId.hpp b/hotspot/src/share/vm/gc_implementation/shared/gcId.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..1d2decc6bb5bc3d7da0cb5f0aa1bb72442c9aab6
--- /dev/null
+++ b/hotspot/src/share/vm/gc_implementation/shared/gcId.hpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014, 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_IMPLEMENTATION_SHARED_GCID_HPP
+#define SHARE_VM_GC_IMPLEMENTATION_SHARED_GCID_HPP
+
+#include "memory/allocation.hpp"
+
+class GCId VALUE_OBJ_CLASS_SPEC {
+ private:
+  uint _id;
+  GCId(uint id) : _id(id) {}
+  GCId() { } // Unused
+
+  static uint _next_id;
+  static const uint UNDEFINED = (uint)-1;
+
+ public:
+  uint id() const {
+    assert(_id != UNDEFINED, "Using undefined GC ID");
+    return _id;
+  }
+  bool is_undefined() const;
+
+  static const GCId create();
+  static const GCId peek();
+  static const GCId undefined();
+};
+
+#endif // SHARE_VM_GC_IMPLEMENTATION_SHARED_GCID_HPP
diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcTrace.cpp b/hotspot/src/share/vm/gc_implementation/shared/gcTrace.cpp
index 994d468bbc5392d0b6a9f42934797ed610b9f630..ddac9531667c17e85aa921b6d41c1f31188f4faf 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/gcTrace.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/gcTrace.cpp
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "gc_implementation/shared/copyFailedInfo.hpp"
 #include "gc_implementation/shared/gcHeapSummary.hpp"
+#include "gc_implementation/shared/gcId.hpp"
 #include "gc_implementation/shared/gcTimer.hpp"
 #include "gc_implementation/shared/gcTrace.hpp"
 #include "gc_implementation/shared/objectCountEventSender.hpp"
@@ -38,19 +39,14 @@
 #include "gc_implementation/g1/evacuationInfo.hpp"
 #endif
 
-#define assert_unset_gc_id() assert(_shared_gc_info.id() == SharedGCInfo::UNSET_GCID, "GC already started?")
-#define assert_set_gc_id() assert(_shared_gc_info.id() != SharedGCInfo::UNSET_GCID, "GC not started?")
-
-static GCId GCTracer_next_gc_id = 0;
-static GCId create_new_gc_id() {
-  return GCTracer_next_gc_id++;
-}
+#define assert_unset_gc_id() assert(_shared_gc_info.gc_id().is_undefined(), "GC already started?")
+#define assert_set_gc_id() assert(!_shared_gc_info.gc_id().is_undefined(), "GC not started?")
 
 void GCTracer::report_gc_start_impl(GCCause::Cause cause, const Ticks& timestamp) {
   assert_unset_gc_id();
 
-  GCId gc_id = create_new_gc_id();
-  _shared_gc_info.set_id(gc_id);
+  GCId gc_id = GCId::create();
+  _shared_gc_info.set_gc_id(gc_id);
   _shared_gc_info.set_cause(cause);
   _shared_gc_info.set_start_timestamp(timestamp);
 }
@@ -62,7 +58,7 @@ void GCTracer::report_gc_start(GCCause::Cause cause, const Ticks& timestamp) {
 }
 
 bool GCTracer::has_reported_gc_start() const {
-  return _shared_gc_info.id() != SharedGCInfo::UNSET_GCID;
+  return !_shared_gc_info.gc_id().is_undefined();
 }
 
 void GCTracer::report_gc_end_impl(const Ticks& timestamp, TimePartitions* time_partitions) {
@@ -81,7 +77,7 @@ void GCTracer::report_gc_end(const Ticks& timestamp, TimePartitions* time_partit
 
   report_gc_end_impl(timestamp, time_partitions);
 
-  _shared_gc_info.set_id(SharedGCInfo::UNSET_GCID);
+  _shared_gc_info.set_gc_id(GCId::undefined());
 }
 
 void GCTracer::report_gc_reference_stats(const ReferenceProcessorStats& rps) const {
@@ -132,7 +128,7 @@ void GCTracer::report_object_count_after_gc(BoolObjectClosure* is_alive_cl) {
     if (!cit.allocation_failed()) {
       HeapInspection hi(false, false, false, NULL);
       hi.populate_table(&cit, is_alive_cl);
-      ObjectCountEventSenderClosure event_sender(_shared_gc_info.id(), cit.size_of_instances_in_words(), Ticks::now());
+      ObjectCountEventSenderClosure event_sender(_shared_gc_info.gc_id(), cit.size_of_instances_in_words(), Ticks::now());
       cit.iterate(&event_sender);
     }
   }
diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcTrace.hpp b/hotspot/src/share/vm/gc_implementation/shared/gcTrace.hpp
index 3b55211a724893641edfd87e55bcf19027e3dba7..dd13344155fcd6fb0b6cf74d9df7b4750e742658 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/gcTrace.hpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/gcTrace.hpp
@@ -27,6 +27,7 @@
 
 #include "gc_interface/gcCause.hpp"
 #include "gc_interface/gcName.hpp"
+#include "gc_implementation/shared/gcId.hpp"
 #include "gc_implementation/shared/gcWhen.hpp"
 #include "gc_implementation/shared/copyFailedInfo.hpp"
 #include "memory/allocation.hpp"
@@ -38,7 +39,6 @@
 #include "utilities/macros.hpp"
 #include "utilities/ticks.hpp"
 
-typedef uint GCId;
 
 class EvacuationInfo;
 class GCHeapSummary;
@@ -50,11 +50,8 @@ class TimePartitions;
 class BoolObjectClosure;
 
 class SharedGCInfo VALUE_OBJ_CLASS_SPEC {
- public:
-  static const GCId UNSET_GCID = (GCId)-1;
-
  private:
-  GCId _id;
+  GCId _gc_id;
   GCName _name;
   GCCause::Cause _cause;
   Ticks     _start_timestamp;
@@ -64,7 +61,7 @@ class SharedGCInfo VALUE_OBJ_CLASS_SPEC {
 
  public:
   SharedGCInfo(GCName name) :
-    _id(UNSET_GCID),
+    _gc_id(GCId::undefined()),
     _name(name),
     _cause(GCCause::_last_gc_cause),
     _start_timestamp(),
@@ -73,8 +70,8 @@ class SharedGCInfo VALUE_OBJ_CLASS_SPEC {
     _longest_pause() {
   }
 
-  void set_id(GCId id) { _id = id; }
-  GCId id() const { return _id; }
+  void set_gc_id(GCId gc_id) { _gc_id = gc_id; }
+  const GCId& gc_id() const { return _gc_id; }
 
   void set_start_timestamp(const Ticks& timestamp) { _start_timestamp = timestamp; }
   const Ticks start_timestamp() const { return _start_timestamp; }
@@ -131,10 +128,11 @@ class GCTracer : public ResourceObj {
   void report_gc_reference_stats(const ReferenceProcessorStats& rp) const;
   void report_object_count_after_gc(BoolObjectClosure* object_filter) NOT_SERVICES_RETURN;
   bool has_reported_gc_start() const;
+  const GCId& gc_id() { return _shared_gc_info.gc_id(); }
 
  protected:
   GCTracer(GCName name) : _shared_gc_info(name) {}
-  virtual void report_gc_start_impl(GCCause::Cause cause, const Ticks& timestamp);
+  void report_gc_start_impl(GCCause::Cause cause, const Ticks& timestamp);
   virtual void report_gc_end_impl(const Ticks& timestamp, TimePartitions* time_partitions);
 
  private:
diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcTraceSend.cpp b/hotspot/src/share/vm/gc_implementation/shared/gcTraceSend.cpp
index 95ca83a4a1d57bb9da907e8dc58049a4b0df1bfc..5462135a0145c3e655a9e0ca98ebe6a45360ebab 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/gcTraceSend.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/gcTraceSend.cpp
@@ -43,7 +43,7 @@ typedef uintptr_t TraceAddress;
 void GCTracer::send_garbage_collection_event() const {
   EventGCGarbageCollection event(UNTIMED);
   if (event.should_commit()) {
-    event.set_gcId(_shared_gc_info.id());
+    event.set_gcId(_shared_gc_info.gc_id().id());
     event.set_name(_shared_gc_info.name());
     event.set_cause((u2) _shared_gc_info.cause());
     event.set_sumOfPauses(_shared_gc_info.sum_of_pauses());
@@ -57,7 +57,7 @@ void GCTracer::send_garbage_collection_event() const {
 void GCTracer::send_reference_stats_event(ReferenceType type, size_t count) const {
   EventGCReferenceStatistics e;
   if (e.should_commit()) {
-      e.set_gcId(_shared_gc_info.id());
+      e.set_gcId(_shared_gc_info.gc_id().id());
       e.set_type((u1)type);
       e.set_count(count);
       e.commit();
@@ -68,7 +68,7 @@ void GCTracer::send_metaspace_chunk_free_list_summary(GCWhen::Type when, Metaspa
                                                       const MetaspaceChunkFreeListSummary& summary) const {
   EventMetaspaceChunkFreeListSummary e;
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_when(when);
     e.set_metadataType(mdtype);
 
@@ -91,7 +91,7 @@ void GCTracer::send_metaspace_chunk_free_list_summary(GCWhen::Type when, Metaspa
 void ParallelOldTracer::send_parallel_old_event() const {
   EventGCParallelOld e(UNTIMED);
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_densePrefix((TraceAddress)_parallel_old_gc_info.dense_prefix());
     e.set_starttime(_shared_gc_info.start_timestamp());
     e.set_endtime(_shared_gc_info.end_timestamp());
@@ -102,7 +102,7 @@ void ParallelOldTracer::send_parallel_old_event() const {
 void YoungGCTracer::send_young_gc_event() const {
   EventGCYoungGarbageCollection e(UNTIMED);
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_tenuringThreshold(_tenuring_threshold);
     e.set_starttime(_shared_gc_info.start_timestamp());
     e.set_endtime(_shared_gc_info.end_timestamp());
@@ -113,7 +113,7 @@ void YoungGCTracer::send_young_gc_event() const {
 void OldGCTracer::send_old_gc_event() const {
   EventGCOldGarbageCollection e(UNTIMED);
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_starttime(_shared_gc_info.start_timestamp());
     e.set_endtime(_shared_gc_info.end_timestamp());
     e.commit();
@@ -132,7 +132,7 @@ static TraceStructCopyFailed to_trace_struct(const CopyFailedInfo& cf_info) {
 void YoungGCTracer::send_promotion_failed_event(const PromotionFailedInfo& pf_info) const {
   EventPromotionFailed e;
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_data(to_trace_struct(pf_info));
     e.set_thread(pf_info.thread()->thread_id());
     e.commit();
@@ -143,7 +143,7 @@ void YoungGCTracer::send_promotion_failed_event(const PromotionFailedInfo& pf_in
 void OldGCTracer::send_concurrent_mode_failure_event() {
   EventConcurrentModeFailure e;
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.commit();
   }
 }
@@ -152,7 +152,7 @@ void OldGCTracer::send_concurrent_mode_failure_event() {
 void G1NewTracer::send_g1_young_gc_event() {
   EventGCG1GarbageCollection e(UNTIMED);
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_type(_g1_young_gc_info.type());
     e.set_starttime(_shared_gc_info.start_timestamp());
     e.set_endtime(_shared_gc_info.end_timestamp());
@@ -163,7 +163,7 @@ void G1NewTracer::send_g1_young_gc_event() {
 void G1NewTracer::send_evacuation_info_event(EvacuationInfo* info) {
   EventEvacuationInfo e;
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_cSetRegions(info->collectionset_regions());
     e.set_cSetUsedBefore(info->collectionset_used_before());
     e.set_cSetUsedAfter(info->collectionset_used_after());
@@ -179,7 +179,7 @@ void G1NewTracer::send_evacuation_info_event(EvacuationInfo* info) {
 void G1NewTracer::send_evacuation_failed_event(const EvacuationFailedInfo& ef_info) const {
   EventEvacuationFailed e;
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_data(to_trace_struct(ef_info));
     e.commit();
   }
@@ -206,17 +206,17 @@ static TraceStructObjectSpace to_trace_struct(const SpaceSummary& summary) {
 }
 
 class GCHeapSummaryEventSender : public GCHeapSummaryVisitor {
-  GCId _id;
+  GCId _gc_id;
   GCWhen::Type _when;
  public:
-  GCHeapSummaryEventSender(GCId id, GCWhen::Type when) : _id(id), _when(when) {}
+  GCHeapSummaryEventSender(GCId gc_id, GCWhen::Type when) : _gc_id(gc_id), _when(when) {}
 
   void visit(const GCHeapSummary* heap_summary) const {
     const VirtualSpaceSummary& heap_space = heap_summary->heap();
 
     EventGCHeapSummary e;
     if (e.should_commit()) {
-      e.set_gcId(_id);
+      e.set_gcId(_gc_id.id());
       e.set_when((u1)_when);
       e.set_heapSpace(to_trace_struct(heap_space));
       e.set_heapUsed(heap_summary->used());
@@ -236,7 +236,7 @@ class GCHeapSummaryEventSender : public GCHeapSummaryVisitor {
 
     EventPSHeapSummary e;
     if (e.should_commit()) {
-      e.set_gcId(_id);
+      e.set_gcId(_gc_id.id());
       e.set_when((u1)_when);
 
       e.set_oldSpace(to_trace_struct(ps_heap_summary->old()));
@@ -251,7 +251,7 @@ class GCHeapSummaryEventSender : public GCHeapSummaryVisitor {
 };
 
 void GCTracer::send_gc_heap_summary_event(GCWhen::Type when, const GCHeapSummary& heap_summary) const {
-  GCHeapSummaryEventSender visitor(_shared_gc_info.id(), when);
+  GCHeapSummaryEventSender visitor(_shared_gc_info.gc_id(), when);
   heap_summary.accept(&visitor);
 }
 
@@ -268,7 +268,7 @@ static TraceStructMetaspaceSizes to_trace_struct(const MetaspaceSizes& sizes) {
 void GCTracer::send_meta_space_summary_event(GCWhen::Type when, const MetaspaceSummary& meta_space_summary) const {
   EventMetaspaceSummary e;
   if (e.should_commit()) {
-    e.set_gcId(_shared_gc_info.id());
+    e.set_gcId(_shared_gc_info.gc_id().id());
     e.set_when((u1) when);
     e.set_gcThreshold(meta_space_summary.capacity_until_GC());
     e.set_metaspace(to_trace_struct(meta_space_summary.meta_space()));
@@ -287,7 +287,7 @@ class PhaseSender : public PhaseVisitor {
   void send_phase(PausePhase* pause) {
     T event(UNTIMED);
     if (event.should_commit()) {
-      event.set_gcId(_gc_id);
+      event.set_gcId(_gc_id.id());
       event.set_name(pause->name());
       event.set_starttime(pause->start());
       event.set_endtime(pause->end());
@@ -311,7 +311,7 @@ class PhaseSender : public PhaseVisitor {
 };
 
 void GCTracer::send_phase_events(TimePartitions* time_partitions) const {
-  PhaseSender phase_reporter(_shared_gc_info.id());
+  PhaseSender phase_reporter(_shared_gc_info.gc_id());
 
   TimePartitionPhasesIterator iter(time_partitions);
   while (iter.has_next()) {
diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcTraceTime.cpp b/hotspot/src/share/vm/gc_implementation/shared/gcTraceTime.cpp
index 033ca6b779da876f409f8b2f7646e63a73f04001..83890611ec5cb0cc1dff1a4ebb0411bc88b0c27d 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/gcTraceTime.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/gcTraceTime.cpp
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "gc_implementation/shared/gcTimer.hpp"
+#include "gc_implementation/shared/gcTrace.hpp"
 #include "gc_implementation/shared/gcTraceTime.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/os.hpp"
@@ -34,7 +35,7 @@
 #include "utilities/ticks.inline.hpp"
 
 
-GCTraceTime::GCTraceTime(const char* title, bool doit, bool print_cr, GCTimer* timer) :
+GCTraceTime::GCTraceTime(const char* title, bool doit, bool print_cr, GCTimer* timer, GCId gc_id) :
     _title(title), _doit(doit), _print_cr(print_cr), _timer(timer), _start_counter() {
   if (_doit || _timer != NULL) {
     _start_counter.stamp();
@@ -52,6 +53,9 @@ GCTraceTime::GCTraceTime(const char* title, bool doit, bool print_cr, GCTimer* t
       gclog_or_tty->stamp();
       gclog_or_tty->print(": ");
     }
+    if (PrintGCID) {
+      gclog_or_tty->print("#%u: ", gc_id.id());
+    }
     gclog_or_tty->print("[%s", title);
     gclog_or_tty->flush();
   }
diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcTraceTime.hpp b/hotspot/src/share/vm/gc_implementation/shared/gcTraceTime.hpp
index 83df182f90cf93c55ef2f1b6de381c621fa6a599..30e494baa52115db3663e0e0e5c8c28eea739ea7 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/gcTraceTime.hpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/gcTraceTime.hpp
@@ -25,6 +25,7 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_GCTRACETIME_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_GCTRACETIME_HPP
 
+#include "gc_implementation/shared/gcTrace.hpp"
 #include "prims/jni_md.h"
 #include "utilities/ticks.hpp"
 
@@ -38,7 +39,7 @@ class GCTraceTime {
   Ticks _start_counter;
 
  public:
-  GCTraceTime(const char* title, bool doit, bool print_cr, GCTimer* timer);
+  GCTraceTime(const char* title, bool doit, bool print_cr, GCTimer* timer, GCId gc_id);
   ~GCTraceTime();
 };
 
diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
index 8590e850b60a627fbf4baecacf7845010a0ef5cb..965aedea05320a77dbf23a8a0c9db137957fd551 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
@@ -28,6 +28,7 @@
 #include "gc_implementation/shared/spaceDecorator.hpp"
 #include "memory/sharedHeap.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/thread.inline.hpp"
 
 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp b/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp
index 17a3ecbc14afb9d7d85b1c77d0fcc08c3610ddd4..f5661fbb412cd9815dd77c87cb50521c3aafe7df 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "utilities/macros.hpp"
 #if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/mutableSpace.hpp"
diff --git a/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.cpp b/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.cpp
index 7504a21c2cd8d04fb9007d20a85f26d27f3ac45d..4e0dc6077a660b7b59cbdfbc361b9b7e79f06ac8 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.cpp
@@ -24,6 +24,7 @@
 
 
 #include "precompiled.hpp"
+#include "gc_implementation/shared/gcId.hpp"
 #include "gc_implementation/shared/objectCountEventSender.hpp"
 #include "memory/heapInspection.hpp"
 #include "trace/tracing.hpp"
@@ -38,7 +39,7 @@ void ObjectCountEventSender::send(const KlassInfoEntry* entry, GCId gc_id, const
          "Only call this method if the event is enabled");
 
   EventObjectCountAfterGC event(UNTIMED);
-  event.set_gcId(gc_id);
+  event.set_gcId(gc_id.id());
   event.set_class(entry->klass());
   event.set_count(entry->count());
   event.set_totalSize(entry->words() * BytesPerWord);
diff --git a/hotspot/src/share/vm/gc_interface/collectedHeap.cpp b/hotspot/src/share/vm/gc_interface/collectedHeap.cpp
index 1304092002ed7d32bf6a756ed4b9073fd93af4a8..ddad402c25980374d8c0a9903901914a6122aa9c 100644
--- a/hotspot/src/share/vm/gc_interface/collectedHeap.cpp
+++ b/hotspot/src/share/vm/gc_interface/collectedHeap.cpp
@@ -558,13 +558,13 @@ void CollectedHeap::resize_all_tlabs() {
 
 void CollectedHeap::pre_full_gc_dump(GCTimer* timer) {
   if (HeapDumpBeforeFullGC) {
-    GCTraceTime tt("Heap Dump (before full gc): ", PrintGCDetails, false, timer);
+    GCTraceTime tt("Heap Dump (before full gc): ", PrintGCDetails, false, timer, GCId::create());
     // We are doing a "major" collection and a heap dump before
     // major collection has been requested.
     HeapDumper::dump_heap();
   }
   if (PrintClassHistogramBeforeFullGC) {
-    GCTraceTime tt("Class Histogram (before full gc): ", PrintGCDetails, true, timer);
+    GCTraceTime tt("Class Histogram (before full gc): ", PrintGCDetails, true, timer, GCId::create());
     VM_GC_HeapInspection inspector(gclog_or_tty, false /* ! full gc */);
     inspector.doit();
   }
@@ -572,11 +572,11 @@ void CollectedHeap::pre_full_gc_dump(GCTimer* timer) {
 
 void CollectedHeap::post_full_gc_dump(GCTimer* timer) {
   if (HeapDumpAfterFullGC) {
-    GCTraceTime tt("Heap Dump (after full gc): ", PrintGCDetails, false, timer);
+    GCTraceTime tt("Heap Dump (after full gc): ", PrintGCDetails, false, timer, GCId::create());
     HeapDumper::dump_heap();
   }
   if (PrintClassHistogramAfterFullGC) {
-    GCTraceTime tt("Class Histogram (after full gc): ", PrintGCDetails, true, timer);
+    GCTraceTime tt("Class Histogram (after full gc): ", PrintGCDetails, true, timer, GCId::create());
     VM_GC_HeapInspection inspector(gclog_or_tty, false /* ! full gc */);
     inspector.doit();
   }
diff --git a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp
index 6c30983c2eaf7e7011daf4f29d7af7f777e247d3..323f67fc1f62ffcb194ba21cb959f0fb1dfbb4e7 100644
--- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp
+++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, 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,6 +37,7 @@
 #include "oops/oop.inline.hpp"
 #include "prims/jvmtiExport.hpp"
 #include "prims/jvmtiThreadState.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/frame.inline.hpp"
 #include "runtime/handles.inline.hpp"
@@ -2782,11 +2783,11 @@ run:
       if (TraceExceptions) {
         ttyLocker ttyl;
         ResourceMark rm;
-        tty->print_cr("Exception <%s> (" INTPTR_FORMAT ")", except_oop->print_value_string(), (void*)except_oop());
+        tty->print_cr("Exception <%s> (" INTPTR_FORMAT ")", except_oop->print_value_string(), p2i(except_oop()));
         tty->print_cr(" thrown in interpreter method <%s>", METHOD->print_value_string());
         tty->print_cr(" at bci %d, continuing at %d for thread " INTPTR_FORMAT,
-                      istate->bcp() - (intptr_t)METHOD->code_base(),
-                      continuation_bci, THREAD);
+                      (int)(istate->bcp() - METHOD->code_base()),
+                      (int)continuation_bci, p2i(THREAD));
       }
       // for AbortVMOnException flag
       NOT_PRODUCT(Exceptions::debug_check_abort(except_oop));
@@ -2798,11 +2799,11 @@ run:
     if (TraceExceptions) {
       ttyLocker ttyl;
       ResourceMark rm;
-      tty->print_cr("Exception <%s> (" INTPTR_FORMAT ")", except_oop->print_value_string(), (void*)except_oop());
+      tty->print_cr("Exception <%s> (" INTPTR_FORMAT ")", except_oop->print_value_string(), p2i(except_oop()));
       tty->print_cr(" thrown in interpreter method <%s>", METHOD->print_value_string());
       tty->print_cr(" at bci %d, unwinding for thread " INTPTR_FORMAT,
-                    istate->bcp() - (intptr_t)METHOD->code_base(),
-                    THREAD);
+                    (int)(istate->bcp() - METHOD->code_base()),
+                    p2i(THREAD));
     }
     // for AbortVMOnException flag
     NOT_PRODUCT(Exceptions::debug_check_abort(except_oop));
@@ -3401,7 +3402,7 @@ BytecodeInterpreter::print() {
   tty->print_cr("osr._osr_buf: " INTPTR_FORMAT, (uintptr_t) this->_result._osr._osr_buf);
   tty->print_cr("osr._osr_entry: " INTPTR_FORMAT, (uintptr_t) this->_result._osr._osr_entry);
   tty->print_cr("prev_link: " INTPTR_FORMAT, (uintptr_t) this->_prev_link);
-  tty->print_cr("native_mirror: " INTPTR_FORMAT, (void*) this->_oop_temp);
+  tty->print_cr("native_mirror: " INTPTR_FORMAT, (uintptr_t) this->_oop_temp);
   tty->print_cr("stack_base: " INTPTR_FORMAT, (uintptr_t) this->_stack_base);
   tty->print_cr("stack_limit: " INTPTR_FORMAT, (uintptr_t) this->_stack_limit);
   tty->print_cr("monitor_base: " INTPTR_FORMAT, (uintptr_t) this->_monitor_base);
diff --git a/hotspot/src/share/vm/interpreter/bytecodeInterpreterProfiling.hpp b/hotspot/src/share/vm/interpreter/bytecodeInterpreterProfiling.hpp
index 095a989cc012f7effb97d6c94c3bb0f9db9b16f8..86b6c22822f88abb05b06273139a9d5e85062077 100644
--- a/hotspot/src/share/vm/interpreter/bytecodeInterpreterProfiling.hpp
+++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreterProfiling.hpp
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2012, 2014 SAP AG. 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
@@ -86,11 +86,11 @@
                   " \t-> " PTR_FORMAT "(%d)",                                  \
                 (int) THREAD->osthread()->thread_id(),                         \
                 BCI(),                                                         \
-                MDX(),                                                         \
+                p2i(MDX()),                                                    \
                 (MDX() == NULL                                                 \
                  ? 0                                                           \
                  : istate->method()->method_data()->dp_to_di((address)MDX())), \
-                mdx,                                                           \
+                p2i(mdx),                                                      \
                 istate->method()->method_data()->dp_to_di((address)mdx)        \
                 );                                                             \
   };                                                                           \
@@ -107,7 +107,7 @@
     MethodData *md = istate->method()->method_data();                          \
     tty->cr();                                                                 \
     tty->print("method data at mdx " PTR_FORMAT "(0) for",                     \
-               md->data_layout_at(md->bci_to_di(0)));                          \
+               p2i(md->data_layout_at(md->bci_to_di(0))));                     \
     istate->method()->print_short_name(tty);                                   \
     tty->cr();                                                                 \
     if (md != NULL) {                                                          \
@@ -115,7 +115,7 @@
       address mdx = (address) MDX();                                           \
       if (mdx != NULL) {                                                       \
         tty->print_cr("current mdx " PTR_FORMAT "(%d)",                        \
-                      mdx,                                                     \
+                      p2i(mdx),                                                \
                       istate->method()->method_data()->dp_to_di(mdx));         \
       }                                                                        \
     } else {                                                                   \
diff --git a/hotspot/src/share/vm/interpreter/bytecodes.cpp b/hotspot/src/share/vm/interpreter/bytecodes.cpp
index 0f78210fcc9d024abb64ce07519316dd9306a113..5c26a4a751fd6183e3c7a0abd8ccd53bb8e5e50a 100644
--- a/hotspot/src/share/vm/interpreter/bytecodes.cpp
+++ b/hotspot/src/share/vm/interpreter/bytecodes.cpp
@@ -541,9 +541,6 @@ void Bytecodes::initialize() {
 
   def(_shouldnotreachhere  , "_shouldnotreachhere" , "b"    , NULL    , T_VOID   ,  0, false);
 
-  // platform specific JVM bytecodes
-  pd_initialize();
-
   // compare can_trap information for each bytecode with the
   // can_trap information for the corresponding base bytecode
   // (if a rewritten bytecode can trap, so must the base bytecode)
diff --git a/hotspot/src/share/vm/interpreter/bytecodes.hpp b/hotspot/src/share/vm/interpreter/bytecodes.hpp
index 2cb49c98cb143a20b47642857556564575a748a3..04a1f564abcfc265d358ed7075002ff5732e3104 100644
--- a/hotspot/src/share/vm/interpreter/bytecodes.hpp
+++ b/hotspot/src/share/vm/interpreter/bytecodes.hpp
@@ -287,23 +287,6 @@ class Bytecodes: AllStatic {
 
     _shouldnotreachhere,      // For debugging
 
-    // Platform specific JVM bytecodes
-#ifdef TARGET_ARCH_x86
-# include "bytecodes_x86.hpp"
-#endif
-#ifdef TARGET_ARCH_sparc
-# include "bytecodes_sparc.hpp"
-#endif
-#ifdef TARGET_ARCH_zero
-# include "bytecodes_zero.hpp"
-#endif
-#ifdef TARGET_ARCH_arm
-# include "bytecodes_arm.hpp"
-#endif
-#ifdef TARGET_ARCH_ppc
-# include "bytecodes_ppc.hpp"
-#endif
-
 
     number_of_codes
   };
@@ -348,8 +331,6 @@ class Bytecodes: AllStatic {
 
   static void        def(Code code, const char* name, const char* format, const char* wide_format, BasicType result_type, int depth, bool can_trap);
   static void        def(Code code, const char* name, const char* format, const char* wide_format, BasicType result_type, int depth, bool can_trap, Code java_code);
-  static void        pd_initialize();              // platform specific initialization
-  static Code        pd_base_code_for(Code code);  // platform specific base_code_for implementation
 
   // Verify that bcp points into method
 #ifdef ASSERT
diff --git a/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp b/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp
index 0f79ab5072f4caff90e3306c95849a19cd91e8df..42a721839a84543fca8f9c97d23229fab680d824 100644
--- a/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp
+++ b/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp
@@ -42,6 +42,7 @@
 #include "oops/symbol.hpp"
 #include "prims/jvmtiExport.hpp"
 #include "prims/nativeLookup.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/compilationPolicy.hpp"
 #include "runtime/deoptimization.hpp"
diff --git a/hotspot/src/share/vm/memory/allocation.cpp b/hotspot/src/share/vm/memory/allocation.cpp
index c0254d9123f25f5d65494058f2ea6ebfa6073c2f..588b01981d06a2ec74d175d4c0636f6640440fa9 100644
--- a/hotspot/src/share/vm/memory/allocation.cpp
+++ b/hotspot/src/share/vm/memory/allocation.cpp
@@ -29,7 +29,7 @@
 #include "memory/metaspaceShared.hpp"
 #include "memory/resourceArea.hpp"
 #include "memory/universe.hpp"
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 #include "runtime/task.hpp"
 #include "runtime/threadCritical.hpp"
diff --git a/hotspot/src/share/vm/memory/cardTableRS.cpp b/hotspot/src/share/vm/memory/cardTableRS.cpp
index 56af890a4219f1bda1bafa3ce04096c566e11567..7c9d3618673854eef1f955eaa541eaa9f4b24121 100644
--- a/hotspot/src/share/vm/memory/cardTableRS.cpp
+++ b/hotspot/src/share/vm/memory/cardTableRS.cpp
@@ -29,6 +29,7 @@
 #include "memory/generation.hpp"
 #include "memory/space.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/java.hpp"
 #include "runtime/os.hpp"
 #include "utilities/macros.hpp"
diff --git a/hotspot/src/share/vm/memory/defNewGeneration.cpp b/hotspot/src/share/vm/memory/defNewGeneration.cpp
index bf51090df12d6b3f5ea260202f2c4d7805370476..1a904b5c63688c7dbb952844e8ec48ed3c70e076 100644
--- a/hotspot/src/share/vm/memory/defNewGeneration.cpp
+++ b/hotspot/src/share/vm/memory/defNewGeneration.cpp
@@ -41,6 +41,7 @@
 #include "memory/space.inline.hpp"
 #include "oops/instanceRefKlass.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/java.hpp"
 #include "runtime/prefetch.inline.hpp"
 #include "runtime/thread.inline.hpp"
@@ -585,7 +586,7 @@ void DefNewGeneration::collect(bool   full,
 
   init_assuming_no_promotion_failure();
 
-  GCTraceTime t1(GCCauseString("GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL);
+  GCTraceTime t1(GCCauseString("GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL, gc_tracer.gc_id());
   // Capture heap used before collection (for printing).
   size_t gch_prev_used = gch->used();
 
@@ -641,7 +642,7 @@ void DefNewGeneration::collect(bool   full,
   rp->setup_policy(clear_all_soft_refs);
   const ReferenceProcessorStats& stats =
   rp->process_discovered_references(&is_alive, &keep_alive, &evacuate_followers,
-                                    NULL, _gc_timer);
+                                    NULL, _gc_timer, gc_tracer.gc_id());
   gc_tracer.report_gc_reference_stats(stats);
 
   if (!_promotion_failed) {
diff --git a/hotspot/src/share/vm/memory/gcLocker.cpp b/hotspot/src/share/vm/memory/gcLocker.cpp
index 9674263793987321337ed76aa18f85bee7d754a2..fae40920a8747d5e4ac7e6157e1ba88b626e38b7 100644
--- a/hotspot/src/share/vm/memory/gcLocker.cpp
+++ b/hotspot/src/share/vm/memory/gcLocker.cpp
@@ -26,6 +26,7 @@
 #include "memory/gcLocker.inline.hpp"
 #include "memory/resourceArea.hpp"
 #include "memory/sharedHeap.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/thread.inline.hpp"
 
 volatile jint GC_locker::_jni_lock_count = 0;
@@ -59,6 +60,17 @@ void GC_locker::verify_critical_count() {
     assert(_jni_lock_count == count, "must be equal");
   }
 }
+
+// In debug mode track the locking state at all times
+void GC_locker::increment_debug_jni_lock_count() {
+  assert(_debug_jni_lock_count >= 0, "bad value");
+  Atomic::inc(&_debug_jni_lock_count);
+}
+
+void GC_locker::decrement_debug_jni_lock_count() {
+  assert(_debug_jni_lock_count > 0, "bad value");
+  Atomic::dec(&_debug_jni_lock_count);
+}
 #endif
 
 bool GC_locker::check_active_before_gc() {
diff --git a/hotspot/src/share/vm/memory/gcLocker.hpp b/hotspot/src/share/vm/memory/gcLocker.hpp
index f12aa6755525154004bea34b029f3c9448da88e8..161bd42993f415f24884cd9aa9d8de686a8fedee 100644
--- a/hotspot/src/share/vm/memory/gcLocker.hpp
+++ b/hotspot/src/share/vm/memory/gcLocker.hpp
@@ -94,18 +94,8 @@ class GC_locker: public AllStatic {
   }
 
   // In debug mode track the locking state at all times
-  static void increment_debug_jni_lock_count() {
-#ifdef ASSERT
-    assert(_debug_jni_lock_count >= 0, "bad value");
-    Atomic::inc(&_debug_jni_lock_count);
-#endif
-  }
-  static void decrement_debug_jni_lock_count() {
-#ifdef ASSERT
-    assert(_debug_jni_lock_count > 0, "bad value");
-    Atomic::dec(&_debug_jni_lock_count);
-#endif
-  }
+  static void increment_debug_jni_lock_count() NOT_DEBUG_RETURN;
+  static void decrement_debug_jni_lock_count() NOT_DEBUG_RETURN;
 
   // Set the current lock count
   static void set_jni_lock_count(int count) {
diff --git a/hotspot/src/share/vm/memory/genCollectedHeap.cpp b/hotspot/src/share/vm/memory/genCollectedHeap.cpp
index a774f4051e6101bcd879b4f7725b6bfa89c34872..bdb915ebb0c1ed6fa7c5441b018d76f08ceb7a87 100644
--- a/hotspot/src/share/vm/memory/genCollectedHeap.cpp
+++ b/hotspot/src/share/vm/memory/genCollectedHeap.cpp
@@ -28,6 +28,7 @@
 #include "classfile/vmSymbols.hpp"
 #include "code/icBuffer.hpp"
 #include "gc_implementation/shared/collectorCounters.hpp"
+#include "gc_implementation/shared/gcTrace.hpp"
 #include "gc_implementation/shared/gcTraceTime.hpp"
 #include "gc_implementation/shared/vmGCOperations.hpp"
 #include "gc_interface/collectedHeap.inline.hpp"
@@ -384,7 +385,9 @@ void GenCollectedHeap::do_collection(bool  full,
     const char* gc_cause_prefix = complete ? "Full GC" : "GC";
     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
-    GCTraceTime t(GCCauseString(gc_cause_prefix, gc_cause()), PrintGCDetails, false, NULL);
+    // The PrintGCDetails logging starts before we have incremented the GC id. We will do that later
+    // so we can assume here that the next GC id is what we want.
+    GCTraceTime t(GCCauseString(gc_cause_prefix, gc_cause()), PrintGCDetails, false, NULL, GCId::peek());
 
     gc_prologue(complete);
     increment_total_collections(complete);
@@ -417,7 +420,9 @@ void GenCollectedHeap::do_collection(bool  full,
         }
         // Timer for individual generations. Last argument is false: no CR
         // FIXME: We should try to start the timing earlier to cover more of the GC pause
-        GCTraceTime t1(_gens[i]->short_name(), PrintGCDetails, false, NULL);
+        // The PrintGCDetails logging starts before we have incremented the GC id. We will do that later
+        // so we can assume here that the next GC id is what we want.
+        GCTraceTime t1(_gens[i]->short_name(), PrintGCDetails, false, NULL, GCId::peek());
         TraceCollectorStats tcs(_gens[i]->counters());
         TraceMemoryManagerStats tmms(_gens[i]->kind(),gc_cause());
 
diff --git a/hotspot/src/share/vm/memory/genMarkSweep.cpp b/hotspot/src/share/vm/memory/genMarkSweep.cpp
index 64d7c3eaa6167d5df0c698e6da6158efde76a98c..dcd7308843eb4230d7226d70c50c21e655919677 100644
--- a/hotspot/src/share/vm/memory/genMarkSweep.cpp
+++ b/hotspot/src/share/vm/memory/genMarkSweep.cpp
@@ -69,7 +69,7 @@ void GenMarkSweep::invoke_at_safepoint(int level, ReferenceProcessor* rp, bool c
   _ref_processor = rp;
   rp->setup_policy(clear_all_softrefs);
 
-  GCTraceTime t1(GCCauseString("Full GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL);
+  GCTraceTime t1(GCCauseString("Full GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL, _gc_tracer->gc_id());
 
   gch->trace_heap_before_gc(_gc_tracer);
 
@@ -193,7 +193,7 @@ void GenMarkSweep::deallocate_stacks() {
 void GenMarkSweep::mark_sweep_phase1(int level,
                                   bool clear_all_softrefs) {
   // Recursively traverse all live objects and mark them
-  GCTraceTime tm("phase 1", PrintGC && Verbose, true, _gc_timer);
+  GCTraceTime tm("phase 1", PrintGC && Verbose, true, _gc_timer, _gc_tracer->gc_id());
   trace(" 1");
 
   GenCollectedHeap* gch = GenCollectedHeap::heap();
@@ -220,7 +220,7 @@ void GenMarkSweep::mark_sweep_phase1(int level,
     ref_processor()->setup_policy(clear_all_softrefs);
     const ReferenceProcessorStats& stats =
       ref_processor()->process_discovered_references(
-        &is_alive, &keep_alive, &follow_stack_closure, NULL, _gc_timer);
+        &is_alive, &keep_alive, &follow_stack_closure, NULL, _gc_timer, _gc_tracer->gc_id());
     gc_tracer()->report_gc_reference_stats(stats);
   }
 
@@ -262,7 +262,7 @@ void GenMarkSweep::mark_sweep_phase2() {
 
   GenCollectedHeap* gch = GenCollectedHeap::heap();
 
-  GCTraceTime tm("phase 2", PrintGC && Verbose, true, _gc_timer);
+  GCTraceTime tm("phase 2", PrintGC && Verbose, true, _gc_timer, _gc_tracer->gc_id());
   trace("2");
 
   gch->prepare_for_compaction();
@@ -279,7 +279,7 @@ void GenMarkSweep::mark_sweep_phase3(int level) {
   GenCollectedHeap* gch = GenCollectedHeap::heap();
 
   // Adjust the pointers to reflect the new locations
-  GCTraceTime tm("phase 3", PrintGC && Verbose, true, _gc_timer);
+  GCTraceTime tm("phase 3", PrintGC && Verbose, true, _gc_timer, _gc_tracer->gc_id());
   trace("3");
 
   // Need new claim bits for the pointer adjustment tracing.
@@ -327,7 +327,7 @@ void GenMarkSweep::mark_sweep_phase4() {
   // to use a higher index (saved from phase2) when verifying perm_gen.
   GenCollectedHeap* gch = GenCollectedHeap::heap();
 
-  GCTraceTime tm("phase 4", PrintGC && Verbose, true, _gc_timer);
+  GCTraceTime tm("phase 4", PrintGC && Verbose, true, _gc_timer, _gc_tracer->gc_id());
   trace("4");
 
   GenCompactClosure blk;
diff --git a/hotspot/src/share/vm/memory/iterator.cpp b/hotspot/src/share/vm/memory/iterator.cpp
index f69eb4ed75db4613ec153d4aee097ba8d8f71c83..6cd8e965922128dadd159624cf8a7a3382964c03 100644
--- a/hotspot/src/share/vm/memory/iterator.cpp
+++ b/hotspot/src/share/vm/memory/iterator.cpp
@@ -27,6 +27,7 @@
 #include "oops/oop.inline.hpp"
 
 void KlassToOopClosure::do_klass(Klass* k) {
+  assert(_oop_closure != NULL, "Not initialized?");
   k->oops_do(_oop_closure);
 }
 
diff --git a/hotspot/src/share/vm/memory/iterator.hpp b/hotspot/src/share/vm/memory/iterator.hpp
index 81a845e5056c4490ef17e3bbf9c98589a1961784..e91d42974b1e703337fbea81ec1edb032a6dd067 100644
--- a/hotspot/src/share/vm/memory/iterator.hpp
+++ b/hotspot/src/share/vm/memory/iterator.hpp
@@ -115,9 +115,19 @@ class CLDClosure : public Closure {
 };
 
 class KlassToOopClosure : public KlassClosure {
+  friend class MetadataAwareOopClosure;
+  friend class MetadataAwareOopsInGenClosure;
+
   OopClosure* _oop_closure;
- public:
-  KlassToOopClosure(OopClosure* oop_closure) : _oop_closure(oop_closure) {}
+
+  // Used when _oop_closure couldn't be set in an initialization list.
+  void initialize(OopClosure* oop_closure) {
+    assert(_oop_closure == NULL, "Should only be called once");
+    _oop_closure = oop_closure;
+  }
+
+public:
+  KlassToOopClosure(OopClosure* oop_closure = NULL) : _oop_closure(oop_closure) {}
   virtual void do_klass(Klass* k);
 };
 
@@ -135,6 +145,29 @@ class CLDToOopClosure : public CLDClosure {
   void do_cld(ClassLoaderData* cld);
 };
 
+// The base class for all concurrent marking closures,
+// that participates in class unloading.
+// It's used to proxy through the metadata to the oops defined in them.
+class MetadataAwareOopClosure: public ExtendedOopClosure {
+  KlassToOopClosure _klass_closure;
+
+ public:
+  MetadataAwareOopClosure() : ExtendedOopClosure() {
+    _klass_closure.initialize(this);
+  }
+  MetadataAwareOopClosure(ReferenceProcessor* rp) : ExtendedOopClosure(rp) {
+    _klass_closure.initialize(this);
+  }
+
+  virtual bool do_metadata()    { return do_metadata_nv(); }
+  inline  bool do_metadata_nv() { return true; }
+
+  virtual void do_klass(Klass* k);
+  void do_klass_nv(Klass* k);
+
+  virtual void do_class_loader_data(ClassLoaderData* cld);
+};
+
 // ObjectClosure is used for iterating through an object space
 
 class ObjectClosure : public Closure {
@@ -318,4 +351,16 @@ class SymbolClosure : public StackObj {
   }
 };
 
+
+// Helper defines for ExtendOopClosure
+
+#define if_do_metadata_checked(closure, nv_suffix)       \
+  /* Make sure the non-virtual and the virtual versions match. */     \
+  assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
+      "Inconsistency in do_metadata");                                \
+  if (closure->do_metadata##nv_suffix())
+
+#define assert_should_ignore_metadata(closure, nv_suffix)                                  \
+  assert(!closure->do_metadata##nv_suffix(), "Code to handle metadata is not implemented")
+
 #endif // SHARE_VM_MEMORY_ITERATOR_HPP
diff --git a/hotspot/src/share/vm/memory/iterator.inline.hpp b/hotspot/src/share/vm/memory/iterator.inline.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..cef1266601295213f221751a5ac6a6e915cb7942
--- /dev/null
+++ b/hotspot/src/share/vm/memory/iterator.inline.hpp
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2014, 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_MEMORY_ITERATOR_INLINE_HPP
+#define SHARE_VM_MEMORY_ITERATOR_INLINE_HPP
+
+#include "classfile/classLoaderData.hpp"
+#include "memory/iterator.hpp"
+#include "oops/klass.hpp"
+#include "utilities/debug.hpp"
+
+inline void MetadataAwareOopClosure::do_class_loader_data(ClassLoaderData* cld) {
+  assert(_klass_closure._oop_closure == this, "Must be");
+
+  bool claim = true;  // Must claim the class loader data before processing.
+  cld->oops_do(_klass_closure._oop_closure, &_klass_closure, claim);
+}
+
+inline void MetadataAwareOopClosure::do_klass_nv(Klass* k) {
+  ClassLoaderData* cld = k->class_loader_data();
+  do_class_loader_data(cld);
+}
+
+inline void MetadataAwareOopClosure::do_klass(Klass* k)       { do_klass_nv(k); }
+
+#endif // SHARE_VM_MEMORY_ITERATOR_INLINE_HPP
diff --git a/hotspot/src/share/vm/memory/referenceProcessor.cpp b/hotspot/src/share/vm/memory/referenceProcessor.cpp
index 2a074f21f1544b302bce6b101215e43047960c12..cb14dd8541b207b0346a24688e5f9d7b1041f622 100644
--- a/hotspot/src/share/vm/memory/referenceProcessor.cpp
+++ b/hotspot/src/share/vm/memory/referenceProcessor.cpp
@@ -190,7 +190,8 @@ ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
   OopClosure*                  keep_alive,
   VoidClosure*                 complete_gc,
   AbstractRefProcTaskExecutor* task_executor,
-  GCTimer*                     gc_timer) {
+  GCTimer*                     gc_timer,
+  GCId                         gc_id) {
   NOT_PRODUCT(verify_ok_to_handle_reflists());
 
   assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
@@ -212,7 +213,7 @@ ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
   // Soft references
   size_t soft_count = 0;
   {
-    GCTraceTime tt("SoftReference", trace_time, false, gc_timer);
+    GCTraceTime tt("SoftReference", trace_time, false, gc_timer, gc_id);
     soft_count =
       process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
                                  is_alive, keep_alive, complete_gc, task_executor);
@@ -223,7 +224,7 @@ ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
   // Weak references
   size_t weak_count = 0;
   {
-    GCTraceTime tt("WeakReference", trace_time, false, gc_timer);
+    GCTraceTime tt("WeakReference", trace_time, false, gc_timer, gc_id);
     weak_count =
       process_discovered_reflist(_discoveredWeakRefs, NULL, true,
                                  is_alive, keep_alive, complete_gc, task_executor);
@@ -232,7 +233,7 @@ ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
   // Final references
   size_t final_count = 0;
   {
-    GCTraceTime tt("FinalReference", trace_time, false, gc_timer);
+    GCTraceTime tt("FinalReference", trace_time, false, gc_timer, gc_id);
     final_count =
       process_discovered_reflist(_discoveredFinalRefs, NULL, false,
                                  is_alive, keep_alive, complete_gc, task_executor);
@@ -241,7 +242,7 @@ ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
   // Phantom references
   size_t phantom_count = 0;
   {
-    GCTraceTime tt("PhantomReference", trace_time, false, gc_timer);
+    GCTraceTime tt("PhantomReference", trace_time, false, gc_timer, gc_id);
     phantom_count =
       process_discovered_reflist(_discoveredPhantomRefs, NULL, false,
                                  is_alive, keep_alive, complete_gc, task_executor);
@@ -253,7 +254,7 @@ ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
   // thus use JNI weak references to circumvent the phantom references and
   // resurrect a "post-mortem" object.
   {
-    GCTraceTime tt("JNI Weak Reference", trace_time, false, gc_timer);
+    GCTraceTime tt("JNI Weak Reference", trace_time, false, gc_timer, gc_id);
     if (task_executor != NULL) {
       task_executor->set_single_threaded_mode();
     }
@@ -1251,14 +1252,15 @@ void ReferenceProcessor::preclean_discovered_references(
   OopClosure* keep_alive,
   VoidClosure* complete_gc,
   YieldClosure* yield,
-  GCTimer* gc_timer) {
+  GCTimer* gc_timer,
+  GCId     gc_id) {
 
   NOT_PRODUCT(verify_ok_to_handle_reflists());
 
   // Soft references
   {
     GCTraceTime tt("Preclean SoftReferences", PrintGCDetails && PrintReferenceGC,
-              false, gc_timer);
+              false, gc_timer, gc_id);
     for (uint i = 0; i < _max_num_q; i++) {
       if (yield->should_return()) {
         return;
@@ -1271,7 +1273,7 @@ void ReferenceProcessor::preclean_discovered_references(
   // Weak references
   {
     GCTraceTime tt("Preclean WeakReferences", PrintGCDetails && PrintReferenceGC,
-              false, gc_timer);
+              false, gc_timer, gc_id);
     for (uint i = 0; i < _max_num_q; i++) {
       if (yield->should_return()) {
         return;
@@ -1284,7 +1286,7 @@ void ReferenceProcessor::preclean_discovered_references(
   // Final references
   {
     GCTraceTime tt("Preclean FinalReferences", PrintGCDetails && PrintReferenceGC,
-              false, gc_timer);
+              false, gc_timer, gc_id);
     for (uint i = 0; i < _max_num_q; i++) {
       if (yield->should_return()) {
         return;
@@ -1297,7 +1299,7 @@ void ReferenceProcessor::preclean_discovered_references(
   // Phantom references
   {
     GCTraceTime tt("Preclean PhantomReferences", PrintGCDetails && PrintReferenceGC,
-              false, gc_timer);
+              false, gc_timer, gc_id);
     for (uint i = 0; i < _max_num_q; i++) {
       if (yield->should_return()) {
         return;
diff --git a/hotspot/src/share/vm/memory/referenceProcessor.hpp b/hotspot/src/share/vm/memory/referenceProcessor.hpp
index 26ac9f1c5d4e165e6152c745cf7919d69a90cb96..d4d2b89866e63d6dfcc95a783bc867482dc4b27d 100644
--- a/hotspot/src/share/vm/memory/referenceProcessor.hpp
+++ b/hotspot/src/share/vm/memory/referenceProcessor.hpp
@@ -25,6 +25,7 @@
 #ifndef SHARE_VM_MEMORY_REFERENCEPROCESSOR_HPP
 #define SHARE_VM_MEMORY_REFERENCEPROCESSOR_HPP
 
+#include "gc_implementation/shared/gcTrace.hpp"
 #include "memory/referencePolicy.hpp"
 #include "memory/referenceProcessorStats.hpp"
 #include "memory/referenceType.hpp"
@@ -349,7 +350,8 @@ class ReferenceProcessor : public CHeapObj<mtGC> {
                                       OopClosure*        keep_alive,
                                       VoidClosure*       complete_gc,
                                       YieldClosure*      yield,
-                                      GCTimer*           gc_timer);
+                                      GCTimer*           gc_timer,
+                                      GCId               gc_id);
 
   // Delete entries in the discovered lists that have
   // either a null referent or are not active. Such
@@ -480,7 +482,8 @@ class ReferenceProcessor : public CHeapObj<mtGC> {
                                 OopClosure*                  keep_alive,
                                 VoidClosure*                 complete_gc,
                                 AbstractRefProcTaskExecutor* task_executor,
-                                GCTimer *gc_timer);
+                                GCTimer *gc_timer,
+                                GCId    gc_id);
 
   // Enqueue references at end of GC (called by the garbage collector)
   bool enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor = NULL);
diff --git a/hotspot/src/share/vm/memory/space.cpp b/hotspot/src/share/vm/memory/space.cpp
index ae29692a62b7d90a7d2a022a2a8fb77653fb5229..396a743ac3b81511650562b3aa62e988aa7af0df 100644
--- a/hotspot/src/share/vm/memory/space.cpp
+++ b/hotspot/src/share/vm/memory/space.cpp
@@ -37,6 +37,7 @@
 #include "oops/oop.inline.hpp"
 #include "oops/oop.inline2.hpp"
 #include "runtime/java.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/prefetch.inline.hpp"
 #include "runtime/orderAccess.inline.hpp"
 #include "runtime/safepoint.hpp"
diff --git a/hotspot/src/share/vm/memory/specialized_oop_closures.hpp b/hotspot/src/share/vm/memory/specialized_oop_closures.hpp
index 24986b95089a75d6a108a0bd95051cf5dcd8854c..b4e2fa33a221d45eeee966301c3b0f513e3038ac 100644
--- a/hotspot/src/share/vm/memory/specialized_oop_closures.hpp
+++ b/hotspot/src/share/vm/memory/specialized_oop_closures.hpp
@@ -25,7 +25,6 @@
 #ifndef SHARE_VM_MEMORY_SPECIALIZED_OOP_CLOSURES_HPP
 #define SHARE_VM_MEMORY_SPECIALIZED_OOP_CLOSURES_HPP
 
-#include "runtime/atomic.hpp"
 #include "utilities/macros.hpp"
 #if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1_specialized_oop_closures.hpp"
diff --git a/hotspot/src/share/vm/memory/threadLocalAllocBuffer.inline.hpp b/hotspot/src/share/vm/memory/threadLocalAllocBuffer.inline.hpp
index cf3fefbfe3a5872998a9a538ad602c90686d54d8..60e645fa6ff7564a747a014cd3111c591fa7ef8f 100644
--- a/hotspot/src/share/vm/memory/threadLocalAllocBuffer.inline.hpp
+++ b/hotspot/src/share/vm/memory/threadLocalAllocBuffer.inline.hpp
@@ -27,7 +27,6 @@
 
 #include "gc_interface/collectedHeap.hpp"
 #include "memory/threadLocalAllocBuffer.hpp"
-#include "runtime/atomic.hpp"
 #include "runtime/thread.hpp"
 #include "utilities/copy.hpp"
 
diff --git a/hotspot/src/share/vm/memory/universe.cpp b/hotspot/src/share/vm/memory/universe.cpp
index 5053b46e8c8c9de3b1a44417abdd7ff76383d014..9d5a2a6cbae96d088ab156e6cb917cf7c69c06e3 100644
--- a/hotspot/src/share/vm/memory/universe.cpp
+++ b/hotspot/src/share/vm/memory/universe.cpp
@@ -53,6 +53,7 @@
 #include "oops/typeArrayKlass.hpp"
 #include "prims/jvmtiRedefineClassesTrace.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/deoptimization.hpp"
 #include "runtime/fprofiler.hpp"
 #include "runtime/handles.inline.hpp"
diff --git a/hotspot/src/share/vm/oops/arrayKlass.cpp b/hotspot/src/share/vm/oops/arrayKlass.cpp
index c55992f0749c2d7801ceaef98d58ef51df69179b..e8a367a376653815cd9c83d08a4109b0b2ae88ee 100644
--- a/hotspot/src/share/vm/oops/arrayKlass.cpp
+++ b/hotspot/src/share/vm/oops/arrayKlass.cpp
@@ -93,7 +93,7 @@ void ArrayKlass::complete_create_array_klass(ArrayKlass* k, KlassHandle super_kl
   ResourceMark rm(THREAD);
   k->initialize_supers(super_klass(), CHECK);
   k->vtable()->initialize_vtable(false, CHECK);
-  java_lang_Class::create_mirror(k, Handle(NULL), CHECK);
+  java_lang_Class::create_mirror(k, Handle(NULL), Handle(NULL), CHECK);
 }
 
 GrowableArray<Klass*>* ArrayKlass::compute_secondary_supers(int num_extra_slots) {
diff --git a/hotspot/src/share/vm/oops/compiledICHolder.cpp b/hotspot/src/share/vm/oops/compiledICHolder.cpp
index 722680792967c763457e272667df4364a33d377f..c17ca240a8579d8efb4de98bcab48830828365cd 100644
--- a/hotspot/src/share/vm/oops/compiledICHolder.cpp
+++ b/hotspot/src/share/vm/oops/compiledICHolder.cpp
@@ -27,11 +27,27 @@
 #include "oops/klass.hpp"
 #include "oops/method.hpp"
 #include "oops/oop.inline2.hpp"
+#include "runtime/atomic.inline.hpp"
 
 volatile int CompiledICHolder::_live_count;
 volatile int CompiledICHolder::_live_not_claimed_count;
 
 
+CompiledICHolder::CompiledICHolder(Method* method, Klass* klass)
+  : _holder_method(method), _holder_klass(klass) {
+#ifdef ASSERT
+  Atomic::inc(&_live_count);
+  Atomic::inc(&_live_not_claimed_count);
+#endif // ASSERT
+}
+
+#ifdef ASSERT
+CompiledICHolder::~CompiledICHolder() {
+  assert(_live_count > 0, "underflow");
+  Atomic::dec(&_live_count);
+}
+#endif // ASSERT
+
 // Printing
 
 void CompiledICHolder::print_on(outputStream* st) const {
@@ -51,3 +67,11 @@ void CompiledICHolder::verify_on(outputStream* st) {
   guarantee(holder_method()->is_method(), "should be method");
   guarantee(holder_klass()->is_klass(),   "should be klass");
 }
+
+#ifdef ASSERT
+
+void CompiledICHolder::claim() {
+  Atomic::dec(&_live_not_claimed_count);
+}
+
+#endif // ASSERT
diff --git a/hotspot/src/share/vm/oops/compiledICHolder.hpp b/hotspot/src/share/vm/oops/compiledICHolder.hpp
index d3ca41f6ba89afc89c456b5f3b584610157f535c..c3e899fde88d2b2ecf3b2c877414853e8cc5aad6 100644
--- a/hotspot/src/share/vm/oops/compiledICHolder.hpp
+++ b/hotspot/src/share/vm/oops/compiledICHolder.hpp
@@ -26,6 +26,7 @@
 #define SHARE_VM_OOPS_COMPILEDICHOLDEROOP_HPP
 
 #include "oops/oop.hpp"
+#include "utilities/macros.hpp"
 
 // A CompiledICHolder* is a helper object for the inline cache implementation.
 // It holds an intermediate value (method+klass pair) used when converting from
@@ -50,20 +51,8 @@ class CompiledICHolder : public CHeapObj<mtCompiler> {
 
  public:
   // Constructor
-  CompiledICHolder(Method* method, Klass* klass)
-      : _holder_method(method), _holder_klass(klass) {
-#ifdef ASSERT
-    Atomic::inc(&_live_count);
-    Atomic::inc(&_live_not_claimed_count);
-#endif
-  }
-
-  ~CompiledICHolder() {
-#ifdef ASSERT
-    assert(_live_count > 0, "underflow");
-    Atomic::dec(&_live_count);
-#endif
-  }
+  CompiledICHolder(Method* method, Klass* klass);
+  ~CompiledICHolder() NOT_DEBUG_RETURN;
 
   static int live_count() { return _live_count; }
   static int live_not_claimed_count() { return _live_not_claimed_count; }
@@ -91,11 +80,7 @@ class CompiledICHolder : public CHeapObj<mtCompiler> {
 
   const char* internal_name() const { return "{compiledICHolder}"; }
 
-  void claim() {
-#ifdef ASSERT
-    Atomic::dec(&_live_not_claimed_count);
-#endif
-  }
+  void claim() NOT_DEBUG_RETURN;
 };
 
 #endif // SHARE_VM_OOPS_COMPILEDICHOLDEROOP_HPP
diff --git a/hotspot/src/share/vm/oops/constantPool.cpp b/hotspot/src/share/vm/oops/constantPool.cpp
index b45fe508a6446e41955e2cf7b22acc7f5892cc8c..111d55b3af7ecdc43f79d0d8c3b8dfefde8a83ac 100644
--- a/hotspot/src/share/vm/oops/constantPool.cpp
+++ b/hotspot/src/share/vm/oops/constantPool.cpp
@@ -71,7 +71,6 @@ ConstantPool::ConstantPool(Array<u1>* tags) {
 
   // only set to non-zero if constant pool is merged by RedefineClasses
   set_version(0);
-  set_lock(new Monitor(Monitor::nonleaf + 2, "A constant pool lock"));
 
   // initialize tag array
   int length = tags->length();
@@ -100,9 +99,6 @@ void ConstantPool::deallocate_contents(ClassLoaderData* loader_data) {
 void ConstantPool::release_C_heap_structures() {
   // walk constant pool and decrement symbol reference counts
   unreference_symbols();
-
-  delete _lock;
-  set_lock(NULL);
 }
 
 objArrayOop ConstantPool::resolved_references() const {
@@ -146,8 +142,7 @@ void ConstantPool::initialize_resolved_references(ClassLoaderData* loader_data,
 // CDS support. Create a new resolved_references array.
 void ConstantPool::restore_unshareable_info(TRAPS) {
 
-  // Only create the new resolved references array and lock if it hasn't been
-  // attempted before
+  // Only create the new resolved references array if it hasn't been attempted before
   if (resolved_references() != NULL) return;
 
   // restore the C++ vtable from the shared archive
@@ -163,9 +158,6 @@ void ConstantPool::restore_unshareable_info(TRAPS) {
       ClassLoaderData* loader_data = pool_holder()->class_loader_data();
       set_resolved_references(loader_data->add_handle(refs_handle));
     }
-
-    // Also need to recreate the mutex.  Make sure this matches the constructor
-    set_lock(new Monitor(Monitor::nonleaf + 2, "A constant pool lock"));
   }
 }
 
@@ -176,7 +168,6 @@ void ConstantPool::remove_unshareable_info() {
   set_resolved_reference_length(
     resolved_references() != NULL ? resolved_references()->length() : 0);
   set_resolved_references(NULL);
-  set_lock(NULL);
 }
 
 int ConstantPool::cp_to_object_index(int cp_index) {
@@ -186,11 +177,41 @@ int ConstantPool::cp_to_object_index(int cp_index) {
   return (i < 0) ? _no_index_sentinel : i;
 }
 
+void ConstantPool::trace_class_resolution(constantPoolHandle this_cp, KlassHandle k) {
+  ResourceMark rm;
+  int line_number = -1;
+  const char * source_file = NULL;
+  if (JavaThread::current()->has_last_Java_frame()) {
+    // try to identify the method which called this function.
+    vframeStream vfst(JavaThread::current());
+    if (!vfst.at_end()) {
+      line_number = vfst.method()->line_number_from_bci(vfst.bci());
+      Symbol* s = vfst.method()->method_holder()->source_file_name();
+      if (s != NULL) {
+        source_file = s->as_C_string();
+      }
+    }
+  }
+  if (k() != this_cp->pool_holder()) {
+    // only print something if the classes are different
+    if (source_file != NULL) {
+      tty->print("RESOLVE %s %s %s:%d\n",
+                 this_cp->pool_holder()->external_name(),
+                 InstanceKlass::cast(k())->external_name(), source_file, line_number);
+    } else {
+      tty->print("RESOLVE %s %s\n",
+                 this_cp->pool_holder()->external_name(),
+                 InstanceKlass::cast(k())->external_name());
+    }
+  }
+}
+
 Klass* ConstantPool::klass_at_impl(constantPoolHandle this_cp, int which, TRAPS) {
-  // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
-  // It is not safe to rely on the tag bit's here, since we don't have a lock, and the entry and
-  // tag is not updated atomicly.
+  assert(THREAD->is_Java_thread(), "must be a Java thread");
 
+  // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
+  // It is not safe to rely on the tag bit's here, since we don't have a lock, and
+  // the entry and tag is not updated atomicly.
   CPSlot entry = this_cp->slot_at(which);
   if (entry.is_resolved()) {
     assert(entry.get_klass()->is_klass(), "must be");
@@ -198,115 +219,51 @@ Klass* ConstantPool::klass_at_impl(constantPoolHandle this_cp, int which, TRAPS)
     return entry.get_klass();
   }
 
-  // Acquire lock on constant oop while doing update. After we get the lock, we check if another object
-  // already has updated the object
-  assert(THREAD->is_Java_thread(), "must be a Java thread");
-  bool do_resolve = false;
-  bool in_error = false;
-
-  // Create a handle for the mirror. This will preserve the resolved class
-  // until the loader_data is registered.
-  Handle mirror_handle;
-
-  Symbol* name = NULL;
-  Handle       loader;
-  {  MonitorLockerEx ml(this_cp->lock());
-
-    if (this_cp->tag_at(which).is_unresolved_klass()) {
-      if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {
-        in_error = true;
-      } else {
-        do_resolve = true;
-        name   = this_cp->unresolved_klass_at(which);
-        loader = Handle(THREAD, this_cp->pool_holder()->class_loader());
-      }
-    }
-  } // unlocking constantPool
-
-
-  // The original attempt to resolve this constant pool entry failed so find the
-  // class of the original error and throw another error of the same class (JVMS 5.4.3).
-  // If there is a detail message, pass that detail message to the error constructor.
-  // The JVMS does not strictly require us to duplicate the same detail message,
-  // or any internal exception fields such as cause or stacktrace.  But since the
-  // detail message is often a class name or other literal string, we will repeat it if
-  // we can find it in the symbol table.
-  if (in_error) {
+  // This tag doesn't change back to unresolved class unless at a safepoint.
+  if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {
+    // The original attempt to resolve this constant pool entry failed so find the
+    // class of the original error and throw another error of the same class
+    // (JVMS 5.4.3).
+    // If there is a detail message, pass that detail message to the error.
+    // The JVMS does not strictly require us to duplicate the same detail message,
+    // or any internal exception fields such as cause or stacktrace.  But since the
+    // detail message is often a class name or other literal string, we will repeat it
+    // if we can find it in the symbol table.
     throw_resolution_error(this_cp, which, CHECK_0);
+    ShouldNotReachHere();
   }
 
-  if (do_resolve) {
-    // this_cp must be unlocked during resolve_or_fail
-    oop protection_domain = this_cp->pool_holder()->protection_domain();
-    Handle h_prot (THREAD, protection_domain);
-    Klass* kk = SystemDictionary::resolve_or_fail(name, loader, h_prot, true, THREAD);
-    KlassHandle k;
-    if (!HAS_PENDING_EXCEPTION) {
-      k = KlassHandle(THREAD, kk);
-      // preserve the resolved klass.
-      mirror_handle = Handle(THREAD, kk->java_mirror());
-      // Do access check for klasses
-      verify_constant_pool_resolve(this_cp, k, THREAD);
-    }
-
-    // Failed to resolve class. We must record the errors so that subsequent attempts
-    // to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
-    if (HAS_PENDING_EXCEPTION) {
-        MonitorLockerEx ml(this_cp->lock());
+  Handle mirror_handle;
+  Symbol* name = entry.get_symbol();
+  Handle loader (THREAD, this_cp->pool_holder()->class_loader());
+  Handle protection_domain (THREAD, this_cp->pool_holder()->protection_domain());
+  Klass* kk = SystemDictionary::resolve_or_fail(name, loader, protection_domain, true, THREAD);
+  KlassHandle k (THREAD, kk);
+  if (!HAS_PENDING_EXCEPTION) {
+    // preserve the resolved klass from unloading
+    mirror_handle = Handle(THREAD, kk->java_mirror());
+    // Do access check for klasses
+    verify_constant_pool_resolve(this_cp, k, THREAD);
+  }
 
-        // some other thread has beaten us and has resolved the class.
-        if (this_cp->tag_at(which).is_klass()) {
-          CLEAR_PENDING_EXCEPTION;
-          entry = this_cp->resolved_klass_at(which);
-          return entry.get_klass();
-        }
+  // Failed to resolve class. We must record the errors so that subsequent attempts
+  // to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
+  if (HAS_PENDING_EXCEPTION) {
+    save_and_throw_exception(this_cp, which, constantTag(JVM_CONSTANT_UnresolvedClass), CHECK_0);
+  }
 
-        // The tag could have changed to in-error before the lock but we have to
-        // handle that here for the class case.
-        save_and_throw_exception(this_cp, which, constantTag(JVM_CONSTANT_UnresolvedClass), CHECK_0);
-    }
+  // Make this class loader depend upon the class loader owning the class reference
+  ClassLoaderData* this_key = this_cp->pool_holder()->class_loader_data();
+  this_key->record_dependency(k(), CHECK_NULL); // Can throw OOM
 
-    if (TraceClassResolution && !k()->oop_is_array()) {
-      // skip resolving the constant pool so that this code get's
-      // called the next time some bytecodes refer to this class.
-      ResourceMark rm;
-      int line_number = -1;
-      const char * source_file = NULL;
-      if (JavaThread::current()->has_last_Java_frame()) {
-        // try to identify the method which called this function.
-        vframeStream vfst(JavaThread::current());
-        if (!vfst.at_end()) {
-          line_number = vfst.method()->line_number_from_bci(vfst.bci());
-          Symbol* s = vfst.method()->method_holder()->source_file_name();
-          if (s != NULL) {
-            source_file = s->as_C_string();
-          }
-        }
-      }
-      if (k() != this_cp->pool_holder()) {
-        // only print something if the classes are different
-        if (source_file != NULL) {
-          tty->print("RESOLVE %s %s %s:%d\n",
-                     this_cp->pool_holder()->external_name(),
-                     InstanceKlass::cast(k())->external_name(), source_file, line_number);
-        } else {
-          tty->print("RESOLVE %s %s\n",
-                     this_cp->pool_holder()->external_name(),
-                     InstanceKlass::cast(k())->external_name());
-        }
-      }
+  if (TraceClassResolution && !k->oop_is_array()) {
+    // skip resolving the constant pool so that this code gets
+    // called the next time some bytecodes refer to this class.
+    trace_class_resolution(this_cp, k);
       return k();
     } else {
-      MonitorLockerEx ml(this_cp->lock());
-      // Only updated constant pool - if it is resolved.
-      do_resolve = this_cp->tag_at(which).is_unresolved_klass();
-      if (do_resolve) {
-        ClassLoaderData* this_key = this_cp->pool_holder()->class_loader_data();
-        this_key->record_dependency(k(), CHECK_NULL); // Can throw OOM
         this_cp->klass_at_put(which, k());
       }
-    }
-  }
 
   entry = this_cp->resolved_klass_at(which);
   assert(entry.is_resolved() && entry.get_klass()->is_klass(), "must be resolved at this point");
@@ -576,7 +533,7 @@ Symbol* ConstantPool::exception_message(constantPoolHandle this_cp, int which, c
   switch (tag.value()) {
   case JVM_CONSTANT_UnresolvedClass:
     // return the class name in the error message
-    message = this_cp->unresolved_klass_at(which);
+    message = this_cp->klass_name_at(which);
     break;
   case JVM_CONSTANT_MethodHandle:
     // return the method handle name in the error message
@@ -606,7 +563,6 @@ void ConstantPool::throw_resolution_error(constantPoolHandle this_cp, int which,
 // in the resolution error table, so that the same exception is thrown again.
 void ConstantPool::save_and_throw_exception(constantPoolHandle this_cp, int which,
                                             constantTag tag, TRAPS) {
-  assert(this_cp->lock()->is_locked(), "constant pool lock should be held");
   Symbol* error = PENDING_EXCEPTION->klass()->name();
 
   int error_tag = tag.error_value();
@@ -620,7 +576,14 @@ void ConstantPool::save_and_throw_exception(constantPoolHandle this_cp, int whic
   } else if (this_cp->tag_at(which).value() != error_tag) {
     Symbol* message = exception_message(this_cp, which, tag, PENDING_EXCEPTION);
     SystemDictionary::add_resolution_error(this_cp, which, error, message);
-    this_cp->tag_at_put(which, error_tag);
+    // CAS in the tag.  If a thread beat us to registering this error that's fine.
+    // If another thread resolved the reference, this is an error.  The resolution
+    // must deterministically get an error.   So why do we save this?
+    // We save this because jvmti can add classes to the bootclass path after this
+    // error, so it needs to get the same error if the error is first.
+    jbyte old_tag = Atomic::cmpxchg((jbyte)error_tag,
+                            (jbyte*)this_cp->tag_addr_at(which), (jbyte)tag.value());
+    assert(old_tag == error_tag || old_tag == tag.value(), "should not be resolved otherwise");
   } else {
     // some other thread put this in error state
     throw_resolution_error(this_cp, which, CHECK);
@@ -710,7 +673,6 @@ oop ConstantPool::resolve_constant_at_impl(constantPoolHandle this_cp, int index
                                                                    THREAD);
       result_oop = value();
       if (HAS_PENDING_EXCEPTION) {
-        MonitorLockerEx ml(this_cp->lock());  // lock cpool to change tag.
         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
       }
       break;
@@ -727,7 +689,6 @@ oop ConstantPool::resolve_constant_at_impl(constantPoolHandle this_cp, int index
       Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
       result_oop = value();
       if (HAS_PENDING_EXCEPTION) {
-        MonitorLockerEx ml(this_cp->lock());  // lock cpool to change tag.
         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
       }
       break;
@@ -765,22 +726,17 @@ oop ConstantPool::resolve_constant_at_impl(constantPoolHandle this_cp, int index
   }
 
   if (cache_index >= 0) {
-    // Cache the oop here also.
-    Handle result_handle(THREAD, result_oop);
-    MonitorLockerEx ml(this_cp->lock());  // don't know if we really need this
-    oop result = this_cp->resolved_references()->obj_at(cache_index);
-    // Benign race condition:  resolved_references may already be filled in while we were trying to lock.
+    // Benign race condition:  resolved_references may already be filled in.
     // The important thing here is that all threads pick up the same result.
     // It doesn't matter which racing thread wins, as long as only one
     // result is used by all threads, and all future queries.
-    // That result may be either a resolved constant or a failure exception.
-    if (result == NULL) {
-      this_cp->resolved_references()->obj_at_put(cache_index, result_handle());
-      return result_handle();
+    oop old_result = this_cp->resolved_references()->atomic_compare_exchange_oop(cache_index, result_oop, NULL);
+    if (old_result == NULL) {
+      return result_oop;  // was installed
     } else {
       // Return the winning thread's result.  This can be different than
-      // result_handle() for MethodHandles.
-      return result;
+      // the result here for MethodHandles.
+      return old_result;
     }
   } else {
     return result_oop;
@@ -853,9 +809,8 @@ bool ConstantPool::klass_name_at_matches(instanceKlassHandle k,
 }
 
 
-// Iterate over symbols and decrement ones which are Symbol*s.
-// This is done during GC so do not need to lock constantPool unless we
-// have per-thread safepoints.
+// Iterate over symbols and decrement ones which are Symbol*s
+// This is done during GC.
 // Only decrement the UTF8 symbols. Unresolved classes and strings point to
 // these symbols but didn't increment the reference count.
 void ConstantPool::unreference_symbols() {
@@ -987,8 +942,8 @@ bool ConstantPool::compare_entry_to(int index1, constantPoolHandle cp2,
 
   case JVM_CONSTANT_UnresolvedClass:
   {
-    Symbol* k1 = unresolved_klass_at(index1);
-    Symbol* k2 = cp2->unresolved_klass_at(index2);
+    Symbol* k1 = klass_name_at(index1);
+    Symbol* k2 = cp2->klass_name_at(index2);
     if (k1 == k2) {
       return true;
     }
@@ -1970,7 +1925,6 @@ void ConstantPool::print_entry_on(const int index, outputStream* st) {
       break;
     case JVM_CONSTANT_UnresolvedClass :               // fall-through
     case JVM_CONSTANT_UnresolvedClassInError: {
-      // unresolved_klass_at requires lock or safe world.
       CPSlot entry = slot_at(index);
       if (entry.is_resolved()) {
         entry.get_klass()->print_value_on(st);
diff --git a/hotspot/src/share/vm/oops/constantPool.hpp b/hotspot/src/share/vm/oops/constantPool.hpp
index 99c766ab7c557ba0556c85dad011828c5be0a229..5c5ea1c76e237d65bc8c90b3f08a686ebac49932 100644
--- a/hotspot/src/share/vm/oops/constantPool.hpp
+++ b/hotspot/src/share/vm/oops/constantPool.hpp
@@ -112,12 +112,12 @@ class ConstantPool : public Metadata {
     int                _version;
   } _saved;
 
-  Monitor*             _lock;
-
   void set_tags(Array<u1>* tags)               { _tags = tags; }
   void tag_at_put(int which, jbyte t)          { tags()->at_put(which, t); }
   void release_tag_at_put(int which, jbyte t)  { tags()->release_at_put(which, t); }
 
+  u1* tag_addr_at(int which) const             { return tags()->adr_at(which); }
+
   void set_operands(Array<u2>* operands)       { _operands = operands; }
 
   int flags() const                            { return _flags; }
@@ -362,14 +362,6 @@ class ConstantPool : public Metadata {
     return CPSlot((Klass*)OrderAccess::load_ptr_acquire(obj_at_addr_raw(which))).get_klass();
   }
 
-  // This method should only be used with a cpool lock or during parsing or gc
-  Symbol* unresolved_klass_at(int which) {     // Temporary until actual use
-    Symbol* s = CPSlot((Symbol*)OrderAccess::load_ptr_acquire(obj_at_addr_raw(which))).get_symbol();
-    // check that the klass is still unresolved.
-    assert(tag_at(which).is_unresolved_klass(), "Corrupted constant pool");
-    return s;
-  }
-
   // RedefineClasses() API support:
   Symbol* klass_at_noresolve(int which) { return klass_name_at(which); }
 
@@ -818,6 +810,8 @@ class ConstantPool : public Metadata {
   static Klass* klass_at_impl(constantPoolHandle this_cp, int which, TRAPS);
   static oop string_at_impl(constantPoolHandle this_cp, int which, int obj_index, TRAPS);
 
+  static void trace_class_resolution(constantPoolHandle this_cp, KlassHandle k);
+
   // Resolve string constants (to prevent allocation during compilation)
   static void resolve_string_constants_impl(constantPoolHandle this_cp, TRAPS);
 
@@ -848,8 +842,6 @@ class ConstantPool : public Metadata {
 
   void set_resolved_reference_length(int length) { _saved._resolved_reference_length = length; }
   int  resolved_reference_length() const  { return _saved._resolved_reference_length; }
-  void set_lock(Monitor* lock)            { _lock = lock; }
-  Monitor* lock()                         { return _lock; }
 
   // Decrease ref counts of symbols that are in the constant pool
   // when the holder class is unloaded
diff --git a/hotspot/src/share/vm/oops/cpCache.cpp b/hotspot/src/share/vm/oops/cpCache.cpp
index d601367ba9963068ed8ae241359b175dffa4ca6b..64f16f78467b7258775911be777b5cffc6ca9033 100644
--- a/hotspot/src/share/vm/oops/cpCache.cpp
+++ b/hotspot/src/share/vm/oops/cpCache.cpp
@@ -32,6 +32,7 @@
 #include "oops/oop.inline.hpp"
 #include "prims/jvmtiRedefineClassesTrace.hpp"
 #include "prims/methodHandles.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/orderAccess.inline.hpp"
 #include "utilities/macros.hpp"
@@ -286,7 +287,9 @@ void ConstantPoolCacheEntry::set_method_handle_common(constantPoolHandle cpool,
   // the lock, so that when the losing writer returns, he can use the linked
   // cache entry.
 
-  MonitorLockerEx ml(cpool->lock());
+  // Use the lock from the metaspace for this, which cannot stop for safepoint.
+  Mutex* metaspace_lock = cpool->pool_holder()->class_loader_data()->metaspace_lock();
+  MutexLockerEx ml(metaspace_lock,  Mutex::_no_safepoint_check_flag);
   if (!is_f1_null()) {
     return;
   }
diff --git a/hotspot/src/share/vm/oops/instanceClassLoaderKlass.cpp b/hotspot/src/share/vm/oops/instanceClassLoaderKlass.cpp
index a92167a9a7db06aa1f45fbb0e25f46e4bbc7dec6..131ecbfb040af2923b1d75b63b6aced5e4d202c7 100644
--- a/hotspot/src/share/vm/oops/instanceClassLoaderKlass.cpp
+++ b/hotspot/src/share/vm/oops/instanceClassLoaderKlass.cpp
@@ -28,6 +28,7 @@
 #include "gc_implementation/shared/markSweep.inline.hpp"
 #include "gc_interface/collectedHeap.inline.hpp"
 #include "memory/genOopClosures.inline.hpp"
+#include "memory/iterator.inline.hpp"
 #include "memory/oopFactory.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/instanceClassLoaderKlass.hpp"
@@ -44,12 +45,6 @@
 #include "oops/oop.pcgc.inline.hpp"
 #endif // INCLUDE_ALL_GCS
 
-#define if_do_metadata_checked(closure, nv_suffix)                    \
-  /* Make sure the non-virtual and the virtual versions match. */     \
-  assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
-      "Inconsistency in do_metadata");                                \
-  if (closure->do_metadata##nv_suffix())
-
 // Macro to define InstanceClassLoaderKlass::oop_oop_iterate for virtual/nonvirtual for
 // all closures.  Macros calling macros above for each oop size.
 // Since ClassLoader objects have only a pointer to the loader_data, they are not
diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp
index bcf9dc0a097b4c1398a1d7d54935d0643dff76f0..91d00f8fdeac682bf2bc6e84bff8f9926a4d9efb 100644
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp
@@ -35,6 +35,7 @@
 #include "jvmtifiles/jvmti.h"
 #include "memory/genOopClosures.inline.hpp"
 #include "memory/heapInspection.hpp"
+#include "memory/iterator.inline.hpp"
 #include "memory/metadataFactory.hpp"
 #include "memory/oopFactory.hpp"
 #include "oops/fieldStreams.hpp"
@@ -51,6 +52,7 @@
 #include "prims/jvmtiRedefineClasses.hpp"
 #include "prims/jvmtiThreadState.hpp"
 #include "prims/methodComparator.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/fieldDescriptor.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/javaCalls.hpp"
@@ -2113,12 +2115,6 @@ void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
 // closure's do_metadata() method dictates whether the given closure should be
 // applied to the klass ptr in the object header.
 
-#define if_do_metadata_checked(closure, nv_suffix)                    \
-  /* Make sure the non-virtual and the virtual versions match. */     \
-  assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
-      "Inconsistency in do_metadata");                                \
-  if (closure->do_metadata##nv_suffix())
-
 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
                                                                              \
 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
@@ -2142,10 +2138,9 @@ int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure)
 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
                                               OopClosureType* closure) {        \
   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
-  /* header */                                                                  \
-  if_do_metadata_checked(closure, nv_suffix) {                                  \
-    closure->do_klass##nv_suffix(obj->klass());                                 \
-  }                                                                             \
+                                                                                \
+  assert_should_ignore_metadata(closure, nv_suffix);                            \
+                                                                                \
   /* instance variables */                                                      \
   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
     obj,                                                                        \
diff --git a/hotspot/src/share/vm/oops/instanceKlass.hpp b/hotspot/src/share/vm/oops/instanceKlass.hpp
index 57b0687029038085cd4d0991d63cea84ce71df46..d6c919e94624f6b965065955ca2412f3a4e95f24 100644
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp
@@ -32,7 +32,6 @@
 #include "oops/fieldInfo.hpp"
 #include "oops/instanceOop.hpp"
 #include "oops/klassVtable.hpp"
-#include "runtime/atomic.hpp"
 #include "runtime/handles.hpp"
 #include "runtime/os.hpp"
 #include "utilities/accessFlags.hpp"
diff --git a/hotspot/src/share/vm/oops/instanceMirrorKlass.cpp b/hotspot/src/share/vm/oops/instanceMirrorKlass.cpp
index fd05124f855ecc7c56a980827117c07fefc99d06..2fd8e48397cd81610d3dbb61316d6b0eedc0993d 100644
--- a/hotspot/src/share/vm/oops/instanceMirrorKlass.cpp
+++ b/hotspot/src/share/vm/oops/instanceMirrorKlass.cpp
@@ -28,6 +28,7 @@
 #include "gc_implementation/shared/markSweep.inline.hpp"
 #include "gc_interface/collectedHeap.inline.hpp"
 #include "memory/genOopClosures.inline.hpp"
+#include "memory/iterator.inline.hpp"
 #include "memory/oopFactory.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/instanceMirrorKlass.hpp"
@@ -241,12 +242,6 @@ int InstanceMirrorKlass::oop_adjust_pointers(oop obj) {
   return oop_size(obj);                                                               \
 
 
-#define if_do_metadata_checked(closure, nv_suffix)                    \
-  /* Make sure the non-virtual and the virtual versions match. */     \
-  assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
-      "Inconsistency in do_metadata");                                \
-  if (closure->do_metadata##nv_suffix())
-
 // Macro to define InstanceMirrorKlass::oop_oop_iterate for virtual/nonvirtual for
 // all closures.  Macros calling macros above for each oop size.
 
diff --git a/hotspot/src/share/vm/oops/klass.cpp b/hotspot/src/share/vm/oops/klass.cpp
index d81dceb8f376bf88810cbd2519bb2cbfc4d0f98d..77e2561258fddc18ace2435e26af16b4a71dd8ea 100644
--- a/hotspot/src/share/vm/oops/klass.cpp
+++ b/hotspot/src/share/vm/oops/klass.cpp
@@ -508,7 +508,7 @@ void Klass::restore_unshareable_info(TRAPS) {
   // Only recreate it if not present.  A previous attempt to restore may have
   // gotten an OOM later but keep the mirror if it was created.
   if (java_mirror() == NULL) {
-    java_lang_Class::create_mirror(this, Handle(NULL), CHECK);
+    java_lang_Class::create_mirror(this, Handle(NULL), Handle(NULL), CHECK);
   }
 }
 
diff --git a/hotspot/src/share/vm/oops/objArrayKlass.cpp b/hotspot/src/share/vm/oops/objArrayKlass.cpp
index 40b6d1b7ca85685ae5b737b04babb570b86614b1..0d17ce64dfd51d920944313dff79c3734e63bb7b 100644
--- a/hotspot/src/share/vm/oops/objArrayKlass.cpp
+++ b/hotspot/src/share/vm/oops/objArrayKlass.cpp
@@ -29,6 +29,7 @@
 #include "gc_implementation/shared/markSweep.inline.hpp"
 #include "gc_interface/collectedHeap.inline.hpp"
 #include "memory/genOopClosures.inline.hpp"
+#include "memory/iterator.inline.hpp"
 #include "memory/metadataFactory.hpp"
 #include "memory/resourceArea.hpp"
 #include "memory/universe.inline.hpp"
@@ -476,12 +477,6 @@ void ObjArrayKlass::oop_follow_contents(ParCompactionManager* cm,
 }
 #endif // INCLUDE_ALL_GCS
 
-#define if_do_metadata_checked(closure, nv_suffix)                    \
-  /* Make sure the non-virtual and the virtual versions match. */     \
-  assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
-      "Inconsistency in do_metadata");                                \
-  if (closure->do_metadata##nv_suffix())
-
 #define ObjArrayKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)           \
                                                                                 \
 int ObjArrayKlass::oop_oop_iterate##nv_suffix(oop obj,                          \
diff --git a/hotspot/src/share/vm/oops/objArrayOop.cpp b/hotspot/src/share/vm/oops/objArrayOop.cpp
index 00c4abe5ec3d684af285af0e42e79aba31178052..2d91b46a6801e3a4239bb909ef96f353f6f26914 100644
--- a/hotspot/src/share/vm/oops/objArrayOop.cpp
+++ b/hotspot/src/share/vm/oops/objArrayOop.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -27,6 +27,22 @@
 #include "oops/objArrayOop.hpp"
 #include "oops/oop.inline.hpp"
 
+oop objArrayOopDesc::atomic_compare_exchange_oop(int index, oop exchange_value,
+                                                 oop compare_value) {
+  volatile HeapWord* dest;
+  if (UseCompressedOops) {
+    dest = (HeapWord*)obj_at_addr<narrowOop>(index);
+  } else {
+    dest = (HeapWord*)obj_at_addr<oop>(index);
+  }
+  oop res = oopDesc::atomic_compare_exchange_oop(exchange_value, dest, compare_value, true);
+  // update card mark if success
+  if (res == compare_value) {
+    update_barrier_set((void*)dest, exchange_value);
+  }
+  return res;
+}
+
 #define ObjArrayOop_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)                    \
                                                                                    \
 int objArrayOopDesc::oop_iterate_range(OopClosureType* blk, int start, int end) {  \
diff --git a/hotspot/src/share/vm/oops/objArrayOop.hpp b/hotspot/src/share/vm/oops/objArrayOop.hpp
index 0cf5d0395e05279e25845d0e41380651cc75fab3..897452a66247131ddcde5e8d15f8ce7c4b2b3a79 100644
--- a/hotspot/src/share/vm/oops/objArrayOop.hpp
+++ b/hotspot/src/share/vm/oops/objArrayOop.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -95,6 +95,9 @@ private:
       oop_store(obj_at_addr<oop>(index), value);
     }
   }
+
+  oop atomic_compare_exchange_oop(int index, oop exchange_value, oop compare_value);
+
   // Sizing
   static int header_size()    { return arrayOopDesc::header_size(T_OBJECT); }
   int object_size()           { return object_size(length()); }
diff --git a/hotspot/src/share/vm/oops/oop.pcgc.inline.hpp b/hotspot/src/share/vm/oops/oop.pcgc.inline.hpp
index 596bbc6d1233020d58e75869225b0d8213b0a590..5a8d4d0afafa61ad0aa38d8165368d3c209c7ab7 100644
--- a/hotspot/src/share/vm/oops/oop.pcgc.inline.hpp
+++ b/hotspot/src/share/vm/oops/oop.pcgc.inline.hpp
@@ -26,6 +26,7 @@
 #define SHARE_VM_OOPS_OOP_PCGC_INLINE_HPP
 
 #include "utilities/macros.hpp"
+#include "runtime/atomic.inline.hpp"
 #if INCLUDE_ALL_GCS
 #include "gc_implementation/parNew/parNewGeneration.hpp"
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
diff --git a/hotspot/src/share/vm/oops/symbol.cpp b/hotspot/src/share/vm/oops/symbol.cpp
index cab865503fa71584b5c739c9ebf7103752cf8aa5..d3d1f13b63fa33af989018cf5c91d9c1fe76ad25 100644
--- a/hotspot/src/share/vm/oops/symbol.cpp
+++ b/hotspot/src/share/vm/oops/symbol.cpp
@@ -26,11 +26,11 @@
 #include "precompiled.hpp"
 #include "classfile/altHashing.hpp"
 #include "classfile/classLoaderData.hpp"
+#include "memory/allocation.inline.hpp"
+#include "memory/resourceArea.hpp"
 #include "oops/symbol.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
-#include "memory/allocation.inline.hpp"
-#include "memory/resourceArea.hpp"
 
 Symbol::Symbol(const u1* name, int length, int refcount) {
   _refcount = refcount;
diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp
index 0036e76518e4b77d8bc20e8b60603115c49a2f44..9c8ae35a04e486e5ba70874ceff26ac408e486ac 100644
--- a/hotspot/src/share/vm/opto/compile.cpp
+++ b/hotspot/src/share/vm/opto/compile.cpp
@@ -3411,7 +3411,7 @@ void Compile::verify_graph_edges(bool no_dead_code) {
     _root->verify_edges(visited);
     if (no_dead_code) {
       // Now make sure that no visited node is used by an unvisited node.
-      bool dead_nodes = 0;
+      bool dead_nodes = false;
       Unique_Node_List checked(area);
       while (visited.size() > 0) {
         Node* n = visited.pop();
@@ -3422,14 +3422,16 @@ void Compile::verify_graph_edges(bool no_dead_code) {
           if (visited.member(use))  continue;  // already in the graph
           if (use->is_Con())        continue;  // a dead ConNode is OK
           // At this point, we have found a dead node which is DU-reachable.
-          if (dead_nodes++ == 0)
+          if (!dead_nodes) {
             tty->print_cr("*** Dead nodes reachable via DU edges:");
+            dead_nodes = true;
+          }
           use->dump(2);
           tty->print_cr("---");
           checked.push(use);  // No repeats; pretend it is now checked.
         }
       }
-      assert(dead_nodes == 0, "using nodes must be reachable from root");
+      assert(!dead_nodes, "using nodes must be reachable from root");
     }
   }
 }
diff --git a/hotspot/src/share/vm/opto/matcher.cpp b/hotspot/src/share/vm/opto/matcher.cpp
index 2b2f11f9b4eac2c60af833f15faefbf569246b8c..a8321b07753a20bc31db3408730a7b37d4a2131c 100644
--- a/hotspot/src/share/vm/opto/matcher.cpp
+++ b/hotspot/src/share/vm/opto/matcher.cpp
@@ -36,7 +36,6 @@
 #include "opto/runtime.hpp"
 #include "opto/type.hpp"
 #include "opto/vectornode.hpp"
-#include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #ifdef TARGET_ARCH_MODEL_x86_32
 # include "adfiles/ad_x86_32.hpp"
diff --git a/hotspot/src/share/vm/opto/runtime.cpp b/hotspot/src/share/vm/opto/runtime.cpp
index 632a03f2304bd069a1a8f6bc51e1bfdfcc6d64d1..dba4f047b5a86ad5a73ee34b89042fe6c60d42a6 100644
--- a/hotspot/src/share/vm/opto/runtime.cpp
+++ b/hotspot/src/share/vm/opto/runtime.cpp
@@ -55,6 +55,7 @@
 #include "opto/mulnode.hpp"
 #include "opto/runtime.hpp"
 #include "opto/subnode.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/fprofiler.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/interfaceSupport.hpp"
diff --git a/hotspot/src/share/vm/prims/jni.cpp b/hotspot/src/share/vm/prims/jni.cpp
index cdb53afe1b7aeee41a50c97be66d3b6fd299c41f..6eebcad45aace6140cbf8b2e88caeeb51addd0f1 100644
--- a/hotspot/src/share/vm/prims/jni.cpp
+++ b/hotspot/src/share/vm/prims/jni.cpp
@@ -59,6 +59,7 @@
 #include "prims/jvm_misc.hpp"
 #include "prims/jvmtiExport.hpp"
 #include "prims/jvmtiThreadState.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/compilationPolicy.hpp"
 #include "runtime/fieldDescriptor.hpp"
 #include "runtime/fprofiler.hpp"
@@ -3336,13 +3337,7 @@ static bool initializeDirectBufferSupport(JNIEnv* env, JavaThread* thread) {
     directBufferSupportInitializeEnded = 1;
   } else {
     while (!directBufferSupportInitializeEnded && !directBufferSupportInitializeFailed) {
-      // Set state as yield_all can call os:sleep. On Solaris, yield_all calls
-      // os::sleep which requires the VM state transition. On other platforms, it
-      // is not necessary. The following call to change the VM state is purposely
-      // put inside the loop to avoid potential deadlock when multiple threads
-      // try to call this method. See 6791815 for more details.
-      ThreadInVMfromNative tivn(thread);
-      os::yield_all();
+      os::yield();
     }
   }
 
diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp
index 69e45bd11f7964f7ce1ac5b2ac568908632848c0..0dbeea8a8a467cdd54a41e1b79c34697ba8d69d6 100644
--- a/hotspot/src/share/vm/prims/jvm.cpp
+++ b/hotspot/src/share/vm/prims/jvm.cpp
@@ -44,6 +44,7 @@
 #include "prims/nativeLookup.hpp"
 #include "prims/privilegedStack.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/dtraceJSDT.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/init.hpp"
@@ -55,6 +56,7 @@
 #include "runtime/os.hpp"
 #include "runtime/perfData.hpp"
 #include "runtime/reflection.hpp"
+#include "runtime/thread.inline.hpp"
 #include "runtime/vframe.hpp"
 #include "runtime/vm_operations.hpp"
 #include "services/attachListener.hpp"
diff --git a/hotspot/src/share/vm/prims/jvmtiEnv.cpp b/hotspot/src/share/vm/prims/jvmtiEnv.cpp
index 765cbcd62907b9e17ed00f849f57806aa96c7c78..7d6b121e5fa1a325c896fc9e45609adccd33d380 100644
--- a/hotspot/src/share/vm/prims/jvmtiEnv.cpp
+++ b/hotspot/src/share/vm/prims/jvmtiEnv.cpp
@@ -258,9 +258,6 @@ JvmtiEnv::RetransformClasses(jint class_count, const jclass* classes) {
       // VM representation. We don't attach the reconstituted class
       // bytes to the InstanceKlass here because they have not been
       // validated and we're not at a safepoint.
-      constantPoolHandle  constants(current_thread, ikh->constants());
-      MonitorLockerEx ml(constants->lock());    // lock constant pool while we query it
-
       JvmtiClassFileReconstituter reconstituter(ikh);
       if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
         return reconstituter.get_error();
@@ -2445,9 +2442,6 @@ JvmtiEnv::GetConstantPool(oop k_mirror, jint* constant_pool_count_ptr, jint* con
   }
 
   instanceKlassHandle ikh(thread, k_oop);
-  constantPoolHandle  constants(thread, ikh->constants());
-  MonitorLockerEx ml(constants->lock());    // lock constant pool while we query it
-
   JvmtiConstantPoolReconstituter reconstituter(ikh);
   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
     return reconstituter.get_error();
@@ -2467,6 +2461,7 @@ JvmtiEnv::GetConstantPool(oop k_mirror, jint* constant_pool_count_ptr, jint* con
     return reconstituter.get_error();
   }
 
+  constantPoolHandle  constants(thread, ikh->constants());
   *constant_pool_count_ptr      = constants->length();
   *constant_pool_byte_count_ptr = cpool_size;
   *constant_pool_bytes_ptr      = cpool_bytes;
diff --git a/hotspot/src/share/vm/prims/jvmtiImpl.cpp b/hotspot/src/share/vm/prims/jvmtiImpl.cpp
index 0d6d00d4ec6cc3a69e5915d3ceec086a709f680a..328e9d869affbb9051c25d3f6cf8080164b6bce7 100644
--- a/hotspot/src/share/vm/prims/jvmtiImpl.cpp
+++ b/hotspot/src/share/vm/prims/jvmtiImpl.cpp
@@ -32,7 +32,7 @@
 #include "prims/jvmtiEventController.inline.hpp"
 #include "prims/jvmtiImpl.hpp"
 #include "prims/jvmtiRedefineClasses.hpp"
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/deoptimization.hpp"
 #include "runtime/handles.hpp"
 #include "runtime/handles.inline.hpp"
diff --git a/hotspot/src/share/vm/prims/jvmtiRawMonitor.cpp b/hotspot/src/share/vm/prims/jvmtiRawMonitor.cpp
index 4be4d277055a7cb64c088164a26ba1d9a8e554d2..003f12f0c0a938eee4b8eb62deb15908e0c40afc 100644
--- a/hotspot/src/share/vm/prims/jvmtiRawMonitor.cpp
+++ b/hotspot/src/share/vm/prims/jvmtiRawMonitor.cpp
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "prims/jvmtiRawMonitor.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/interfaceSupport.hpp"
 #include "runtime/orderAccess.inline.hpp"
 #include "runtime/thread.inline.hpp"
diff --git a/hotspot/src/share/vm/prims/unsafe.cpp b/hotspot/src/share/vm/prims/unsafe.cpp
index 332f8fb74ab46f2e7e4b6bef794528333be60064..955e34d503479c806954c5a79b6e794a18ce783a 100644
--- a/hotspot/src/share/vm/prims/unsafe.cpp
+++ b/hotspot/src/share/vm/prims/unsafe.cpp
@@ -31,6 +31,7 @@
 #include "memory/allocation.inline.hpp"
 #include "prims/jni.h"
 #include "prims/jvm.h"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/interfaceSupport.hpp"
 #include "runtime/prefetch.inline.hpp"
@@ -891,6 +892,14 @@ UNSAFE_ENTRY(jclass, Unsafe_DefineClass(JNIEnv *env, jobject unsafe, jstring nam
   }
 UNSAFE_END
 
+static jobject get_class_loader(JNIEnv* env, jclass cls) {
+  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
+    return NULL;
+  }
+  Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
+  oop loader = k->class_loader();
+  return JNIHandles::make_local(env, loader);
+}
 
 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length))
   UnsafeWrapper("Unsafe_DefineClass");
@@ -899,7 +908,7 @@ UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring na
 
     int depthFromDefineClass0 = 1;
     jclass  caller = JVM_GetCallerClass(env, depthFromDefineClass0);
-    jobject loader = (caller == NULL) ? NULL : JVM_GetClassLoader(env, caller);
+    jobject loader = (caller == NULL) ? NULL : get_class_loader(env, caller);
     jobject pd     = (caller == NULL) ? NULL : JVM_GetProtectionDomain(env, caller);
 
     return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
diff --git a/hotspot/src/share/vm/runtime/biasedLocking.cpp b/hotspot/src/share/vm/runtime/biasedLocking.cpp
index c8c2acf37dfad7d2f4070143fc02d40f105d1a38..f89f71bca6aeaa54b48bb82109347b27ce6ac326 100644
--- a/hotspot/src/share/vm/runtime/biasedLocking.cpp
+++ b/hotspot/src/share/vm/runtime/biasedLocking.cpp
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "oops/klass.inline.hpp"
 #include "oops/markOop.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/basicLock.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/task.hpp"
diff --git a/hotspot/src/share/vm/runtime/extendedPC.hpp b/hotspot/src/share/vm/runtime/extendedPC.hpp
index 7a1ca4abe45ddf04ae26c345ce7bcab89303312b..ea937416ac5ebd8f6eead7114199113f545abd7b 100644
--- a/hotspot/src/share/vm/runtime/extendedPC.hpp
+++ b/hotspot/src/share/vm/runtime/extendedPC.hpp
@@ -25,6 +25,9 @@
 #ifndef SHARE_VM_RUNTIME_EXTENDEDPC_HPP
 #define SHARE_VM_RUNTIME_EXTENDEDPC_HPP
 
+#include "memory/allocation.hpp"
+#include "utilities/globalDefinitions.hpp"
+
 // An ExtendedPC contains the _pc from a signal handler in a platform
 // independent way.
 
diff --git a/hotspot/src/share/vm/runtime/frame.cpp b/hotspot/src/share/vm/runtime/frame.cpp
index 2f7cb8f186a33f2bf389deac3ee1e21bd390d7f1..5768693b40615b77ef27ebbaa098e2a63f3c0761 100644
--- a/hotspot/src/share/vm/runtime/frame.cpp
+++ b/hotspot/src/share/vm/runtime/frame.cpp
@@ -44,6 +44,7 @@
 #include "runtime/signature.hpp"
 #include "runtime/stubCodeGenerator.hpp"
 #include "runtime/stubRoutines.hpp"
+#include "runtime/thread.inline.hpp"
 #include "utilities/decoder.hpp"
 
 #ifdef TARGET_ARCH_x86
diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp
index 1dbf51c8632624a582001919adcb63b54e7188f6..56cafb656008c43474f9fc8c1ad78f2d7bde5a66 100644
--- a/hotspot/src/share/vm/runtime/globals.hpp
+++ b/hotspot/src/share/vm/runtime/globals.hpp
@@ -2299,6 +2299,9 @@ class CommandLineFlags {
   manageable(bool, PrintGCTimeStamps, false,                                \
           "Print timestamps at garbage collection")                         \
                                                                             \
+  manageable(bool, PrintGCID, true,                                         \
+          "Print an identifier for each garbage collection")                \
+                                                                            \
   product(bool, PrintGCTaskTimeStamps, false,                               \
           "Print timestamps for individual gc worker thread tasks")         \
                                                                             \
diff --git a/hotspot/src/share/vm/runtime/handles.cpp b/hotspot/src/share/vm/runtime/handles.cpp
index e80b6d79828c7f94e8bc9e888d50924255bc5bf3..5d35853893021f64930889ab543fb649d1db4588 100644
--- a/hotspot/src/share/vm/runtime/handles.cpp
+++ b/hotspot/src/share/vm/runtime/handles.cpp
@@ -26,6 +26,7 @@
 #include "memory/allocation.inline.hpp"
 #include "oops/constantPool.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/thread.inline.hpp"
 #ifdef TARGET_OS_FAMILY_linux
diff --git a/hotspot/src/share/vm/runtime/interfaceSupport.cpp b/hotspot/src/share/vm/runtime/interfaceSupport.cpp
index 09757155d9d35fcd54db57f9cf13b8e7829d6000..25953f3d3bc838fdfb7ca2678b4845d10573f721 100644
--- a/hotspot/src/share/vm/runtime/interfaceSupport.cpp
+++ b/hotspot/src/share/vm/runtime/interfaceSupport.cpp
@@ -28,6 +28,7 @@
 #include "gc_interface/collectedHeap.inline.hpp"
 #include "memory/genCollectedHeap.hpp"
 #include "memory/resourceArea.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/init.hpp"
 #include "runtime/interfaceSupport.hpp"
 #include "runtime/orderAccess.inline.hpp"
diff --git a/hotspot/src/share/vm/runtime/mutex.cpp b/hotspot/src/share/vm/runtime/mutex.cpp
index f5ac0f8ea153edb098d0b5f31f962a1262a4be88..f903c00291ca069a4774f2e1fafaa7a88bf26bd9 100644
--- a/hotspot/src/share/vm/runtime/mutex.cpp
+++ b/hotspot/src/share/vm/runtime/mutex.cpp
@@ -24,6 +24,7 @@
  */
 
 #include "precompiled.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/mutex.hpp"
 #include "runtime/orderAccess.inline.hpp"
 #include "runtime/osThread.hpp"
diff --git a/hotspot/src/share/vm/runtime/objectMonitor.cpp b/hotspot/src/share/vm/runtime/objectMonitor.cpp
index d9682ebf6016dbdb5c768fbc80cacd1686aaf555..c7a91f470c60bfa2b5b68a836130f7f0257e557f 100644
--- a/hotspot/src/share/vm/runtime/objectMonitor.cpp
+++ b/hotspot/src/share/vm/runtime/objectMonitor.cpp
@@ -27,6 +27,7 @@
 #include "memory/resourceArea.hpp"
 #include "oops/markOop.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/interfaceSupport.hpp"
 #include "runtime/mutexLocker.hpp"
diff --git a/hotspot/src/share/vm/runtime/os.cpp b/hotspot/src/share/vm/runtime/os.cpp
index dc5d664989b0f0d4ddcfef1e8256d557e70ef63f..5666aa0d45f534a11fa4d256019bf978654e553d 100644
--- a/hotspot/src/share/vm/runtime/os.cpp
+++ b/hotspot/src/share/vm/runtime/os.cpp
@@ -40,6 +40,7 @@
 #include "prims/jvm_misc.hpp"
 #include "prims/privilegedStack.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/frame.inline.hpp"
 #include "runtime/interfaceSupport.hpp"
 #include "runtime/java.hpp"
diff --git a/hotspot/src/share/vm/runtime/os.hpp b/hotspot/src/share/vm/runtime/os.hpp
index c0c81a1f2ad43acc3b9acf6471966d6808f30a33..d4bd89d756c10fc80d0d0db145c8efb9d5a48807 100644
--- a/hotspot/src/share/vm/runtime/os.hpp
+++ b/hotspot/src/share/vm/runtime/os.hpp
@@ -26,7 +26,6 @@
 #define SHARE_VM_RUNTIME_OS_HPP
 
 #include "jvmtifiles/jvmti.h"
-#include "runtime/atomic.hpp"
 #include "runtime/extendedPC.hpp"
 #include "runtime/handles.hpp"
 #include "utilities/top.hpp"
@@ -453,8 +452,6 @@ class os: AllStatic {
     // yield that can be used in lieu of blocking.
   } ;
   static YieldResult NakedYield () ;
-  static void yield_all(); // Yields to all other threads including lower priority
-                           // (for the default scheduling policy)
   static OSReturn set_priority(Thread* thread, ThreadPriority priority);
   static OSReturn get_priority(const Thread* const thread, ThreadPriority& priority);
 
diff --git a/hotspot/src/share/vm/runtime/safepoint.cpp b/hotspot/src/share/vm/runtime/safepoint.cpp
index e71185d431d2769bc56445fec324f5f9c6d414b7..b0dc8863e831513a5347745e24641cbee1911f92 100644
--- a/hotspot/src/share/vm/runtime/safepoint.cpp
+++ b/hotspot/src/share/vm/runtime/safepoint.cpp
@@ -32,10 +32,12 @@
 #include "code/scopeDesc.hpp"
 #include "gc_interface/collectedHeap.hpp"
 #include "interpreter/interpreter.hpp"
+#include "memory/gcLocker.inline.hpp"
 #include "memory/resourceArea.hpp"
 #include "memory/universe.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/symbol.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/compilationPolicy.hpp"
 #include "runtime/deoptimization.hpp"
 #include "runtime/frame.inline.hpp"
@@ -264,8 +266,8 @@ void SafepointSynchronize::begin() {
       //
       // Further complicating matters is that yield() does not work as naively expected
       // on many platforms -- yield() does not guarantee that any other ready threads
-      // will run.   As such we revert yield_all() after some number of iterations.
-      // Yield_all() is implemented as a short unconditional sleep on some platforms.
+      // will run.   As such we revert to naked_short_sleep() after some number of iterations.
+      // nakes_short_sleep() is implemented as a short unconditional sleep.
       // Typical operating systems round a "short" sleep period up to 10 msecs, so sleeping
       // can actually increase the time it takes the VM thread to detect that a system-wide
       // stop-the-world safepoint has been reached.  In a pathological scenario such as that
@@ -322,9 +324,7 @@ void SafepointSynchronize::begin() {
       if (steps < DeferThrSuspendLoopCount) {
         os::NakedYield() ;
       } else {
-        os::yield_all() ;
-        // Alternately, the VM thread could transiently depress its scheduling priority or
-        // transiently increase the priority of the tardy mutator(s).
+        os::naked_short_sleep(1);
       }
 
       iterations ++ ;
@@ -744,80 +744,12 @@ void SafepointSynchronize::block(JavaThread *thread) {
 // ------------------------------------------------------------------------------------------------------
 // Exception handlers
 
-#ifndef PRODUCT
-
-#ifdef SPARC
-
-#ifdef _LP64
-#define PTR_PAD ""
-#else
-#define PTR_PAD "        "
-#endif
-
-static void print_ptrs(intptr_t oldptr, intptr_t newptr, bool wasoop) {
-  bool is_oop = newptr ? (cast_to_oop(newptr))->is_oop() : false;
-  tty->print_cr(PTR_FORMAT PTR_PAD " %s %c " PTR_FORMAT PTR_PAD " %s %s",
-                oldptr, wasoop?"oop":"   ", oldptr == newptr ? ' ' : '!',
-                newptr, is_oop?"oop":"   ", (wasoop && !is_oop) ? "STALE" : ((wasoop==false&&is_oop==false&&oldptr !=newptr)?"STOMP":"     "));
-}
-
-static void print_longs(jlong oldptr, jlong newptr, bool wasoop) {
-  bool is_oop = newptr ? (cast_to_oop(newptr))->is_oop() : false;
-  tty->print_cr(PTR64_FORMAT " %s %c " PTR64_FORMAT " %s %s",
-                oldptr, wasoop?"oop":"   ", oldptr == newptr ? ' ' : '!',
-                newptr, is_oop?"oop":"   ", (wasoop && !is_oop) ? "STALE" : ((wasoop==false&&is_oop==false&&oldptr !=newptr)?"STOMP":"     "));
-}
-
-static void print_me(intptr_t *new_sp, intptr_t *old_sp, bool *was_oops) {
-#ifdef _LP64
-  tty->print_cr("--------+------address-----+------before-----------+-------after----------+");
-  const int incr = 1;           // Increment to skip a long, in units of intptr_t
-#else
-  tty->print_cr("--------+--address-+------before-----------+-------after----------+");
-  const int incr = 2;           // Increment to skip a long, in units of intptr_t
-#endif
-  tty->print_cr("---SP---|");
-  for( int i=0; i<16; i++ ) {
-    tty->print("blob %c%d |"PTR_FORMAT" ","LO"[i>>3],i&7,new_sp); print_ptrs(*old_sp++,*new_sp++,*was_oops++); }
-  tty->print_cr("--------|");
-  for( int i1=0; i1<frame::memory_parameter_word_sp_offset-16; i1++ ) {
-    tty->print("argv pad|"PTR_FORMAT" ",new_sp); print_ptrs(*old_sp++,*new_sp++,*was_oops++); }
-  tty->print("     pad|"PTR_FORMAT" ",new_sp); print_ptrs(*old_sp++,*new_sp++,*was_oops++);
-  tty->print_cr("--------|");
-  tty->print(" G1     |"PTR_FORMAT" ",new_sp); print_longs(*(jlong*)old_sp,*(jlong*)new_sp,was_oops[incr-1]); old_sp += incr; new_sp += incr; was_oops += incr;
-  tty->print(" G3     |"PTR_FORMAT" ",new_sp); print_longs(*(jlong*)old_sp,*(jlong*)new_sp,was_oops[incr-1]); old_sp += incr; new_sp += incr; was_oops += incr;
-  tty->print(" G4     |"PTR_FORMAT" ",new_sp); print_longs(*(jlong*)old_sp,*(jlong*)new_sp,was_oops[incr-1]); old_sp += incr; new_sp += incr; was_oops += incr;
-  tty->print(" G5     |"PTR_FORMAT" ",new_sp); print_longs(*(jlong*)old_sp,*(jlong*)new_sp,was_oops[incr-1]); old_sp += incr; new_sp += incr; was_oops += incr;
-  tty->print_cr(" FSR    |"PTR_FORMAT" "PTR64_FORMAT"       "PTR64_FORMAT,new_sp,*(jlong*)old_sp,*(jlong*)new_sp);
-  old_sp += incr; new_sp += incr; was_oops += incr;
-  // Skip the floats
-  tty->print_cr("--Float-|"PTR_FORMAT,new_sp);
-  tty->print_cr("---FP---|");
-  old_sp += incr*32;  new_sp += incr*32;  was_oops += incr*32;
-  for( int i2=0; i2<16; i2++ ) {
-    tty->print("call %c%d |"PTR_FORMAT" ","LI"[i2>>3],i2&7,new_sp); print_ptrs(*old_sp++,*new_sp++,*was_oops++); }
-  tty->cr();
-}
-#endif  // SPARC
-#endif  // PRODUCT
-
 
 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
   assert(thread->is_Java_thread(), "polling reference encountered by VM thread");
   assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
   assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization");
 
-  // Uncomment this to get some serious before/after printing of the
-  // Sparc safepoint-blob frame structure.
-  /*
-  intptr_t* sp = thread->last_Java_sp();
-  intptr_t stack_copy[150];
-  for( int i=0; i<150; i++ ) stack_copy[i] = sp[i];
-  bool was_oops[150];
-  for( int i=0; i<150; i++ )
-    was_oops[i] = stack_copy[i] ? ((oop)stack_copy[i])->is_oop() : false;
-  */
-
   if (ShowSafepointMsgs) {
     tty->print("handle_polling_page_exception: ");
   }
@@ -829,7 +761,6 @@ void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
   ThreadSafepointState* state = thread->safepoint_state();
 
   state->handle_polling_page_exception();
-  // print_me(sp,stack_copy,was_oops);
 }
 
 
diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.cpp b/hotspot/src/share/vm/runtime/sharedRuntime.cpp
index efd8be473b346c16a690ab8467218694dd747eef..c717e61c8c6c2e824e097d0ac6922f1eb42a7897 100644
--- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp
@@ -42,6 +42,7 @@
 #include "prims/jvmtiRedefineClassesTrace.hpp"
 #include "prims/methodHandles.hpp"
 #include "prims/nativeLookup.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/arguments.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/handles.inline.hpp"
@@ -1176,10 +1177,7 @@ methodHandle SharedRuntime::resolve_sub_helper(JavaThread *thread,
          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
 
-  // We do not patch the call site if the caller nmethod has been made non-entrant.
-  if (!caller_nm->is_in_use()) {
-    return callee_method;
-  }
+  assert(caller_nm->is_alive(), "It should be alive");
 
 #ifndef PRODUCT
   // tracing/debugging/statistics
@@ -1249,13 +1247,11 @@ methodHandle SharedRuntime::resolve_sub_helper(JavaThread *thread,
 
     // Now that we are ready to patch if the Method* was redefined then
     // don't update call site and let the caller retry.
-    // Don't update call site if caller nmethod has been made non-entrant
-    // as it is a waste of time.
     // Don't update call site if callee nmethod was unloaded or deoptimized.
     // Don't update call site if callee nmethod was replaced by an other nmethod
     // which may happen when multiply alive nmethod (tiered compilation)
     // will be supported.
-    if (!callee_method->is_old() && caller_nm->is_in_use() &&
+    if (!callee_method->is_old() &&
         (callee_nm == NULL || callee_nm->is_in_use() && (callee_method->code() == callee_nm))) {
 #ifdef ASSERT
       // We must not try to patch to jump to an already unloaded method.
@@ -1454,14 +1450,12 @@ methodHandle SharedRuntime::handle_ic_miss_helper(JavaThread *thread, TRAPS) {
   // out of scope.
   JvmtiDynamicCodeEventCollector event_collector;
 
-  // Update inline cache to megamorphic. Skip update if caller has been
-  // made non-entrant or we are called from interpreted.
+  // Update inline cache to megamorphic. Skip update if we are called from interpreted.
   { MutexLocker ml_patch (CompiledIC_lock);
     RegisterMap reg_map(thread, false);
     frame caller_frame = thread->last_frame().sender(&reg_map);
     CodeBlob* cb = caller_frame.cb();
-    if (cb->is_nmethod() && ((nmethod*)cb)->is_in_use()) {
-      // Not a non-entrant nmethod, so find inline_cache
+    if (cb->is_nmethod()) {
       CompiledIC* inline_cache = CompiledIC_before(((nmethod*)cb), caller_frame.pc());
       bool should_be_mono = false;
       if (inline_cache->is_optimized()) {
@@ -1604,19 +1598,13 @@ methodHandle SharedRuntime::reresolve_call_site(JavaThread *thread, TRAPS) {
       // resolve is only done once.
 
       MutexLocker ml(CompiledIC_lock);
-      //
-      // We do not patch the call site if the nmethod has been made non-entrant
-      // as it is a waste of time
-      //
-      if (caller_nm->is_in_use()) {
-        if (is_static_call) {
-          CompiledStaticCall* ssc= compiledStaticCall_at(call_addr);
-          ssc->set_to_clean();
-        } else {
-          // compiled, dispatched call (which used to call an interpreted method)
-          CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
-          inline_cache->set_to_clean();
-        }
+      if (is_static_call) {
+        CompiledStaticCall* ssc= compiledStaticCall_at(call_addr);
+        ssc->set_to_clean();
+      } else {
+        // compiled, dispatched call (which used to call an interpreted method)
+        CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
+        inline_cache->set_to_clean();
       }
     }
 
diff --git a/hotspot/src/share/vm/runtime/sweeper.cpp b/hotspot/src/share/vm/runtime/sweeper.cpp
index 5ec575aa3568d0bcb18f371a6956143791faed0f..0a964ac872804a46105fbbf408dc032faa80fefb 100644
--- a/hotspot/src/share/vm/runtime/sweeper.cpp
+++ b/hotspot/src/share/vm/runtime/sweeper.cpp
@@ -30,7 +30,7 @@
 #include "compiler/compileBroker.hpp"
 #include "memory/resourceArea.hpp"
 #include "oops/method.hpp"
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/compilationPolicy.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/orderAccess.inline.hpp"
diff --git a/hotspot/src/share/vm/runtime/synchronizer.cpp b/hotspot/src/share/vm/runtime/synchronizer.cpp
index 7af5fe72b62b275fd47fe824c0e8005d51dc5dbe..a7de4bda77ae8eb59c6b4abe198e9aa7cc5b4b84 100644
--- a/hotspot/src/share/vm/runtime/synchronizer.cpp
+++ b/hotspot/src/share/vm/runtime/synchronizer.cpp
@@ -27,6 +27,7 @@
 #include "memory/resourceArea.hpp"
 #include "oops/markOop.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/interfaceSupport.hpp"
diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp
index 7031620a28347c566523ef5b49eddeb8ada1b966..05cb340ae85e06840ba3ace3dd932914ee5655d2 100644
--- a/hotspot/src/share/vm/runtime/thread.cpp
+++ b/hotspot/src/share/vm/runtime/thread.cpp
@@ -46,6 +46,7 @@
 #include "prims/jvmtiThreadState.hpp"
 #include "prims/privilegedStack.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/deoptimization.hpp"
 #include "runtime/fprofiler.hpp"
@@ -1357,14 +1358,24 @@ void WatcherThread::make_startable() {
 }
 
 void WatcherThread::stop() {
-  {
-    MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
-    _should_terminate = true;
-    OrderAccess::fence();  // ensure WatcherThread sees update in main loop
+  // Get the PeriodicTask_lock if we can. If we cannot, then the
+  // WatcherThread is using it and we don't want to block on that lock
+  // here because that might cause a safepoint deadlock depending on
+  // what the current WatcherThread tasks are doing.
+  bool have_lock = PeriodicTask_lock->try_lock();
+
+  _should_terminate = true;
+  OrderAccess::fence();  // ensure WatcherThread sees update in main loop
 
+  if (have_lock) {
     WatcherThread* watcher = watcher_thread();
-    if (watcher != NULL)
+    if (watcher != NULL) {
+      // If we managed to get the lock, then we should unpark the
+      // WatcherThread so that it can see we want it to stop.
       watcher->unpark();
+    }
+
+    PeriodicTask_lock->unlock();
   }
 
   // it is ok to take late safepoints here, if needed
diff --git a/hotspot/src/share/vm/runtime/thread.hpp b/hotspot/src/share/vm/runtime/thread.hpp
index 68c9248dea41aeb60d44920684d245d91a73fb04..003932e74f3e40cbebbfd68eee22e008f97f7bc0 100644
--- a/hotspot/src/share/vm/runtime/thread.hpp
+++ b/hotspot/src/share/vm/runtime/thread.hpp
@@ -343,42 +343,16 @@ class Thread: public ThreadShadow {
 
   bool has_async_exception() const { return (_suspend_flags & _has_async_exception) != 0; }
 
-  void set_suspend_flag(SuspendFlags f) {
-    assert(sizeof(jint) == sizeof(_suspend_flags), "size mismatch");
-    uint32_t flags;
-    do {
-      flags = _suspend_flags;
-    }
-    while (Atomic::cmpxchg((jint)(flags | f),
-                           (volatile jint*)&_suspend_flags,
-                           (jint)flags) != (jint)flags);
-  }
-  void clear_suspend_flag(SuspendFlags f) {
-    assert(sizeof(jint) == sizeof(_suspend_flags), "size mismatch");
-    uint32_t flags;
-    do {
-      flags = _suspend_flags;
-    }
-    while (Atomic::cmpxchg((jint)(flags & ~f),
-                           (volatile jint*)&_suspend_flags,
-                           (jint)flags) != (jint)flags);
-  }
+  inline void set_suspend_flag(SuspendFlags f);
+  inline void clear_suspend_flag(SuspendFlags f);
 
-  void set_has_async_exception() {
-    set_suspend_flag(_has_async_exception);
-  }
-  void clear_has_async_exception() {
-    clear_suspend_flag(_has_async_exception);
-  }
+  inline void set_has_async_exception();
+  inline void clear_has_async_exception();
 
   bool do_critical_native_unlock() const { return (_suspend_flags & _critical_native_unlock) != 0; }
 
-  void set_critical_native_unlock() {
-    set_suspend_flag(_critical_native_unlock);
-  }
-  void clear_critical_native_unlock() {
-    clear_suspend_flag(_critical_native_unlock);
-  }
+  inline void set_critical_native_unlock();
+  inline void clear_critical_native_unlock();
 
   // Support for Unhandled Oop detection
 #ifdef CHECK_UNHANDLED_OOPS
@@ -1074,8 +1048,8 @@ class JavaThread: public Thread {
 
   // Suspend/resume support for JavaThread
  private:
-  void set_ext_suspended()       { set_suspend_flag (_ext_suspended);  }
-  void clear_ext_suspended()     { clear_suspend_flag(_ext_suspended); }
+  inline void set_ext_suspended();
+  inline void clear_ext_suspended();
 
  public:
   void java_suspend();
@@ -1123,11 +1097,11 @@ class JavaThread: public Thread {
   // via the appropriate -XX options.
   bool wait_for_ext_suspend_completion(int count, int delay, uint32_t *bits);
 
-  void set_external_suspend()     { set_suspend_flag  (_external_suspend); }
-  void clear_external_suspend()   { clear_suspend_flag(_external_suspend); }
+  inline void set_external_suspend();
+  inline void clear_external_suspend();
 
-  void set_deopt_suspend()        { set_suspend_flag  (_deopt_suspend); }
-  void clear_deopt_suspend()      { clear_suspend_flag(_deopt_suspend); }
+  inline void set_deopt_suspend();
+  inline void clear_deopt_suspend();
   bool is_deopt_suspend()         { return (_suspend_flags & _deopt_suspend) != 0; }
 
   bool is_external_suspend() const {
@@ -1215,11 +1189,7 @@ class JavaThread: public Thread {
 
   void set_pending_unsafe_access_error()          { _special_runtime_exit_condition = _async_unsafe_access_error; }
 
-  void set_pending_async_exception(oop e) {
-    _pending_async_exception = e;
-    _special_runtime_exit_condition = _async_exception;
-    set_has_async_exception();
-  }
+  inline void set_pending_async_exception(oop e);
 
   // Fast-locking support
   bool is_lock_owned(address adr) const;
diff --git a/hotspot/src/share/vm/runtime/thread.inline.hpp b/hotspot/src/share/vm/runtime/thread.inline.hpp
index b68e7d1ae38d758755fec8837f5542f5160d4885..26a3330805bc08acff8499c38d0de8ce9c6392b6 100644
--- a/hotspot/src/share/vm/runtime/thread.inline.hpp
+++ b/hotspot/src/share/vm/runtime/thread.inline.hpp
@@ -27,6 +27,7 @@
 
 #define SHARE_VM_RUNTIME_THREAD_INLINE_HPP_SCOPE
 
+#include "runtime/atomic.inline.hpp"
 #include "runtime/thread.hpp"
 #ifdef TARGET_OS_FAMILY_linux
 # include "thread_linux.inline.hpp"
@@ -46,6 +47,40 @@
 
 #undef SHARE_VM_RUNTIME_THREAD_INLINE_HPP_SCOPE
 
+inline void Thread::set_suspend_flag(SuspendFlags f) {
+  assert(sizeof(jint) == sizeof(_suspend_flags), "size mismatch");
+  uint32_t flags;
+  do {
+    flags = _suspend_flags;
+  }
+  while (Atomic::cmpxchg((jint)(flags | f),
+                         (volatile jint*)&_suspend_flags,
+                         (jint)flags) != (jint)flags);
+}
+inline void Thread::clear_suspend_flag(SuspendFlags f) {
+  assert(sizeof(jint) == sizeof(_suspend_flags), "size mismatch");
+  uint32_t flags;
+  do {
+    flags = _suspend_flags;
+  }
+  while (Atomic::cmpxchg((jint)(flags & ~f),
+                         (volatile jint*)&_suspend_flags,
+                         (jint)flags) != (jint)flags);
+}
+
+inline void Thread::set_has_async_exception() {
+  set_suspend_flag(_has_async_exception);
+}
+inline void Thread::clear_has_async_exception() {
+  clear_suspend_flag(_has_async_exception);
+}
+inline void Thread::set_critical_native_unlock() {
+  set_suspend_flag(_critical_native_unlock);
+}
+inline void Thread::clear_critical_native_unlock() {
+  clear_suspend_flag(_critical_native_unlock);
+}
+
 inline jlong Thread::cooked_allocated_bytes() {
   jlong allocated_bytes = OrderAccess::load_acquire(&_allocated_bytes);
   if (UseTLAB) {
@@ -59,6 +94,33 @@ inline jlong Thread::cooked_allocated_bytes() {
   return allocated_bytes;
 }
 
+inline void JavaThread::set_ext_suspended() {
+  set_suspend_flag (_ext_suspended);
+}
+inline void JavaThread::clear_ext_suspended() {
+  clear_suspend_flag(_ext_suspended);
+}
+
+inline void JavaThread::set_external_suspend() {
+  set_suspend_flag(_external_suspend);
+}
+inline void JavaThread::clear_external_suspend() {
+  clear_suspend_flag(_external_suspend);
+}
+
+inline void JavaThread::set_deopt_suspend() {
+  set_suspend_flag(_deopt_suspend);
+}
+inline void JavaThread::clear_deopt_suspend() {
+  clear_suspend_flag(_deopt_suspend);
+}
+
+inline void JavaThread::set_pending_async_exception(oop e) {
+  _pending_async_exception = e;
+  _special_runtime_exit_condition = _async_exception;
+  set_has_async_exception();
+}
+
 #ifdef PPC64
 inline JavaThreadState JavaThread::thread_state() const    {
   return (JavaThreadState) OrderAccess::load_acquire((volatile jint*)&_thread_state);
diff --git a/hotspot/src/share/vm/runtime/vmStructs.cpp b/hotspot/src/share/vm/runtime/vmStructs.cpp
index 1ae7ddf6681b71f7c8155f958c99cc96becac2c3..33fe915e7fef7da9b22fb3184a06359827b2a6b6 100644
--- a/hotspot/src/share/vm/runtime/vmStructs.cpp
+++ b/hotspot/src/share/vm/runtime/vmStructs.cpp
@@ -104,6 +104,7 @@
 #include "utilities/globalDefinitions.hpp"
 #include "utilities/hashtable.hpp"
 #include "utilities/macros.hpp"
+
 #ifdef TARGET_ARCH_x86
 # include "vmStructs_x86.hpp"
 #endif
@@ -168,6 +169,11 @@
 #include "gc_implementation/parallelScavenge/vmStructs_parallelgc.hpp"
 #include "gc_implementation/g1/vmStructs_g1.hpp"
 #endif // INCLUDE_ALL_GCS
+
+#if INCLUDE_TRACE
+ #include "runtime/vmStructs_trace.hpp"
+#endif
+
 #ifdef COMPILER2
 #include "opto/addnode.hpp"
 #include "opto/block.hpp"
@@ -1390,6 +1396,8 @@ typedef TwoOopHashtable<Symbol*, mtClass>     SymbolTwoOopHashtable;
   /* unsigned short on Win32 */                                           \
   declare_unsigned_integer_type(u1)                                       \
   declare_unsigned_integer_type(u2)                                       \
+  declare_unsigned_integer_type(u4)                                       \
+  declare_unsigned_integer_type(u8)                                       \
   declare_unsigned_integer_type(unsigned)                                 \
                                                                           \
   /*****************************/                                         \
@@ -2923,6 +2931,11 @@ VMStructEntry VMStructs::localHotSpotVMStructs[] = {
                 GENERATE_STATIC_VM_STRUCT_ENTRY)
 #endif // INCLUDE_ALL_GCS
 
+#if INCLUDE_TRACE
+  VM_STRUCTS_TRACE(GENERATE_NONSTATIC_VM_STRUCT_ENTRY,
+                GENERATE_STATIC_VM_STRUCT_ENTRY)
+#endif
+
   VM_STRUCTS_CPU(GENERATE_NONSTATIC_VM_STRUCT_ENTRY,
                  GENERATE_STATIC_VM_STRUCT_ENTRY,
                  GENERATE_UNCHECKED_NONSTATIC_VM_STRUCT_ENTRY,
@@ -2968,6 +2981,11 @@ VMTypeEntry VMStructs::localHotSpotVMTypes[] = {
               GENERATE_TOPLEVEL_VM_TYPE_ENTRY)
 #endif // INCLUDE_ALL_GCS
 
+#if INCLUDE_TRACE
+  VM_TYPES_TRACE(GENERATE_VM_TYPE_ENTRY,
+              GENERATE_TOPLEVEL_VM_TYPE_ENTRY)
+#endif
+
   VM_TYPES_CPU(GENERATE_VM_TYPE_ENTRY,
                GENERATE_TOPLEVEL_VM_TYPE_ENTRY,
                GENERATE_OOP_VM_TYPE_ENTRY,
@@ -3003,6 +3021,10 @@ VMIntConstantEntry VMStructs::localHotSpotVMIntConstants[] = {
   VM_INT_CONSTANTS_PARNEW(GENERATE_VM_INT_CONSTANT_ENTRY)
 #endif // INCLUDE_ALL_GCS
 
+#if INCLUDE_TRACE
+  VM_INT_CONSTANTS_TRACE(GENERATE_VM_INT_CONSTANT_ENTRY)
+#endif
+
   VM_INT_CONSTANTS_CPU(GENERATE_VM_INT_CONSTANT_ENTRY,
                        GENERATE_PREPROCESSOR_VM_INT_CONSTANT_ENTRY,
                        GENERATE_C1_VM_INT_CONSTANT_ENTRY,
@@ -3065,8 +3087,14 @@ VMStructs::init() {
 
   VM_STRUCTS_G1(CHECK_NONSTATIC_VM_STRUCT_ENTRY,
                 CHECK_STATIC_VM_STRUCT_ENTRY);
+
 #endif // INCLUDE_ALL_GCS
 
+#if INCLUDE_TRACE
+  VM_STRUCTS_TRACE(CHECK_NONSTATIC_VM_STRUCT_ENTRY,
+                CHECK_STATIC_VM_STRUCT_ENTRY);
+#endif
+
   VM_STRUCTS_CPU(CHECK_NONSTATIC_VM_STRUCT_ENTRY,
                  CHECK_STATIC_VM_STRUCT_ENTRY,
                  CHECK_NO_OP,
@@ -3105,8 +3133,14 @@ VMStructs::init() {
 
   VM_TYPES_G1(CHECK_VM_TYPE_ENTRY,
               CHECK_SINGLE_ARG_VM_TYPE_NO_OP);
+
 #endif // INCLUDE_ALL_GCS
 
+#if INCLUDE_TRACE
+  VM_TYPES_TRACE(CHECK_VM_TYPE_ENTRY,
+              CHECK_SINGLE_ARG_VM_TYPE_NO_OP);
+#endif
+
   VM_TYPES_CPU(CHECK_VM_TYPE_ENTRY,
                CHECK_SINGLE_ARG_VM_TYPE_NO_OP,
                CHECK_SINGLE_ARG_VM_TYPE_NO_OP,
@@ -3169,6 +3203,12 @@ VMStructs::init() {
   debug_only(VM_STRUCTS_G1(ENSURE_FIELD_TYPE_PRESENT,
                            ENSURE_FIELD_TYPE_PRESENT));
 #endif // INCLUDE_ALL_GCS
+
+#if INCLUDE_TRACE
+  debug_only(VM_STRUCTS_TRACE(ENSURE_FIELD_TYPE_PRESENT,
+                           ENSURE_FIELD_TYPE_PRESENT));
+#endif
+
   debug_only(VM_STRUCTS_CPU(ENSURE_FIELD_TYPE_PRESENT,
                             ENSURE_FIELD_TYPE_PRESENT,
                             CHECK_NO_OP,
diff --git a/hotspot/src/cpu/sparc/vm/bytecodes_sparc.hpp b/hotspot/src/share/vm/runtime/vmStructs_trace.hpp
similarity index 76%
rename from hotspot/src/cpu/sparc/vm/bytecodes_sparc.hpp
rename to hotspot/src/share/vm/runtime/vmStructs_trace.hpp
index f1d08b336abdd8794e4ad4f23f5d703267fe231d..b959c0f4a1fdc8973779b2e5d270f9ef97325e76 100644
--- a/hotspot/src/cpu/sparc/vm/bytecodes_sparc.hpp
+++ b/hotspot/src/share/vm/runtime/vmStructs_trace.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -22,16 +22,14 @@
  *
  */
 
-#ifndef CPU_SPARC_VM_BYTECODES_SPARC_HPP
-#define CPU_SPARC_VM_BYTECODES_SPARC_HPP
+#ifndef SHARE_VM_RUNTIME_VMSTRUCTS_TRACE_HPP
+#define SHARE_VM_RUNTIME_VMSTRUCTS_TRACE_HPP
 
-#ifdef SPARC
-#define NLOCALS_IN_REGS 6
-#endif
+#define VM_INT_CONSTANTS_TRACE(a)
 
+#define VM_STRUCTS_TRACE(a, b)
 
-// Sparc specific bytecodes
+#define VM_TYPES_TRACE(a, b)
 
-// (none)
 
-#endif // CPU_SPARC_VM_BYTECODES_SPARC_HPP
+#endif // SHARE_VM_RUNTIME_VMSTRUCTS_TRACE_HPP
diff --git a/hotspot/src/share/vm/runtime/vm_version.cpp b/hotspot/src/share/vm/runtime/vm_version.cpp
index 9fee996f6876b7afaaf79ed287e419f8ffc4fa0d..a1779a85fe2773ec46188ec2dfabf53b94ba38c6 100644
--- a/hotspot/src/share/vm/runtime/vm_version.cpp
+++ b/hotspot/src/share/vm/runtime/vm_version.cpp
@@ -72,14 +72,16 @@ int Abstract_VM_Version::_reserve_for_allocation_prefetch = 0;
 #ifndef JRE_RELEASE_VERSION
   #error JRE_RELEASE_VERSION must be defined
 #endif
-#ifndef HOTSPOT_BUILD_TARGET
-  #error HOTSPOT_BUILD_TARGET must be defined
-#endif
 
-#ifdef PRODUCT
-  #define VM_RELEASE HOTSPOT_RELEASE_VERSION
-#else
+// NOTE: Builds within Visual Studio do not define the build target in
+//       HOTSPOT_RELEASE_VERSION, so it must be done here
+#if defined(VISUAL_STUDIO_BUILD) && !defined(PRODUCT)
+  #ifndef HOTSPOT_BUILD_TARGET
+    #error HOTSPOT_BUILD_TARGET must be defined
+  #endif
   #define VM_RELEASE HOTSPOT_RELEASE_VERSION "-" HOTSPOT_BUILD_TARGET
+#else
+  #define VM_RELEASE HOTSPOT_RELEASE_VERSION
 #endif
 
 // HOTSPOT_RELEASE_VERSION follows the JDK release version naming convention
diff --git a/hotspot/src/share/vm/services/memPtr.cpp b/hotspot/src/share/vm/services/memPtr.cpp
index bc460517c585cbfce07db7840415432ee24482fd..2bab4b28d9a8dd024a17a1fdbe806252cf2f12c3 100644
--- a/hotspot/src/share/vm/services/memPtr.cpp
+++ b/hotspot/src/share/vm/services/memPtr.cpp
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "services/memPtr.hpp"
 #include "services/memTracker.hpp"
 
diff --git a/hotspot/src/share/vm/services/memPtr.hpp b/hotspot/src/share/vm/services/memPtr.hpp
index c54f0934a9424d01576056da837036c7d607cae7..cae454cc318d8c27703417168db399d6e4ba6462 100644
--- a/hotspot/src/share/vm/services/memPtr.hpp
+++ b/hotspot/src/share/vm/services/memPtr.hpp
@@ -26,7 +26,6 @@
 #define SHARE_VM_SERVICES_MEM_PTR_HPP
 
 #include "memory/allocation.hpp"
-#include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "runtime/safepoint.hpp"
 
diff --git a/hotspot/src/share/vm/services/memRecorder.cpp b/hotspot/src/share/vm/services/memRecorder.cpp
index afe7bd245df5c4c6d0f529d009af48010bc8a9b1..b8707f5836075e853bc92b2f3eba5e41a5270326 100644
--- a/hotspot/src/share/vm/services/memRecorder.cpp
+++ b/hotspot/src/share/vm/services/memRecorder.cpp
@@ -24,7 +24,7 @@
 
 #include "precompiled.hpp"
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "services/memBaseline.hpp"
 #include "services/memRecorder.hpp"
 #include "services/memPtr.hpp"
diff --git a/hotspot/src/share/vm/services/memTracker.cpp b/hotspot/src/share/vm/services/memTracker.cpp
index 213e24e1bd09d02c6c1016197d47fc7f9c664523..190c004b3743bd5b4b16b3c149b6e5f2015a57e3 100644
--- a/hotspot/src/share/vm/services/memTracker.cpp
+++ b/hotspot/src/share/vm/services/memTracker.cpp
@@ -24,7 +24,7 @@
 #include "precompiled.hpp"
 
 #include "oops/instanceKlass.hpp"
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/interfaceSupport.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/safepoint.hpp"
diff --git a/hotspot/src/share/vm/services/memTracker.hpp b/hotspot/src/share/vm/services/memTracker.hpp
index 1072e5d6a3d16a48baefdbdfefaae7f3052e4aaf..52715a68764bb165d2ca061e45489fadbce20823 100644
--- a/hotspot/src/share/vm/services/memTracker.hpp
+++ b/hotspot/src/share/vm/services/memTracker.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, 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
@@ -481,17 +481,9 @@ class MemTracker : AllStatic {
     if (_slowdown_calling_thread && thr != _worker_thread) {
 #ifdef _WINDOWS
       // On Windows, os::NakedYield() does not work as well
-      // as os::yield_all()
-      os::yield_all();
+      // as short sleep.
+      os::naked_short_sleep(1);
 #else
-     // On Solaris, os::yield_all() depends on os::sleep()
-     // which requires JavaTherad in _thread_in_vm state.
-     // Transits thread to _thread_in_vm state can be dangerous
-     // if caller holds lock, as it may deadlock with Threads_lock.
-     // So use NaKedYield instead.
-     //
-     // Linux and BSD, NakedYield() and yield_all() implementations
-     // are the same.
       os::NakedYield();
 #endif
     }
diff --git a/hotspot/src/share/vm/services/threadService.cpp b/hotspot/src/share/vm/services/threadService.cpp
index 21d87567eede378dffc4ae1511a247abbbbe390e..74d3ea1383a784ca2b3ea4e3879df2680144571c 100644
--- a/hotspot/src/share/vm/services/threadService.cpp
+++ b/hotspot/src/share/vm/services/threadService.cpp
@@ -29,6 +29,7 @@
 #include "memory/oopFactory.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/init.hpp"
 #include "runtime/thread.hpp"
diff --git a/hotspot/src/share/vm/shark/sharkRuntime.cpp b/hotspot/src/share/vm/shark/sharkRuntime.cpp
index fd9916e111b86950108b2834370b6e669dfbf2fc..bf609bce4559f31b438dc68842886f9d2a8a6228 100644
--- a/hotspot/src/share/vm/shark/sharkRuntime.cpp
+++ b/hotspot/src/share/vm/shark/sharkRuntime.cpp
@@ -24,6 +24,7 @@
  */
 
 #include "precompiled.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/deoptimization.hpp"
 #include "runtime/thread.hpp"
diff --git a/hotspot/src/share/vm/trace/tracetypes.xml b/hotspot/src/share/vm/trace/tracetypes.xml
index eb1c708eadb2a977d10b4341cd02b0e6dd36c7ed..f41dfc03f3e468bb0e67d2e514141082021945a9 100644
--- a/hotspot/src/share/vm/trace/tracetypes.xml
+++ b/hotspot/src/share/vm/trace/tracetypes.xml
@@ -98,6 +98,7 @@ Now we can use the content + data type in declaring event fields.
       <value type="SYMBOL" field="name" label="Name"/>
       <value type="SYMBOL" field="signature" label="Signature"/>
       <value type="SHORT" field="modifiers" label="Access modifiers"/>
+      <value type="BOOLEAN" field="hidden" label="Hidden"/>
     </content_type>
 
     <content_type id="UTFConstant" hr_name="UTF constant"
diff --git a/hotspot/src/share/vm/utilities/accessFlags.cpp b/hotspot/src/share/vm/utilities/accessFlags.cpp
index d9279428ed07c04079ef3cc4fb361bbe5bc1e899..936fdc1e933a2f8ffbdeaad22203d247128f1794 100644
--- a/hotspot/src/share/vm/utilities/accessFlags.cpp
+++ b/hotspot/src/share/vm/utilities/accessFlags.cpp
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "utilities/accessFlags.hpp"
 #ifdef TARGET_OS_FAMILY_linux
 # include "os_linux.inline.hpp"
diff --git a/hotspot/src/share/vm/utilities/bitMap.cpp b/hotspot/src/share/vm/utilities/bitMap.cpp
index bfcda11fdeac5fa5b5cf1e64626fe8ab438ec97d..446af01e6fa7977854ecf91f45bb5ea3f1e26da2 100644
--- a/hotspot/src/share/vm/utilities/bitMap.cpp
+++ b/hotspot/src/share/vm/utilities/bitMap.cpp
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/resourceArea.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "utilities/bitMap.inline.hpp"
 #include "utilities/copy.hpp"
 #ifdef TARGET_OS_FAMILY_linux
diff --git a/hotspot/src/share/vm/utilities/bitMap.inline.hpp b/hotspot/src/share/vm/utilities/bitMap.inline.hpp
index 318b178f1478aa9d6537eced61d096a78d578627..f565462a1a7514332c1e69c54128799f073124ed 100644
--- a/hotspot/src/share/vm/utilities/bitMap.inline.hpp
+++ b/hotspot/src/share/vm/utilities/bitMap.inline.hpp
@@ -25,7 +25,7 @@
 #ifndef SHARE_VM_UTILITIES_BITMAP_INLINE_HPP
 #define SHARE_VM_UTILITIES_BITMAP_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "utilities/bitMap.hpp"
 
 #ifdef ASSERT
diff --git a/hotspot/src/share/vm/utilities/debug.cpp b/hotspot/src/share/vm/utilities/debug.cpp
index ff3bc5d4c81ac4f399a8791cdc5f8ad8b7bc83f8..445cf55a7f72ed2df33e1653da3eb32da82e4ef0 100644
--- a/hotspot/src/share/vm/utilities/debug.cpp
+++ b/hotspot/src/share/vm/utilities/debug.cpp
@@ -39,6 +39,7 @@
 #include "oops/oop.inline.hpp"
 #include "prims/privilegedStack.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/frame.hpp"
 #include "runtime/java.hpp"
 #include "runtime/sharedRuntime.hpp"
diff --git a/hotspot/src/share/vm/utilities/histogram.cpp b/hotspot/src/share/vm/utilities/histogram.cpp
index 5bc7c59e90dfe2ccb08de19f3edfa4300d36f5e0..f4d7091cd222bae5debf91fc938893239dbe575a 100644
--- a/hotspot/src/share/vm/utilities/histogram.cpp
+++ b/hotspot/src/share/vm/utilities/histogram.cpp
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "utilities/histogram.hpp"
 
 #ifdef ASSERT
diff --git a/hotspot/src/share/vm/utilities/ostream.cpp b/hotspot/src/share/vm/utilities/ostream.cpp
index 54536c50742931f9ec676a60c77cc1b4d108ee31..8dcab1a978260eaa2c9e03b562167f2aace42554 100644
--- a/hotspot/src/share/vm/utilities/ostream.cpp
+++ b/hotspot/src/share/vm/utilities/ostream.cpp
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "compiler/compileLog.hpp"
+#include "gc_implementation/shared/gcId.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/arguments.hpp"
 #include "utilities/defaultStream.hpp"
@@ -240,6 +241,14 @@ void outputStream::date_stamp(bool guard,
   return;
 }
 
+void outputStream::gclog_stamp(const GCId& gc_id) {
+  date_stamp(PrintGCDateStamps);
+  stamp(PrintGCTimeStamps);
+  if (PrintGCID) {
+    print("#%u: ", gc_id.id());
+  }
+}
+
 outputStream& outputStream::indent() {
   while (_position < _indentation) sp();
   return *this;
diff --git a/hotspot/src/share/vm/utilities/ostream.hpp b/hotspot/src/share/vm/utilities/ostream.hpp
index 563bbe432b5dedeeb51d4b82f3ed9b6060cf3fd7..86d8099caa9ef626ec4a5d1f190c26438ada7f2a 100644
--- a/hotspot/src/share/vm/utilities/ostream.hpp
+++ b/hotspot/src/share/vm/utilities/ostream.hpp
@@ -28,6 +28,7 @@
 #include "memory/allocation.hpp"
 #include "runtime/timer.hpp"
 
+class GCId;
 DEBUG_ONLY(class ResourceMark;)
 
 // Output streams for printing
@@ -107,6 +108,7 @@ class outputStream : public ResourceObj {
    void date_stamp(bool guard) {
      date_stamp(guard, "", ": ");
    }
+   void gclog_stamp(const GCId& gc_id);
 
    // portable printing of 64 bit integers
    void print_jlong(jlong value);
diff --git a/hotspot/src/share/vm/utilities/taskqueue.cpp b/hotspot/src/share/vm/utilities/taskqueue.cpp
index a3daa8847b65bcd818b79b98709cdec3e85e3aa8..9a992c1664d0d9f226ede562b98aee117e8c693c 100644
--- a/hotspot/src/share/vm/utilities/taskqueue.cpp
+++ b/hotspot/src/share/vm/utilities/taskqueue.cpp
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 #include "runtime/thread.inline.hpp"
 #include "utilities/debug.hpp"
diff --git a/hotspot/src/share/vm/utilities/vmError.cpp b/hotspot/src/share/vm/utilities/vmError.cpp
index 62d8ba6b1761ef8d943c30227eea38834d5f0718..d18df9ad4e3607343d21c6512e5acedf9fb2ca8f 100644
--- a/hotspot/src/share/vm/utilities/vmError.cpp
+++ b/hotspot/src/share/vm/utilities/vmError.cpp
@@ -27,6 +27,7 @@
 #include "gc_interface/collectedHeap.hpp"
 #include "prims/whitebox.hpp"
 #include "runtime/arguments.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/frame.inline.hpp"
 #include "runtime/init.hpp"
 #include "runtime/os.hpp"
diff --git a/hotspot/src/share/vm/utilities/workgroup.cpp b/hotspot/src/share/vm/utilities/workgroup.cpp
index 3d1f1eef7a6459562faa6178f0fd43713fea6195..6b5d8969798d893ae1f5f98313ae850c8e30d611 100644
--- a/hotspot/src/share/vm/utilities/workgroup.cpp
+++ b/hotspot/src/share/vm/utilities/workgroup.cpp
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "memory/allocation.hpp"
 #include "memory/allocation.inline.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 #include "utilities/workgroup.hpp"
 
diff --git a/hotspot/test/compiler/8009761/Test8009761.java b/hotspot/test/compiler/8009761/Test8009761.java
index 39a2574834830ccbee6d7300b552b39d2976161a..ed0f94665e430e166d4ffcb3f315403690839678 100644
--- a/hotspot/test/compiler/8009761/Test8009761.java
+++ b/hotspot/test/compiler/8009761/Test8009761.java
@@ -21,11 +21,7 @@
  * questions.
  */
 
-import com.sun.management.HotSpotDiagnosticMXBean;
-import com.sun.management.VMOption;
 import sun.hotspot.WhiteBox;
-import sun.management.ManagementFactoryHelper;
-
 import java.lang.reflect.Method;
 
 /*
@@ -40,6 +36,7 @@ import java.lang.reflect.Method;
 public class Test8009761 {
 
     private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
+    private static int COMP_LEVEL_SIMPLE = 1;
     private static int COMP_LEVEL_FULL_OPTIMIZATION = 4;
     private static Method m3 = null;
 
@@ -236,7 +233,7 @@ public class Test8009761 {
 
     static public void main(String[] args) {
         // Make sure background compilation is disabled
-        if (backgroundCompilationEnabled()) {
+        if (WHITE_BOX.getBooleanVMFlag("BackgroundCompilation")) {
             throw new RuntimeException("Background compilation enabled");
         }
 
@@ -256,7 +253,11 @@ public class Test8009761 {
         c1 = count;
 
         // Force the compilation of m3() that will inline m1()
-        WHITE_BOX.enqueueMethodForCompilation(m3, COMP_LEVEL_FULL_OPTIMIZATION);
+        if(!WHITE_BOX.enqueueMethodForCompilation(m3, COMP_LEVEL_FULL_OPTIMIZATION)) {
+            // C2 compiler not available, compile with C1
+            WHITE_BOX.enqueueMethodForCompilation(m3, COMP_LEVEL_SIMPLE);
+        }
+
         // Because background compilation is disabled, method should now be compiled
         if(!WHITE_BOX.isMethodCompiled(m3)) {
             throw new RuntimeException(m3 + " not compiled");
@@ -278,19 +279,4 @@ public class Test8009761 {
             System.out.println("PASSED " + c1);
         }
     }
-
-    /**
-     * Checks if background compilation (-XX:+BackgroundCompilation) is enabled.
-     * @return True if background compilation is enabled, false otherwise
-     */
-    private static boolean backgroundCompilationEnabled() {
-      HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
-      VMOption backgroundCompilation;
-      try {
-          backgroundCompilation = diagnostic.getVMOption("BackgroundCompilation");
-      } catch (IllegalArgumentException e) {
-          return false;
-      }
-      return Boolean.valueOf(backgroundCompilation.getValue());
-    }
 }
diff --git a/hotspot/test/compiler/ciReplay/TestSA.sh b/hotspot/test/compiler/ciReplay/TestSA.sh
index 6ea2c53a6cef784542f7cab82686aec5c0687f79..61d93652f2549391e7658771e438029d151a4625 100644
--- a/hotspot/test/compiler/ciReplay/TestSA.sh
+++ b/hotspot/test/compiler/ciReplay/TestSA.sh
@@ -26,6 +26,7 @@
 ##
 ## @test
 ## @bug 8011675
+## @ignore 8032226, 8031978
 ## @summary testing of ciReplay with using generated by SA replay.txt 
 ## @author igor.ignatyev@oracle.com
 ## @run shell TestSA.sh
diff --git a/hotspot/test/compiler/ciReplay/TestVM.sh b/hotspot/test/compiler/ciReplay/TestVM.sh
index e58d63e16faaa44eecdbb20ec8694f01bfd7d904..c972c607947da332ddb551ca3fc3480562b44b3d 100644
--- a/hotspot/test/compiler/ciReplay/TestVM.sh
+++ b/hotspot/test/compiler/ciReplay/TestVM.sh
@@ -26,6 +26,7 @@
 ##
 ## @test
 ## @bug 8011675
+## @ignore 8031978
 ## @summary testing of ciReplay with using generated by VM replay.txt 
 ## @author igor.ignatyev@oracle.com
 ## @run shell TestVM.sh
diff --git a/hotspot/test/compiler/ciReplay/TestVM_no_comp_level.sh b/hotspot/test/compiler/ciReplay/TestVM_no_comp_level.sh
index d961d42541dcebcc1bbc2212bad2893134b270b7..4d0ee773c44f274f32ebb36526392789dfaf2656 100644
--- a/hotspot/test/compiler/ciReplay/TestVM_no_comp_level.sh
+++ b/hotspot/test/compiler/ciReplay/TestVM_no_comp_level.sh
@@ -26,6 +26,7 @@
 ##
 ## @test
 ## @bug 8011675
+## @ignore 8031978
 ## @summary testing of ciReplay with using generated by VM replay.txt w/o comp_level
 ## @author igor.ignatyev@oracle.com
 ## @run shell TestVM_no_comp_level.sh
diff --git a/hotspot/test/compiler/tiered/NonTieredLevelsTest.java b/hotspot/test/compiler/tiered/NonTieredLevelsTest.java
index 13411a0dd733dff999044923cd2929613e7b2013..08321b872661c4f41fb82b49d8d79e4eb6b38598 100644
--- a/hotspot/test/compiler/tiered/NonTieredLevelsTest.java
+++ b/hotspot/test/compiler/tiered/NonTieredLevelsTest.java
@@ -25,6 +25,7 @@ import java.util.function.IntPredicate;
 
 /**
  * @test NonTieredLevelsTest
+ * @ignore 8046268
  * @library /testlibrary /testlibrary/whitebox /compiler/whitebox
  * @build NonTieredLevelsTest
  * @run main ClassFileInstaller sun.hotspot.WhiteBox
diff --git a/hotspot/test/compiler/tiered/TieredLevelsTest.java b/hotspot/test/compiler/tiered/TieredLevelsTest.java
index 9fb2254d0b54a8c3f3603c8ab5fa75bfa4c4b844..4b9a0a4a90689a99e235a8e1a35f749bce5e5301 100644
--- a/hotspot/test/compiler/tiered/TieredLevelsTest.java
+++ b/hotspot/test/compiler/tiered/TieredLevelsTest.java
@@ -23,6 +23,7 @@
 
 /**
  * @test TieredLevelsTest
+ * @ignore 8046268
  * @library /testlibrary /testlibrary/whitebox /compiler/whitebox
  * @build TieredLevelsTest
  * @run main ClassFileInstaller sun.hotspot.WhiteBox
diff --git a/hotspot/test/compiler/whitebox/ClearMethodStateTest.java b/hotspot/test/compiler/whitebox/ClearMethodStateTest.java
index 89fff68460ff8f4f2424e131ca3e098e39002ea9..195221658cf44396c02a7f6459c979dc6958edd5 100644
--- a/hotspot/test/compiler/whitebox/ClearMethodStateTest.java
+++ b/hotspot/test/compiler/whitebox/ClearMethodStateTest.java
@@ -25,6 +25,7 @@ import java.util.function.Function;
 
 /*
  * @test ClearMethodStateTest
+ * @ignore 8046268
  * @bug 8006683 8007288 8022832
  * @library /testlibrary /testlibrary/whitebox
  * @build ClearMethodStateTest
diff --git a/hotspot/test/compiler/whitebox/DeoptimizeAllTest.java b/hotspot/test/compiler/whitebox/DeoptimizeAllTest.java
index ea4e36400eb803a77f80f69349c12a45e7a5fde9..a5b9d794c66f5732209ad040a44b872354945469 100644
--- a/hotspot/test/compiler/whitebox/DeoptimizeAllTest.java
+++ b/hotspot/test/compiler/whitebox/DeoptimizeAllTest.java
@@ -23,6 +23,7 @@
 
 /*
  * @test DeoptimizeAllTest
+ * @ignore 8046268
  * @bug 8006683 8007288 8022832
  * @library /testlibrary /testlibrary/whitebox
  * @build DeoptimizeAllTest
diff --git a/hotspot/test/compiler/whitebox/DeoptimizeMethodTest.java b/hotspot/test/compiler/whitebox/DeoptimizeMethodTest.java
index 0b9ffd2d9dbcd6706851e18b3cde3cab4f2470f7..e257a1e5e25c6d8a0ae3a8c755ca7d9b685b69cb 100644
--- a/hotspot/test/compiler/whitebox/DeoptimizeMethodTest.java
+++ b/hotspot/test/compiler/whitebox/DeoptimizeMethodTest.java
@@ -23,6 +23,7 @@
 
 /*
  * @test DeoptimizeMethodTest
+ * @ignore 8046268
  * @bug 8006683 8007288 8022832
  * @library /testlibrary /testlibrary/whitebox
  * @build DeoptimizeMethodTest
diff --git a/hotspot/test/compiler/whitebox/EnqueueMethodForCompilationTest.java b/hotspot/test/compiler/whitebox/EnqueueMethodForCompilationTest.java
index d9139dd3674ad70e2416217d2b47b7dbd7184ac7..4acebb2b1233b1e9d5a32680d6cbf13c9f389933 100644
--- a/hotspot/test/compiler/whitebox/EnqueueMethodForCompilationTest.java
+++ b/hotspot/test/compiler/whitebox/EnqueueMethodForCompilationTest.java
@@ -23,6 +23,7 @@
 
 /*
  * @test EnqueueMethodForCompilationTest
+ * @ignore 8046268
  * @bug 8006683 8007288 8022832
  * @library /testlibrary /testlibrary/whitebox
  * @build EnqueueMethodForCompilationTest
diff --git a/hotspot/test/compiler/whitebox/GetNMethodTest.java b/hotspot/test/compiler/whitebox/GetNMethodTest.java
index bb95f01b99189648fafe8c19e9b9ea8020dad90d..9800f3a3eb3f888f8c9298a36e1938bd7980fd90 100644
--- a/hotspot/test/compiler/whitebox/GetNMethodTest.java
+++ b/hotspot/test/compiler/whitebox/GetNMethodTest.java
@@ -26,6 +26,7 @@ import sun.hotspot.code.NMethod;
 
 /*
  * @test GetNMethodTest
+ * @ignore 8046268
  * @bug 8038240
  * @library /testlibrary /testlibrary/whitebox
  * @build GetNMethodTest
diff --git a/hotspot/test/compiler/whitebox/MakeMethodNotCompilableTest.java b/hotspot/test/compiler/whitebox/MakeMethodNotCompilableTest.java
index d6586879778f96538092ac1dcded4a05a362cd00..604175c38eff597ccb12b80a5311a98f202542aa 100644
--- a/hotspot/test/compiler/whitebox/MakeMethodNotCompilableTest.java
+++ b/hotspot/test/compiler/whitebox/MakeMethodNotCompilableTest.java
@@ -23,6 +23,7 @@
 
 /*
  * @test MakeMethodNotCompilableTest
+ * @ignore 8046268
  * @bug 8012322 8006683 8007288 8022832
  * @library /testlibrary /testlibrary/whitebox
  * @build MakeMethodNotCompilableTest
diff --git a/hotspot/test/gc/g1/TestSummarizeRSetStatsTools.java b/hotspot/test/gc/g1/TestSummarizeRSetStatsTools.java
index 096a7c675b5486f6fecc528b8c4e47b7446911d5..1ab8322291b75ed56931e5c352a062cb141e814a 100644
--- a/hotspot/test/gc/g1/TestSummarizeRSetStatsTools.java
+++ b/hotspot/test/gc/g1/TestSummarizeRSetStatsTools.java
@@ -88,7 +88,6 @@ public class TestSummarizeRSetStatsTools {
         ArrayList<String> finalargs = new ArrayList<String>();
         String[] defaultArgs = new String[] {
             "-XX:+UseG1GC",
-            "-XX:+UseCompressedOops",
             "-Xmn4m",
             "-Xmx20m",
             "-XX:InitiatingHeapOccupancyPercent=100", // we don't want the additional GCs due to initial marking
diff --git a/hotspot/test/gc/logging/TestGCId.java b/hotspot/test/gc/logging/TestGCId.java
new file mode 100644
index 0000000000000000000000000000000000000000..98f9491467b4b3287c76c5698f15c72d05b8fb01
--- /dev/null
+++ b/hotspot/test/gc/logging/TestGCId.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2014, 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 TestGCId
+ * @bug 8043607
+ * @summary Ensure that the GCId is logged
+ * @key gc
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.ProcessTools;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+
+public class TestGCId {
+  public static void main(String[] args) throws Exception {
+    testGCId("UseParallelGC", "PrintGC");
+    testGCId("UseParallelGC", "PrintGCDetails");
+
+    testGCId("UseG1GC", "PrintGC");
+    testGCId("UseG1GC", "PrintGCDetails");
+
+    testGCId("UseConcMarkSweepGC", "PrintGC");
+    testGCId("UseConcMarkSweepGC", "PrintGCDetails");
+
+    testGCId("UseSerialGC", "PrintGC");
+    testGCId("UseSerialGC", "PrintGCDetails");
+  }
+
+  private static void verifyContainsGCIDs(OutputAnalyzer output) {
+    output.shouldMatch("^#0: \\[");
+    output.shouldMatch("^#1: \\[");
+    output.shouldHaveExitValue(0);
+  }
+
+  private static void verifyContainsNoGCIDs(OutputAnalyzer output) {
+    output.shouldNotMatch("^#[0-9]+: \\[");
+    output.shouldHaveExitValue(0);
+  }
+
+  private static void testGCId(String gcFlag, String logFlag) throws Exception {
+    // GCID logging enabled
+    ProcessBuilder pb_enabled =
+      ProcessTools.createJavaProcessBuilder("-XX:+" + gcFlag, "-XX:+" + logFlag, "-Xmx10M", "-XX:+PrintGCID", GCTest.class.getName());
+    verifyContainsGCIDs(new OutputAnalyzer(pb_enabled.start()));
+
+    // GCID logging disabled
+    ProcessBuilder pb_disabled =
+      ProcessTools.createJavaProcessBuilder("-XX:+" + gcFlag, "-XX:+" + logFlag, "-Xmx10M", "-XX:-PrintGCID", GCTest.class.getName());
+    verifyContainsNoGCIDs(new OutputAnalyzer(pb_disabled.start()));
+
+    // GCID logging default
+    ProcessBuilder pb_default =
+      ProcessTools.createJavaProcessBuilder("-XX:+" + gcFlag, "-XX:+" + logFlag, "-Xmx10M", GCTest.class.getName());
+    verifyContainsGCIDs(new OutputAnalyzer(pb_default.start()));
+  }
+
+  static class GCTest {
+    private static byte[] garbage;
+    public static void main(String [] args) {
+      System.out.println("Creating garbage");
+      // create 128MB of garbage. This should result in at least one GC
+      for (int i = 0; i < 1024; i++) {
+        garbage = new byte[128 * 1024];
+      }
+      // do a system gc to get one more gc
+      System.gc();
+      System.out.println("Done");
+    }
+  }
+}
diff --git a/hotspot/test/runtime/8001071/Test8001071.sh b/hotspot/test/runtime/8001071/Test8001071.sh
deleted file mode 100644
index 5fb4a7f9965b3ab26dcb84866ce8aa003d8f3b5d..0000000000000000000000000000000000000000
--- a/hotspot/test/runtime/8001071/Test8001071.sh
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/bin/sh
-
-# Copyright (c) 2013, 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 8001071
-## @summary Add simple range check into VM implemenation of Unsafe access methods 
-## @compile Test8001071.java
-## @run shell Test8001071.sh
-## @author filipp.zhinkin@oracle.com
-
-VERSION=`${TESTJAVA}/bin/java ${TESTVMOPTS} -version 2>&1`
-
-if [ -n "`echo $VERSION | grep debug`" -o -n "`echo $VERSION | grep jvmg`" ]; then
-        echo "Build type check passed"
-        echo "Continue testing"
-else
-        echo "Fastdebug build is required for this test"
-        exit 0
-fi
-
-${TESTJAVA}/bin/java -cp ${TESTCLASSES} ${TESTVMOPTS} Test8001071 2>&1
-
-HS_ERR_FILE=hs_err_pid*.log
-
-if [ ! -f $HS_ERR_FILE ]
-then
-    echo "hs_err_pid log file was not found"
-    echo "Test failed"
-    exit 1
-fi
-
-grep "assert(byte_offset < p_size) failed: Unsafe access: offset.*> object's size.*" $HS_ERR_FILE
-
-if [ "0" = "$?" ];
-then
-    echo "Range check assertion failed as expected"
-    echo "Test passed"
-    exit 0
-else
-    echo "Range check assertion was not failed"
-    echo "Test failed"
-    exit 1
-fi
diff --git a/hotspot/test/runtime/CDSCompressedKPtrs/XShareAuto.java b/hotspot/test/runtime/CDSCompressedKPtrs/XShareAuto.java
index 73f0c80431253daaf60b38cffcd43ece2bc05b14..458a781de806a317cb77c3806c77836b2353a940 100644
--- a/hotspot/test/runtime/CDSCompressedKPtrs/XShareAuto.java
+++ b/hotspot/test/runtime/CDSCompressedKPtrs/XShareAuto.java
@@ -44,8 +44,16 @@ public class XShareAuto {
             "-server", "-XX:+UnlockDiagnosticVMOptions",
             "-XX:SharedArchiveFile=./sample.jsa", "-version");
         output = new OutputAnalyzer(pb.start());
-        output.shouldNotContain("sharing");
-        output.shouldHaveExitValue(0);
+        // We asked for server but it could be aliased to something else
+        if (output.getOutput().contains("Server VM")) {
+            // In server case we don't expect to see sharing flag
+            output.shouldNotContain("sharing");
+            output.shouldHaveExitValue(0);
+        }
+        else {
+            System.out.println("Skipping test - no Server VM available");
+            return;
+        }
 
         pb = ProcessTools.createJavaProcessBuilder(
             "-server", "-Xshare:auto", "-XX:+UnlockDiagnosticVMOptions",
diff --git a/hotspot/test/runtime/Unsafe/RangeCheck.java b/hotspot/test/runtime/Unsafe/RangeCheck.java
new file mode 100644
index 0000000000000000000000000000000000000000..4d4ea2e048ae96d27278c1f3eb7286b0829ff9b3
--- /dev/null
+++ b/hotspot/test/runtime/Unsafe/RangeCheck.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2014, 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 8001071
+ * @summary Add simple range check into VM implemenation of Unsafe access methods
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+import sun.misc.Unsafe;
+
+public class RangeCheck {
+
+    public static void main(String args[]) throws Exception {
+        if (!Platform.isDebugBuild()) {
+            System.out.println("Testing assert which requires a debug build. Passing silently.");
+            return;
+        }
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+                true,
+                "-Xmx32m",
+                "-XX:-TransmitErrorReport",
+                "-XX:-InlineUnsafeOps", // The compiler intrinsics doesn't have the assert
+                DummyClassWithMainRangeCheck.class.getName());
+
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldMatch("assert\\(byte_offset < p_size\\) failed: Unsafe access: offset \\d+ > object's size \\d+");
+    }
+
+    public static class DummyClassWithMainRangeCheck {
+        public static void main(String args[]) throws Exception {
+            Unsafe unsafe = Utils.getUnsafe();
+            unsafe.getObject(new DummyClassWithMainRangeCheck(), Short.MAX_VALUE);
+        }
+    }
+}
diff --git a/hotspot/test/runtime/memory/ReadFromNoaccessArea.java b/hotspot/test/runtime/memory/ReadFromNoaccessArea.java
index 1078dd2e4eadd3bafd2b89660c0a5efbb44a7c55..484240287ceb44da3122dd7185090ad5f505a00e 100644
--- a/hotspot/test/runtime/memory/ReadFromNoaccessArea.java
+++ b/hotspot/test/runtime/memory/ReadFromNoaccessArea.java
@@ -47,6 +47,7 @@ public class ReadFromNoaccessArea {
           "-XX:+WhiteBoxAPI",
           "-XX:+UseCompressedOops",
           "-XX:HeapBaseMinAddress=33G",
+          "-Xmx32m",
           DummyClassWithMainTryingToReadFromNoaccessArea.class.getName());
 
     OutputAnalyzer output = new OutputAnalyzer(pb.start());
diff --git a/hotspot/test/runtime/memory/ReserveMemory.java b/hotspot/test/runtime/memory/ReserveMemory.java
index 9e37d52ccdae092044b19c9324ec631dac943cfd..3a65ca605c210203f524ddf73723548aa3502a53 100644
--- a/hotspot/test/runtime/memory/ReserveMemory.java
+++ b/hotspot/test/runtime/memory/ReserveMemory.java
@@ -57,6 +57,7 @@ public class ReserveMemory {
           "-XX:+UnlockDiagnosticVMOptions",
           "-XX:+WhiteBoxAPI",
           "-XX:-TransmitErrorReport",
+          "-Xmx32m",
           "ReserveMemory",
           "test");
 
diff --git a/hotspot/test/runtime/verifier/TestANewArray.java b/hotspot/test/runtime/verifier/TestANewArray.java
new file mode 100644
index 0000000000000000000000000000000000000000..e8f58da2a41799b1d0b832559a11661587f39402
--- /dev/null
+++ b/hotspot/test/runtime/verifier/TestANewArray.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+import java.io.File;
+import java.io.FileOutputStream;
+
+import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.MethodVisitor;
+import static jdk.internal.org.objectweb.asm.Opcodes.*;
+
+import com.oracle.java.testlibrary.*;
+
+/*
+ * @test
+ * @summary Test that anewarray bytecode is valid only if it specifies 255 or fewer dimensions.
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestANewArray.java
+ * @run main/othervm TestANewArray 49
+ * @run main/othervm TestANewArray 50
+ * @run main/othervm TestANewArray 51
+ * @run main/othervm TestANewArray 52
+ */
+
+/*
+ * Testing anewarray instruction with 254, 255 & 264 dimensions to verify JVMS 8,
+ * Section 4.9.1, Static Constraints that states the following:
+ *
+ * "No anewarray instruction may be used to create an array of more than 255 dimensions."
+ *
+ */
+
+public class TestANewArray {
+
+    static String classCName = null; // the generated class name
+
+    static final int test_Dimension_254 = 254; // should always pass
+    static final int test_Dimension_255 = 255; // should always pass, except for cfv 49
+    static final int test_Dimension_264 = 264; // should always fail
+
+    static final String array_Dimension_254 = genArrayDim(test_Dimension_254);
+    static final String array_Dimension_255 = genArrayDim(test_Dimension_255);
+    static final String array_Dimension_264 = genArrayDim(test_Dimension_264);
+
+    public static void main(String... args) throws Exception {
+        int cfv = Integer.parseInt(args[0]);
+
+        // 254 array dimensions
+        byte[] classFile_254 = dumpClassFile(cfv, test_Dimension_254, array_Dimension_254);
+        writeClassFileFromByteArray(classFile_254);
+        System.err.println("Running with cfv: " + cfv + ", test_Dimension_254");
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, "-verify", "-cp", ".",  classCName);
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldNotContain("java.lang.VerifyError");
+        output.shouldHaveExitValue(0);
+
+        // 255 array dimensions
+        byte[] classFile_255 = dumpClassFile(cfv, test_Dimension_255, array_Dimension_255);
+        writeClassFileFromByteArray(classFile_255);
+        System.err.println("Running with cfv: " + cfv + ", test_Dimension_255");
+        pb = ProcessTools.createJavaProcessBuilder(true, "-verify", "-cp", ".",  classCName);
+        output = new OutputAnalyzer(pb.start());
+        if (cfv == 49) {
+            // The type-inferencing verifier used for <=49.0 ClassFiles detects an anewarray instruction
+            // with exactly 255 dimensions and incorrectly issues the "Array with too many dimensions" VerifyError.
+            output.shouldContain("Array with too many dimensions");
+            output.shouldHaveExitValue(1);
+        } else {
+            // 255 dimensions should always pass, except for cfv 49
+            output.shouldNotContain("java.lang.VerifyError");
+            output.shouldNotContain("java.lang.ClassFormatError");
+            output.shouldHaveExitValue(0);
+        }
+
+        // 264 array dimensions
+        byte[] classFile_264 = dumpClassFile(cfv, test_Dimension_264, array_Dimension_264);
+        writeClassFileFromByteArray(classFile_264);
+        System.err.println("Running with cfv: " + cfv + ", test_Dimension_264");
+        pb = ProcessTools.createJavaProcessBuilder(true, "-verify", "-cp", ".",  classCName);
+        output = new OutputAnalyzer(pb.start());
+        output.shouldContain("java.lang.ClassFormatError");
+        output.shouldHaveExitValue(1);
+    }
+
+    public static byte[] dumpClassFile(int cfv, int testDimension264, String arrayDim) throws Exception {
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
+        MethodVisitor mv;
+
+        classCName = "classCName_" + cfv + "_" + testDimension264;
+
+        cw.visit(cfv, ACC_PUBLIC + ACC_SUPER, classCName, null, "java/lang/Object", null);
+        {
+            mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
+            mv.visitCode();
+            mv.visitVarInsn(ALOAD, 0);
+            mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
+            mv.visitInsn(RETURN);
+            mv.visitMaxs(1, 1);
+            mv.visitEnd();
+        }
+        {   // classCName main method
+            mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
+            mv.visitCode();
+            mv.visitIntInsn(BIPUSH, 1);
+            mv.visitTypeInsn(ANEWARRAY, arrayDim); // Test ANEWARRAY bytecode with various dimensions
+            mv.visitInsn(RETURN);
+            mv.visitMaxs(2, 2);
+            mv.visitEnd();
+        }
+        cw.visitEnd();
+        return cw.toByteArray();
+    }
+
+    public static FileOutputStream writeClassFileFromByteArray(byte[] classFileByteArray) throws Exception {
+        FileOutputStream fos = new FileOutputStream(new File(classCName + ".class"));
+        fos.write(classFileByteArray);
+        fos.close();
+        return fos;
+    }
+
+    private static String genArrayDim(int testDim) {
+        StringBuilder array_Dimension = new StringBuilder();
+        for (int i = 0; i < testDim; i++)
+        {
+            array_Dimension.append("[");
+        }
+        return array_Dimension.append("Ljava/lang/Object;").toString();
+    }
+}
diff --git a/jdk/.hgtags b/jdk/.hgtags
index 38493c04e7fbef3ae71f3675122c990ccfc1fb44..bfebe8ade0657b3b247a59d2989e5d6f13e2a15a 100644
--- a/jdk/.hgtags
+++ b/jdk/.hgtags
@@ -264,3 +264,4 @@ fd8e675f141b9bdb2f46d1ae8251f4ee3a895d64 jdk9-b17
 27561aede285c25a3e9ed8bf8918234ad3bb81e3 jdk9-b19
 f87c5be90e01a7ffb47947108eb3e0b0b1920880 jdk9-b20
 2df45ac1bf491278f38c12e0dfbeebadb6c54c8c jdk9-b21
+85bcf0f99edc08873614afbe5a5563e13ce13c83 jdk9-b22
diff --git a/jdk/make/CopyFiles.gmk b/jdk/make/CopyFiles.gmk
index 396f2534317324b1007b787d551c24a237634195..acab25412565f0e92889d1827b76c2f75e0f3b7d 100644
--- a/jdk/make/CopyFiles.gmk
+++ b/jdk/make/CopyFiles.gmk
@@ -407,16 +407,11 @@ COPY_FILES += $(CACERTS_DST)
 
 ##########################################################################################
 
-BLACKLISTED_CERTS_SRC := $(JDK_TOPDIR)/src/share/lib/security/blacklisted.certs
-BLACKLISTED_CERTS_DST := $(JDK_OUTPUTDIR)/lib/security/blacklisted.certs
-
 ifndef OPENJDK
 
   BLACKLIST_SRC := $(JDK_TOPDIR)/src/closed/share/lib/security/blacklist
   BLACKLIST_DST := $(JDK_OUTPUTDIR)/lib/security/blacklist
 
-  BLACKLISTED_CERTS_SRC += $(wildcard $(JDK_TOPDIR)/src/closed/share/lib/security/blacklisted.certs)
-
   TRUSTEDLIBS_SRC := $(JDK_TOPDIR)/src/closed/share/lib/security/trusted.libraries
   TRUSTEDLIBS_DST := $(JDK_OUTPUTDIR)/lib/security/trusted.libraries
 
@@ -432,20 +427,6 @@ ifndef OPENJDK
 
 endif
 
-$(BLACKLISTED_CERTS_DST): $(BLACKLISTED_CERTS_SRC)
-	$(MKDIR) -p $(@D)
-	$(CAT) $^ | $(SED) '/^$$/d' | $(SORT) | $(UNIQ) > $@.tmp
-	$(GREP) -i Algorithm $@.tmp > $@
-	if [ `$(SED) -n -e "$$=" $@` != 1 ]; then \
-	   $(ECHO) "Different algorithms defined in $^"; \
-	   $(RM) $@ $@.tmp; \
-	   false; \
-	fi
-	$(GREP) -iv Algorithm $@.tmp >> $@
-	$(RM) $@.tmp
-
-COPY_FILES += $(BLACKLISTED_CERTS_DST)
-
 ##########################################################################################
 
 ifndef OPENJDK
diff --git a/jdk/make/GenerateData.gmk b/jdk/make/GenerateData.gmk
index 437dd0b1d38ef1bf117e4ed740aff506e9278fc3..8228f9178008c569a3bae9041fd98dbd277dc878 100644
--- a/jdk/make/GenerateData.gmk
+++ b/jdk/make/GenerateData.gmk
@@ -50,6 +50,9 @@ GENDATA += $(GENDATA_TZDB)
 include gendata/GendataHtml32dtd.gmk
 GENDATA += $(GENDATA_HTML32DTD)
 
+include gendata/GendataBlacklistedCerts.gmk
+GENDATA += $(GENDATA_BLACKLISTED_CERTS)
+
 ##########################################################################################
 
 GENDATA_UNINAME := $(JDK_OUTPUTDIR)/classes/java/lang/uniName.dat
diff --git a/jdk/make/Tools.gmk b/jdk/make/Tools.gmk
index d223f4afa624f01106084c76cfcf9c6f4a5e8810..0f78190949015cddf50b688a194fd4c60c02eef4 100644
--- a/jdk/make/Tools.gmk
+++ b/jdk/make/Tools.gmk
@@ -87,6 +87,9 @@ TOOL_HASHER = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
 TOOL_TZDB = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.tzdb.TzdbZoneRulesCompiler
 
+TOOL_BLACKLISTED_CERTS = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
+    build.tools.blacklistedcertsconverter.BlacklistedCertsConverter
+
 
 # TODO: There are references to the jdwpgen.jar in jdk/make/netbeans/jdwpgen/build.xml
 # and nbproject/project.properties in the same dir. Needs to be looked at.
diff --git a/jdk/src/share/lib/security/blacklisted.certs.pem b/jdk/make/data/blacklistedcertsconverter/blacklisted.certs.pem
similarity index 99%
rename from jdk/src/share/lib/security/blacklisted.certs.pem
rename to jdk/make/data/blacklistedcertsconverter/blacklisted.certs.pem
index f44a69853527ae50057a0d2fa6c654536b9901d3..db1c077ccb0469d6b9fbb2897e4a5b6efbb3e186 100644
--- a/jdk/src/share/lib/security/blacklisted.certs.pem
+++ b/jdk/make/data/blacklistedcertsconverter/blacklisted.certs.pem
@@ -1,3 +1,9 @@
+#! java BlacklistedCertsConverter SHA-256
+
+# The line above must be the first line of the blacklisted.certs.pem
+# file inside src/share/lib/security/. It will be ignored if added in
+# src/closed/share/lib/security/blacklisted.certs.pem.
+
 // Subject: CN=Digisign Server ID (Enrich),
 //          OU=457608-K,
 //          O=Digicert Sdn. Bhd.,
diff --git a/jdk/make/gendata/GendataBlacklistedCerts.gmk b/jdk/make/gendata/GendataBlacklistedCerts.gmk
new file mode 100644
index 0000000000000000000000000000000000000000..ab62ca69ef968163536a5f3fe8abc6a4fdc0d6a0
--- /dev/null
+++ b/jdk/make/gendata/GendataBlacklistedCerts.gmk
@@ -0,0 +1,36 @@
+#
+# Copyright (c) 2014, 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.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# 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.
+#
+
+GENDATA_BLACKLISTED_CERTS_SRC := $(JDK_TOPDIR)/make/data/blacklistedcertsconverter/blacklisted.certs.pem
+GENDATA_BLACKLISTED_CERTS := $(JDK_OUTPUTDIR)/lib/security/blacklisted.certs
+
+ifndef OPENJDK
+	GENDATA_BLACKLISTED_CERTS_SRC += $(wildcard $(JDK_TOPDIR)/make/closed/data/blacklistedcertsconverter/blacklisted.certs.pem)
+endif
+ 
+$(GENDATA_BLACKLISTED_CERTS): $(BUILD_TOOLS) $(GENDATA_BLACKLISTED_CERTS_SRC)
+	$(ECHO) "Generating blacklisted certs"
+	$(MKDIR) -p $(@D)
+	($(CAT) $(GENDATA_BLACKLISTED_CERTS_SRC) | $(TOOL_BLACKLISTED_CERTS) > $@) || exit 1
diff --git a/jdk/src/share/lib/security/BlacklistedCertsConverter.java b/jdk/make/src/classes/build/tools/blacklistedcertsconverter/BlacklistedCertsConverter.java
similarity index 56%
rename from jdk/src/share/lib/security/BlacklistedCertsConverter.java
rename to jdk/make/src/classes/build/tools/blacklistedcertsconverter/BlacklistedCertsConverter.java
index 65a88f00a2e45fcc90265684b3c6394edb05f398..9f8ce873c574b706b6bf82d21cbe56a983a10da2 100644
--- a/jdk/src/share/lib/security/BlacklistedCertsConverter.java
+++ b/jdk/make/src/classes/build/tools/blacklistedcertsconverter/BlacklistedCertsConverter.java
@@ -21,37 +21,65 @@
  * questions.
  */
 
+package build.tools.blacklistedcertsconverter;
+
 import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
 import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.util.Collection;
+import java.util.Set;
+import java.util.TreeSet;
+
 
 /**
- * This is the tool to convert blacklisted.certs.pem to blacklisted.certs.
- * Every time a new blacklisted certs is added, please append the PEM format
- * to the end of blacklisted.certs.pem (with proper comments) and then use
- * this tool to generate an updated blacklisted.certs. Make sure to include
- * changes to both in a changeset.
+ * Converts blacklisted.certs.pem from System.in to blacklisted.certs in
+ * System.out. The input must start with a #! line including the fingerprint
+ * algorithm. The output is sorted and unique.
  */
 public class BlacklistedCertsConverter {
+
     public static void main(String[] args) throws Exception {
-        if (args.length == 0) {
-            System.out.println("Usage: java BlacklistedCertsConverter SHA-256" +
-                    " < blacklisted.certs.pem > blacklisted.certs");
-            System.exit(1);
+
+        byte[] pattern = "#! java BlacklistedCertsConverter ".getBytes();
+        String mdAlg = "";
+
+        for (int i=0; ; i++) {
+            int n = System.in.read();
+            if (n < 0) {
+                throw new Exception("Unexpected EOF");
+            }
+            if (i < pattern.length) {
+                if (n != pattern[i]) {
+                    throw new Exception("The first line must start with \""
+                            + new String(pattern) + "\"");
+                }
+            } else if (i < pattern.length + 100) {
+                if (n < 32) {
+                    break;
+                } else {
+                    mdAlg = mdAlg + String.format("%c", n);
+                }
+            }
         }
-        String mdAlg = args[0];
+
+        mdAlg = mdAlg.trim();
+        System.out.println("Algorithm=" + mdAlg);
+
         CertificateFactory cf = CertificateFactory.getInstance("X.509");
         Collection<? extends Certificate> certs
                 = cf.generateCertificates(System.in);
-        System.out.println("Algorithm=" + mdAlg);
+
+        // Output sorted so that it's easy to locate an entry.
+        Set<String> fingerprints = new TreeSet<>();
         for (Certificate cert: certs) {
-            System.out.println(
+            fingerprints.add(
                     getCertificateFingerPrint(mdAlg, (X509Certificate)cert));
         }
+
+        for (String s: fingerprints) {
+            System.out.println(s);
+        }
     }
 
     /**
@@ -69,21 +97,15 @@ public class BlacklistedCertsConverter {
     /**
      * Gets the requested finger print of the certificate.
      */
-    private static String getCertificateFingerPrint(String mdAlg,
-                                                    X509Certificate cert) {
-        String fingerPrint = "";
-        try {
-            byte[] encCertInfo = cert.getEncoded();
-            MessageDigest md = MessageDigest.getInstance(mdAlg);
-            byte[] digest = md.digest(encCertInfo);
-            StringBuffer buf = new StringBuffer();
-            for (int i = 0; i < digest.length; i++) {
-                byte2hex(digest[i], buf);
-            }
-            fingerPrint = buf.toString();
-        } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
-            // ignored
+    private static String getCertificateFingerPrint(
+            String mdAlg, X509Certificate cert) throws Exception {
+        byte[] encCertInfo = cert.getEncoded();
+        MessageDigest md = MessageDigest.getInstance(mdAlg);
+        byte[] digest = md.digest(encCertInfo);
+        StringBuffer buf = new StringBuffer();
+        for (int i = 0; i < digest.length; i++) {
+            byte2hex(digest[i], buf);
         }
-        return fingerPrint;
+        return buf.toString();
     }
 }
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/JceKeyStore.java b/jdk/src/share/classes/com/sun/crypto/provider/JceKeyStore.java
index 5d48553c25a67960b9a4e28431dd07ceed6167e5..cbbc54e42e127d878f685f57ab3f0b3a80a3f07c 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/JceKeyStore.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/JceKeyStore.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, 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
@@ -107,7 +107,7 @@ public final class JceKeyStore extends KeyStoreSpi {
     {
         Key key = null;
 
-        Object entry = entries.get(alias.toLowerCase());
+        Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
 
         if (!((entry instanceof PrivateKeyEntry) ||
               (entry instanceof SecretKeyEntry))) {
@@ -150,7 +150,7 @@ public final class JceKeyStore extends KeyStoreSpi {
     {
         Certificate[] chain = null;
 
-        Object entry = entries.get(alias.toLowerCase());
+        Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
 
         if ((entry instanceof PrivateKeyEntry)
             && (((PrivateKeyEntry)entry).chain != null)) {
@@ -178,7 +178,7 @@ public final class JceKeyStore extends KeyStoreSpi {
     public Certificate engineGetCertificate(String alias) {
         Certificate cert = null;
 
-        Object entry = entries.get(alias.toLowerCase());
+        Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
 
         if (entry != null) {
             if (entry instanceof TrustedCertEntry) {
@@ -203,7 +203,7 @@ public final class JceKeyStore extends KeyStoreSpi {
     public Date engineGetCreationDate(String alias) {
         Date date = null;
 
-        Object entry = entries.get(alias.toLowerCase());
+        Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
 
         if (entry != null) {
             // We have to create a new instance of java.util.Date because
@@ -266,7 +266,7 @@ public final class JceKeyStore extends KeyStoreSpi {
                     }
 
                     // store the entry
-                    entries.put(alias.toLowerCase(), entry);
+                    entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
 
                 } else {
                     SecretKeyEntry entry = new SecretKeyEntry();
@@ -274,7 +274,7 @@ public final class JceKeyStore extends KeyStoreSpi {
 
                     // seal and store the key
                     entry.sealedKey = keyProtector.seal(key);
-                    entries.put(alias.toLowerCase(), entry);
+                    entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
                 }
 
             } catch (Exception e) {
@@ -322,7 +322,7 @@ public final class JceKeyStore extends KeyStoreSpi {
                 entry.chain = null;
             }
 
-            entries.put(alias.toLowerCase(), entry);
+            entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
         }
     }
 
@@ -345,7 +345,7 @@ public final class JceKeyStore extends KeyStoreSpi {
     {
         synchronized(entries) {
 
-            Object entry = entries.get(alias.toLowerCase());
+            Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
             if (entry != null) {
                 if (entry instanceof PrivateKeyEntry) {
                     throw new KeyStoreException("Cannot overwrite own "
@@ -358,7 +358,7 @@ public final class JceKeyStore extends KeyStoreSpi {
             TrustedCertEntry trustedCertEntry = new TrustedCertEntry();
             trustedCertEntry.cert = cert;
             trustedCertEntry.date = new Date();
-            entries.put(alias.toLowerCase(), trustedCertEntry);
+            entries.put(alias.toLowerCase(Locale.ENGLISH), trustedCertEntry);
         }
     }
 
@@ -373,7 +373,7 @@ public final class JceKeyStore extends KeyStoreSpi {
         throws KeyStoreException
     {
         synchronized(entries) {
-            entries.remove(alias.toLowerCase());
+            entries.remove(alias.toLowerCase(Locale.ENGLISH));
         }
     }
 
@@ -394,7 +394,7 @@ public final class JceKeyStore extends KeyStoreSpi {
      * @return true if the alias exists, false otherwise
      */
     public boolean engineContainsAlias(String alias) {
-        return entries.containsKey(alias.toLowerCase());
+        return entries.containsKey(alias.toLowerCase(Locale.ENGLISH));
     }
 
     /**
@@ -416,7 +416,7 @@ public final class JceKeyStore extends KeyStoreSpi {
     public boolean engineIsKeyEntry(String alias) {
         boolean isKey = false;
 
-        Object entry = entries.get(alias.toLowerCase());
+        Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
         if ((entry instanceof PrivateKeyEntry)
             || (entry instanceof SecretKeyEntry)) {
             isKey = true;
@@ -434,7 +434,7 @@ public final class JceKeyStore extends KeyStoreSpi {
      */
     public boolean engineIsCertificateEntry(String alias) {
         boolean isCert = false;
-        Object entry = entries.get(alias.toLowerCase());
+        Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
         if (entry instanceof TrustedCertEntry) {
             isCert = true;
         }
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/PBEKey.java b/jdk/src/share/classes/com/sun/crypto/provider/PBEKey.java
index d954d0fe6a5666164c5ac770502f824ef6e2cd72..10ba5cb79f68eb7a40c02a971fea66670dd3e108 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/PBEKey.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PBEKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -27,6 +27,7 @@ package com.sun.crypto.provider;
 
 import java.security.KeyRep;
 import java.security.spec.InvalidKeySpecException;
+import java.util.Locale;
 import javax.crypto.SecretKey;
 import javax.crypto.spec.PBEKeySpec;
 
@@ -91,7 +92,7 @@ final class PBEKey implements SecretKey {
         for (int i = 1; i < this.key.length; i++) {
             retval += this.key[i] * i;
         }
-        return(retval ^= getAlgorithm().toLowerCase().hashCode());
+        return(retval ^= getAlgorithm().toLowerCase(Locale.ENGLISH).hashCode());
     }
 
     public boolean equals(Object obj) {
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/PBEKeyFactory.java b/jdk/src/share/classes/com/sun/crypto/provider/PBEKeyFactory.java
index 26dd0867c951d4f06ab371321adf7bf02fab7f83..0c87971876f2e52eae22761d30dbd15c23810f42 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/PBEKeyFactory.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PBEKeyFactory.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -32,6 +32,7 @@ import javax.crypto.SecretKey;
 import javax.crypto.SecretKeyFactorySpi;
 import javax.crypto.spec.PBEKeySpec;
 import java.util.HashSet;
+import java.util.Locale;
 
 /**
  * This class implements a key factory for PBE keys according to PKCS#5,
@@ -56,24 +57,24 @@ abstract class PBEKeyFactory extends SecretKeyFactorySpi {
 
     static {
         validTypes = new HashSet<String>(17);
-        validTypes.add("PBEWithMD5AndDES".toUpperCase());
-        validTypes.add("PBEWithSHA1AndDESede".toUpperCase());
-        validTypes.add("PBEWithSHA1AndRC2_40".toUpperCase());
-        validTypes.add("PBEWithSHA1AndRC2_128".toUpperCase());
-        validTypes.add("PBEWithSHA1AndRC4_40".toUpperCase());
-        validTypes.add("PBEWithSHA1AndRC4_128".toUpperCase());
+        validTypes.add("PBEWithMD5AndDES".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithSHA1AndDESede".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithSHA1AndRC2_40".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithSHA1AndRC2_128".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithSHA1AndRC4_40".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithSHA1AndRC4_128".toUpperCase(Locale.ENGLISH));
         // Proprietary algorithm.
-        validTypes.add("PBEWithMD5AndTripleDES".toUpperCase());
-        validTypes.add("PBEWithHmacSHA1AndAES_128".toUpperCase());
-        validTypes.add("PBEWithHmacSHA224AndAES_128".toUpperCase());
-        validTypes.add("PBEWithHmacSHA256AndAES_128".toUpperCase());
-        validTypes.add("PBEWithHmacSHA384AndAES_128".toUpperCase());
-        validTypes.add("PBEWithHmacSHA512AndAES_128".toUpperCase());
-        validTypes.add("PBEWithHmacSHA1AndAES_256".toUpperCase());
-        validTypes.add("PBEWithHmacSHA224AndAES_256".toUpperCase());
-        validTypes.add("PBEWithHmacSHA256AndAES_256".toUpperCase());
-        validTypes.add("PBEWithHmacSHA384AndAES_256".toUpperCase());
-        validTypes.add("PBEWithHmacSHA512AndAES_256".toUpperCase());
+        validTypes.add("PBEWithMD5AndTripleDES".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA1AndAES_128".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA224AndAES_128".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA256AndAES_128".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA384AndAES_128".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA512AndAES_128".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA1AndAES_256".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA224AndAES_256".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA256AndAES_256".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA384AndAES_256".toUpperCase(Locale.ENGLISH));
+        validTypes.add("PBEWithHmacSHA512AndAES_256".toUpperCase(Locale.ENGLISH));
     }
 
     public static final class PBEWithMD5AndDES
@@ -237,7 +238,7 @@ abstract class PBEKeyFactory extends SecretKeyFactorySpi {
     protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
         throws InvalidKeySpecException {
         if ((key instanceof SecretKey)
-            && (validTypes.contains(key.getAlgorithm().toUpperCase()))
+            && (validTypes.contains(key.getAlgorithm().toUpperCase(Locale.ENGLISH)))
             && (key.getFormat().equalsIgnoreCase("RAW"))) {
 
             // Check if requested key spec is amongst the valid ones
@@ -279,7 +280,7 @@ abstract class PBEKeyFactory extends SecretKeyFactorySpi {
     {
         try {
             if ((key != null) &&
-                (validTypes.contains(key.getAlgorithm().toUpperCase())) &&
+                (validTypes.contains(key.getAlgorithm().toUpperCase(Locale.ENGLISH))) &&
                 (key.getFormat().equalsIgnoreCase("RAW"))) {
 
                 // Check if key originates from this factory
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java b/jdk/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java
index ec3bd3e79923d8405ba56918013e1a31705a93c7..16756fbe5e06a0ca48f1da6fee484ab7ed5eb55b 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, 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,6 +30,7 @@ import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
 import java.nio.charset.Charset;
 import java.util.Arrays;
+import java.util.Locale;
 import java.security.KeyRep;
 import java.security.GeneralSecurityException;
 import java.security.NoSuchAlgorithmException;
@@ -143,7 +144,7 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey {
                 @Override
                 public int hashCode() {
                     return Arrays.hashCode(password) * 41 +
-                            prf.getAlgorithm().toLowerCase().hashCode();
+                      prf.getAlgorithm().toLowerCase(Locale.ENGLISH).hashCode();
                 }
                 @Override
                 public boolean equals(Object obj) {
@@ -221,7 +222,7 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey {
         for (int i = 1; i < this.key.length; i++) {
             retval += this.key[i] * i;
         }
-        return(retval ^= getAlgorithm().toLowerCase().hashCode());
+        return(retval ^= getAlgorithm().toLowerCase(Locale.ENGLISH).hashCode());
     }
 
     public boolean equals(Object obj) {
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java
index d41c94480e9aa383e2b7c5ab5c3ff5aa6ac16ed1..c5a957ce6d76a375f2b482353fe5f362d3d2f84d 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java
@@ -111,6 +111,7 @@ public final class Connection implements Runnable {
 
     private static final boolean debug = false;
     private static final int dump = 0; // > 0 r, > 1 rw
+    public static final long DEFAULT_READ_TIMEOUT_MILLIS = 15 * 1000; // 15 second timeout;
 
 
     final private Thread worker;    // Initialized in constructor
@@ -460,7 +461,7 @@ public final class Connection implements Runnable {
                             // available
                             ldr.wait(readTimeout);
                         } else {
-                            ldr.wait(15 * 1000); // 15 second timeout
+                            ldr.wait(DEFAULT_READ_TIMEOUT_MILLIS);
                         }
                         waited = true;
                     } else {
diff --git a/jdk/src/share/classes/com/sun/security/ntlm/Client.java b/jdk/src/share/classes/com/sun/security/ntlm/Client.java
index ba3e90c3858a360d69d4ee07c324f94bf828ed2d..9aacd433793c9e1ba3279e63e47b50015894b970 100644
--- a/jdk/src/share/classes/com/sun/security/ntlm/Client.java
+++ b/jdk/src/share/classes/com/sun/security/ntlm/Client.java
@@ -46,7 +46,7 @@ public final class Client extends NTLM {
     final private String hostname;
     final private String username;
 
-    private String domain;    // might be updated by Type 2 msg
+    private String domain;
     private byte[] pw1, pw2;
 
     /**
@@ -82,7 +82,7 @@ public final class Client extends NTLM {
         }
         this.hostname = hostname;
         this.username = username;
-        this.domain = domain;
+        this.domain = domain == null ? "" : domain;
         this.pw1 = getP1(password);
         this.pw2 = getP2(password);
         debug("NTLM Client: (h,u,t,version(v)) = (%s,%s,%s,%s(%s))\n",
@@ -95,19 +95,13 @@ public final class Client extends NTLM {
      */
     public byte[] type1() {
         Writer p = new Writer(1, 32);
-        int flags = 0x8203;
-        if (hostname != null) {
-            flags |= 0x2000;
-        }
-        if (domain != null) {
-            flags |= 0x1000;
-        }
+        // Negotiate always sign, Negotiate NTLM,
+        // Request Target, Negotiate OEM, Negotiate unicode
+        int flags = 0x8207;
         if (v != Version.NTLM) {
             flags |= 0x80000;
         }
         p.writeInt(12, flags);
-        p.writeSecurityBuffer(24, hostname, false);
-        p.writeSecurityBuffer(16, domain, false);
         debug("NTLM Client: Type 1 created\n");
         debug(p.getBytes());
         return p.getBytes();
@@ -133,13 +127,10 @@ public final class Client extends NTLM {
         byte[] challenge = r.readBytes(24, 8);
         int inputFlags = r.readInt(20);
         boolean unicode = (inputFlags & 1) == 1;
-        String domainFromServer = r.readSecurityBuffer(12, unicode);
-        if (domainFromServer != null) {
-            domain = domainFromServer;
-        }
-        if (domain == null) {
-            domain = "";
-        }
+
+        // IE uses domainFromServer to generate an alist if server has not
+        // provided one. Firefox/WebKit do not. Neither do we.
+        //String domainFromServer = r.readSecurityBuffer(12, unicode);
 
         int flags = 0x88200 | (inputFlags & 3);
         Writer p = new Writer(3, 64);
@@ -163,7 +154,9 @@ public final class Client extends NTLM {
             if (writeLM) lm = calcV2(nthash,
                     username.toUpperCase(Locale.US)+domain, nonce, challenge);
             if (writeNTLM) {
-                byte[] alist = type2.length > 48 ?
+                // Some client create a alist even if server does not send
+                // one: (i16)2 (i16)len target_in_unicode (i16)0 (i16) 0
+                byte[] alist = ((inputFlags & 0x800000) != 0) ?
                     r.readSecurityBuffer(40) : new byte[0];
                 byte[] blob = new byte[32+alist.length];
                 System.arraycopy(new byte[]{1,1,0,0,0,0,0,0}, 0, blob, 0, 8);
diff --git a/jdk/src/share/classes/com/sun/security/ntlm/Server.java b/jdk/src/share/classes/com/sun/security/ntlm/Server.java
index 0593b2e1c8982febf76b28eb485599adb2ff6e63..adec1a3fa29eb7ce9a761d74813d5bb6fe9862be 100644
--- a/jdk/src/share/classes/com/sun/security/ntlm/Server.java
+++ b/jdk/src/share/classes/com/sun/security/ntlm/Server.java
@@ -1,3 +1,4 @@
+
 /*
  * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -92,7 +93,9 @@ public abstract class Server extends NTLM {
         debug("NTLM Server: Type 1 received\n");
         if (type1 != null) debug(type1);
         Writer p = new Writer(2, 32);
-        int flags = 0x80205;
+        // Negotiate NTLM2 Key, Target Type Domain,
+        // Negotiate NTLM, Request Target, Negotiate unicode
+        int flags = 0x90205;
         p.writeSecurityBuffer(12, domain, true);
         p.writeInt(20, flags);
         p.writeBytes(24, nonce);
@@ -127,8 +130,9 @@ public abstract class Server extends NTLM {
                     "Wrong domain: " + incomingDomain +
                     " vs " + domain); // Needed?
         }*/
+
         boolean verified = false;
-        char[] password = getPassword(domain, username);
+        char[] password = getPassword(incomingDomain, username);
         if (password == null) {
             throw new NTLMException(NTLMException.USER_UNKNOWN,
                     "Unknown user");
@@ -179,6 +183,8 @@ public abstract class Server extends NTLM {
                 }
             }
             if (incomingNTLM.length > 0) {
+                // We didn't sent alist in type2(), so there
+                // is nothing to check here.
                 byte[] clientBlob = Arrays.copyOfRange(
                         incomingNTLM, 16, incomingNTLM.length);
                 byte[] ntlmresponse = calcV2(nthash,
diff --git a/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Base.java b/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Base.java
index 30461e25f7c8d94103cdcf5abf4c60261f7233f1..7a7dc52a26c11fe0201bc9d22ec81d129f543f5a 100644
--- a/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Base.java
+++ b/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Base.java
@@ -26,11 +26,14 @@
 
 package com.sun.security.sasl.gsskerb;
 
+import java.util.Locale;
 import java.util.Map;
 import java.util.logging.Level;
 import javax.security.sasl.*;
 import com.sun.security.sasl.util.AbstractSaslImpl;
 import org.ietf.jgss.*;
+import com.sun.security.jgss.ExtendedGSSContext;
+import com.sun.security.jgss.InquireType;
 
 abstract class GssKrb5Base extends AbstractSaslImpl {
 
@@ -61,6 +64,36 @@ abstract class GssKrb5Base extends AbstractSaslImpl {
         return "GSSAPI";
     }
 
+    @Override
+    public Object getNegotiatedProperty(String propName) {
+        if (!completed) {
+            throw new IllegalStateException("Authentication incomplete");
+        }
+        String xprefix = "com.sun.security.jgss.inquiretype.";
+        if (propName.startsWith(xprefix)) {
+            String type = propName.substring(xprefix.length());
+            if (logger.isLoggable(Level.FINEST)) {
+                logger.logp(Level.FINE, "GssKrb5Base",
+                        "getNegotiatedProperty", propName);
+            }
+            for (InquireType t: InquireType.values()) {
+                if (t.name().toLowerCase(Locale.US).equals(type)) {
+                    try {
+                        return ((ExtendedGSSContext)secCtx).inquireSecContext(t);
+                    } catch (GSSException e) {
+                        if (logger.isLoggable(Level.FINEST)) {
+                            logger.log(Level.WARNING, "inquireSecContext error", e);
+                        }
+                        return null;
+                    }
+                }
+            }
+            // No such InquireType. Although not likely to be defined
+            // as a property in a parent class, still try it.
+        }
+        return super.getNegotiatedProperty(propName);
+    }
+
     public byte[] unwrap(byte[] incoming, int start, int len)
         throws SaslException {
         if (!completed) {
diff --git a/jdk/src/share/classes/com/sun/security/sasl/ntlm/NTLMClient.java b/jdk/src/share/classes/com/sun/security/sasl/ntlm/NTLMClient.java
index dbb1d610d317e4faaf4dd9d283b2a83b85ec1d6c..2cf561c0d3ce8934502c87bcaed7d04127033759 100644
--- a/jdk/src/share/classes/com/sun/security/sasl/ntlm/NTLMClient.java
+++ b/jdk/src/share/classes/com/sun/security/sasl/ntlm/NTLMClient.java
@@ -160,9 +160,17 @@ final class NTLMClient implements SaslClient {
             }
         }
         try {
+            String name = ncb.getName();
+            if (name == null) {
+                name = authzid;
+            }
+            String domain = dcb.getText();
+            if (domain == null) {
+                domain = serverName;
+            }
             client = new Client(version, hostname,
-                    ncb.getName(),
-                    dcb.getText(),
+                    name,
+                    domain,
                     pcb.getPassword());
         } catch (NTLMException ne) {
             throw new SaslException(
diff --git a/jdk/src/share/classes/com/sun/security/sasl/ntlm/NTLMServer.java b/jdk/src/share/classes/com/sun/security/sasl/ntlm/NTLMServer.java
index 9589abd358e30530ef7e8a03484075d708164f1a..c1a8eb6d59590eea79c9a6380fd14d847736723b 100644
--- a/jdk/src/share/classes/com/sun/security/sasl/ntlm/NTLMServer.java
+++ b/jdk/src/share/classes/com/sun/security/sasl/ntlm/NTLMServer.java
@@ -141,8 +141,10 @@ final class NTLMServer implements SaslServer {
             server = new Server(version, domain) {
                 public char[] getPassword(String ntdomain, String username) {
                     try {
-                        RealmCallback rcb = new RealmCallback(
-                                "Domain: ", ntdomain);
+                        RealmCallback rcb =
+                                (ntdomain == null || ntdomain.isEmpty())
+                                    ? new RealmCallback("Domain: ")
+                                    : new RealmCallback("Domain: ", ntdomain);
                         NameCallback ncb = new NameCallback(
                                 "Name: ", username);
                         PasswordCallback pcb = new PasswordCallback(
diff --git a/jdk/src/share/classes/java/awt/font/JavaAWTFontAccessImpl.java b/jdk/src/share/classes/java/awt/font/JavaAWTFontAccessImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..a15b9311fb91dcbc456b75b3d54ba3ea72eae885
--- /dev/null
+++ b/jdk/src/share/classes/java/awt/font/JavaAWTFontAccessImpl.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2014, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+package java.awt.font;
+
+import java.lang.reflect.Field;
+import sun.misc.JavaAWTFontAccess;
+
+class JavaAWTFontAccessImpl implements sun.misc.JavaAWTFontAccess {
+
+    // java.awt.font.TextAttribute constants
+    public Object getTextAttributeConstant(String name) {
+        switch (name) {
+        case "RUN_DIRECTION":
+        case "NUMERIC_SHAPING":
+        case "BIDI_EMBEDDING":
+        case "RUN_DIRECTION_LTR":
+            try {
+                Field f = TextAttribute.class.getField(name);
+                return f.get(null);
+            } catch (NoSuchFieldException | IllegalAccessException x) {
+                throw new AssertionError(x);
+            }
+        }
+
+        throw new AssertionError("Constant name is not recognized");
+    }
+
+    // java.awt.font.NumericShaper
+    public void shape(Object shaper, char[] text, int start, int count) {
+        assert shaper instanceof NumericShaper;
+        ((NumericShaper)shaper).shape(text, start,count);
+    }
+
+}
diff --git a/jdk/src/share/classes/java/awt/font/NumericShaper.java b/jdk/src/share/classes/java/awt/font/NumericShaper.java
index 7e1980e9fe2deafd549e68e144b71b47eb3983df..c02d959e0bd9b696bac57042d142d03cf381e323 100644
--- a/jdk/src/share/classes/java/awt/font/NumericShaper.java
+++ b/jdk/src/share/classes/java/awt/font/NumericShaper.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, 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,6 +31,7 @@ import java.util.Arrays;
 import java.util.Comparator;
 import java.util.EnumSet;
 import java.util.Set;
+import sun.misc.SharedSecrets;
 
 /**
  * The <code>NumericShaper</code> class is used to convert Latin-1 (European)
@@ -134,6 +135,14 @@ import java.util.Set;
  */
 
 public final class NumericShaper implements java.io.Serializable {
+
+    // For access from java.text.Bidi
+    static {
+        if (SharedSecrets.getJavaAWTFontAccess() == null) {
+            SharedSecrets.setJavaAWTFontAccess(new JavaAWTFontAccessImpl());
+        }
+    }
+
     /**
      * A {@code NumericShaper.Range} represents a Unicode range of a
      * script having its own decimal digits. For example, the {@link
diff --git a/jdk/src/share/classes/java/awt/font/TextAttribute.java b/jdk/src/share/classes/java/awt/font/TextAttribute.java
index 264871bd031a1dfb572faf0dae9b51229746b305..3a7714ba1ddb9194e57b7d77f3ccc706b868b6aa 100644
--- a/jdk/src/share/classes/java/awt/font/TextAttribute.java
+++ b/jdk/src/share/classes/java/awt/font/TextAttribute.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -44,6 +44,7 @@ import java.io.InvalidObjectException;
 import java.text.AttributedCharacterIterator.Attribute;
 import java.util.Map;
 import java.util.HashMap;
+import sun.misc.SharedSecrets;
 
 /**
  * The <code>TextAttribute</code> class defines attribute keys and
@@ -257,6 +258,13 @@ public final class TextAttribute extends Attribute {
     private static final Map<String, TextAttribute>
             instanceMap = new HashMap<String, TextAttribute>(29);
 
+    // For access from java.text.Bidi
+    static {
+        if (SharedSecrets.getJavaAWTFontAccess() == null) {
+            SharedSecrets.setJavaAWTFontAccess(new JavaAWTFontAccessImpl());
+        }
+    }
+
     /**
      * Constructs a <code>TextAttribute</code> with the specified name.
      * @param name the attribute name to assign to this
diff --git a/jdk/src/share/classes/java/lang/Class.java b/jdk/src/share/classes/java/lang/Class.java
index 71daa390286af2ba10fd7246d724eb6bcf02bf49..ed7fa95e1218263fbb0dd4984541147a1bf5cfe5 100644
--- a/jdk/src/share/classes/java/lang/Class.java
+++ b/jdk/src/share/classes/java/lang/Class.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2014, 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
@@ -130,11 +130,15 @@ public final class Class<T> implements java.io.Serializable,
     }
 
     /*
-     * Constructor. Only the Java Virtual Machine creates Class
-     * objects.
+     * Private constructor. Only the Java Virtual Machine creates Class objects.
+     * This constructor is not used and prevents the default constructor being
+     * generated.
      */
-    private Class() {}
-
+    private Class(ClassLoader loader) {
+        // Initialize final field for classLoader.  The initialization value of non-null
+        // prevents future JIT optimizations from assuming this final field is null.
+        classLoader = loader;
+    }
 
     /**
      * Converts the object to a string. The string representation is the
@@ -677,8 +681,10 @@ public final class Class<T> implements java.io.Serializable,
     }
 
     // Package-private to allow ClassLoader access
-    native ClassLoader getClassLoader0();
+    ClassLoader getClassLoader0() { return classLoader; }
 
+    // Initialized in JVM not by private constructor
+    private final ClassLoader classLoader;
 
     /**
      * Returns an array of {@code TypeVariable} objects that represent the
diff --git a/jdk/src/share/classes/java/lang/reflect/AccessibleObject.java b/jdk/src/share/classes/java/lang/reflect/AccessibleObject.java
index a5931e145a7a6e27252ab126bcc7fc113f5bc596..f85ab432388a56fb8b256c397146fcdf7580f90b 100644
--- a/jdk/src/share/classes/java/lang/reflect/AccessibleObject.java
+++ b/jdk/src/share/classes/java/lang/reflect/AccessibleObject.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -129,16 +129,24 @@ public class AccessibleObject implements AnnotatedElement {
         setAccessible0(this, flag);
     }
 
-    /* Check that you aren't exposing java.lang.Class.<init>. */
+    /* Check that you aren't exposing java.lang.Class.<init> or sensitive
+       fields in java.lang.Class. */
     private static void setAccessible0(AccessibleObject obj, boolean flag)
         throws SecurityException
     {
         if (obj instanceof Constructor && flag == true) {
             Constructor<?> c = (Constructor<?>)obj;
             if (c.getDeclaringClass() == Class.class) {
-                throw new SecurityException("Can not make a java.lang.Class" +
+                throw new SecurityException("Cannot make a java.lang.Class" +
                                             " constructor accessible");
             }
+        } else if (obj instanceof Field && flag == true) {
+            Field f = (Field)obj;
+            if (f.getDeclaringClass() == Class.class &&
+                f.getName().equals("classLoader")) {
+                throw new SecurityException("Cannot make java.lang.Class.classLoader" +
+                                            " accessible");
+            }
         }
         obj.override = flag;
     }
diff --git a/jdk/src/share/classes/java/net/URL.java b/jdk/src/share/classes/java/net/URL.java
index 9987bc08a4d931156a4cdfb25ce52e126fc88f2f..e0abaace2b5b068549ddb7357f0f2b8fabd555b8 100644
--- a/jdk/src/share/classes/java/net/URL.java
+++ b/jdk/src/share/classes/java/net/URL.java
@@ -1071,7 +1071,7 @@ public final class URL implements java.io.Serializable {
     /**
      * The URLStreamHandler factory.
      */
-    static URLStreamHandlerFactory factory;
+    private static volatile URLStreamHandlerFactory factory;
 
     /**
      * Sets an application's {@code URLStreamHandlerFactory}.
@@ -1106,6 +1106,7 @@ public final class URL implements java.io.Serializable {
                 security.checkSetFactory();
             }
             handlers.clear();
+            // safe publication of URLStreamHandlerFactory with volatile write
             factory = fac;
         }
     }
@@ -1127,9 +1128,11 @@ public final class URL implements java.io.Serializable {
 
             boolean checkedWithFactory = false;
 
-            // Use the factory (if any)
-            if (factory != null) {
-                handler = factory.createURLStreamHandler(protocol);
+            // Use the factory (if any). Volatile read makes
+            // URLStreamHandlerFactory appear fully initialized to current thread.
+            URLStreamHandlerFactory fac = factory;
+            if (fac != null) {
+                handler = fac.createURLStreamHandler(protocol);
                 checkedWithFactory = true;
             }
 
@@ -1193,8 +1196,8 @@ public final class URL implements java.io.Serializable {
 
                 // Check with factory if another thread set a
                 // factory since our last check
-                if (!checkedWithFactory && factory != null) {
-                    handler2 = factory.createURLStreamHandler(protocol);
+                if (!checkedWithFactory && (fac = factory) != null) {
+                    handler2 = fac.createURLStreamHandler(protocol);
                 }
 
                 if (handler2 != null) {
diff --git a/jdk/src/share/classes/java/util/IdentityHashMap.java b/jdk/src/share/classes/java/util/IdentityHashMap.java
index f96055bc6c1a4abfc6360ee1026d7006c306b9ae..d4ad6006c923317d7fcb3d7c9062cbd9a243ea68 100644
--- a/jdk/src/share/classes/java/util/IdentityHashMap.java
+++ b/jdk/src/share/classes/java/util/IdentityHashMap.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, 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
@@ -25,7 +25,6 @@
 
 package java.util;
 
-import java.io.*;
 import java.lang.reflect.Array;
 import java.util.function.BiConsumer;
 import java.util.function.BiFunction;
@@ -74,7 +73,7 @@ import java.util.function.Consumer;
  * maximum size and the number of buckets is unspecified.
  *
  * <p>If the size of the map (the number of key-value mappings) sufficiently
- * exceeds the expected maximum size, the number of buckets is increased
+ * exceeds the expected maximum size, the number of buckets is increased.
  * Increasing the number of buckets ("rehashing") may be fairly expensive, so
  * it pays to create identity hash maps with a sufficiently large expected
  * maximum size.  On the other hand, iteration over collection views requires
@@ -160,6 +159,10 @@ public class IdentityHashMap<K,V>
      * The maximum capacity, used if a higher value is implicitly specified
      * by either of the constructors with arguments.
      * MUST be a power of two <= 1<<29.
+     *
+     * In fact, the map can hold no more than MAXIMUM_CAPACITY-1 items
+     * because it has to have at least one slot with the key == null
+     * in order to avoid infinite loops in get(), put(), remove()
      */
     private static final int MAXIMUM_CAPACITY = 1 << 29;
 
@@ -180,11 +183,6 @@ public class IdentityHashMap<K,V>
      */
     transient int modCount;
 
-    /**
-     * The next size value at which to resize (capacity * load factor).
-     */
-    private transient int threshold;
-
     /**
      * Value representing null keys inside tables.
      */
@@ -229,27 +227,18 @@ public class IdentityHashMap<K,V>
     }
 
     /**
-     * Returns the appropriate capacity for the specified expected maximum
-     * size.  Returns the smallest power of two between MINIMUM_CAPACITY
-     * and MAXIMUM_CAPACITY, inclusive, that is greater than
-     * (3 * expectedMaxSize)/2, if such a number exists.  Otherwise
-     * returns MAXIMUM_CAPACITY.  If (3 * expectedMaxSize)/2 is negative, it
-     * is assumed that overflow has occurred, and MAXIMUM_CAPACITY is returned.
+     * Returns the appropriate capacity for the given expected maximum size.
+     * Returns the smallest power of two between MINIMUM_CAPACITY and
+     * MAXIMUM_CAPACITY, inclusive, that is greater than (3 *
+     * expectedMaxSize)/2, if such a number exists.  Otherwise returns
+     * MAXIMUM_CAPACITY.
      */
-    private int capacity(int expectedMaxSize) {
-        // Compute min capacity for expectedMaxSize given a load factor of 2/3
-        int minCapacity = (3 * expectedMaxSize)/2;
-
-        // Compute the appropriate capacity
-        int result;
-        if (minCapacity > MAXIMUM_CAPACITY || minCapacity < 0) {
-            result = MAXIMUM_CAPACITY;
-        } else {
-            result = MINIMUM_CAPACITY;
-            while (result < minCapacity)
-                result <<= 1;
-        }
-        return result;
+    private static int capacity(int expectedMaxSize) {
+        // assert expectedMaxSize >= 0;
+        return
+            (expectedMaxSize > MAXIMUM_CAPACITY / 3) ? MAXIMUM_CAPACITY :
+            (expectedMaxSize <= 2 * MINIMUM_CAPACITY / 3) ? MINIMUM_CAPACITY :
+            Integer.highestOneBit(expectedMaxSize + (expectedMaxSize << 1));
     }
 
     /**
@@ -262,7 +251,6 @@ public class IdentityHashMap<K,V>
         // assert initCapacity >= MINIMUM_CAPACITY;
         // assert initCapacity <= MAXIMUM_CAPACITY;
 
-        threshold = (initCapacity * 2)/3;
         table = new Object[2 * initCapacity];
     }
 
@@ -429,52 +417,58 @@ public class IdentityHashMap<K,V>
      * @see     #containsKey(Object)
      */
     public V put(K key, V value) {
-        Object k = maskNull(key);
-        Object[] tab = table;
-        int len = tab.length;
-        int i = hash(k, len);
+        final Object k = maskNull(key);
 
-        Object item;
-        while ( (item = tab[i]) != null) {
-            if (item == k) {
-                @SuppressWarnings("unchecked")
-                    V oldValue = (V) tab[i + 1];
-                tab[i + 1] = value;
-                return oldValue;
+        retryAfterResize: for (;;) {
+            final Object[] tab = table;
+            final int len = tab.length;
+            int i = hash(k, len);
+
+            for (Object item; (item = tab[i]) != null;
+                 i = nextKeyIndex(i, len)) {
+                if (item == k) {
+                    @SuppressWarnings("unchecked")
+                        V oldValue = (V) tab[i + 1];
+                    tab[i + 1] = value;
+                    return oldValue;
+                }
             }
-            i = nextKeyIndex(i, len);
-        }
 
-        modCount++;
-        tab[i] = k;
-        tab[i + 1] = value;
-        if (++size >= threshold)
-            resize(len); // len == 2 * current capacity.
-        return null;
+            final int s = size + 1;
+            // Use optimized form of 3 * s.
+            // Next capacity is len, 2 * current capacity.
+            if (s + (s << 1) > len && resize(len))
+                continue retryAfterResize;
+
+            modCount++;
+            tab[i] = k;
+            tab[i + 1] = value;
+            size = s;
+            return null;
+        }
     }
 
     /**
-     * Resize the table to hold given capacity.
+     * Resizes the table if necessary to hold given capacity.
      *
      * @param newCapacity the new capacity, must be a power of two.
+     * @return whether a resize did in fact take place
      */
-    private void resize(int newCapacity) {
+    private boolean resize(int newCapacity) {
         // assert (newCapacity & -newCapacity) == newCapacity; // power of 2
         int newLength = newCapacity * 2;
 
         Object[] oldTable = table;
         int oldLength = oldTable.length;
-        if (oldLength == 2*MAXIMUM_CAPACITY) { // can't expand any further
-            if (threshold == MAXIMUM_CAPACITY-1)
+        if (oldLength == 2 * MAXIMUM_CAPACITY) { // can't expand any further
+            if (size == MAXIMUM_CAPACITY - 1)
                 throw new IllegalStateException("Capacity exhausted.");
-            threshold = MAXIMUM_CAPACITY-1;  // Gigantic map!
-            return;
+            return false;
         }
         if (oldLength >= newLength)
-            return;
+            return false;
 
         Object[] newTable = new Object[newLength];
-        threshold = newLength / 3;
 
         for (int j = 0; j < oldLength; j += 2) {
             Object key = oldTable[j];
@@ -490,6 +484,7 @@ public class IdentityHashMap<K,V>
             }
         }
         table = newTable;
+        return true;
     }
 
     /**
@@ -504,8 +499,8 @@ public class IdentityHashMap<K,V>
         int n = m.size();
         if (n == 0)
             return;
-        if (n > threshold) // conservatively pre-expand
-            resize(capacity(n));
+        if (n > size)
+            resize(capacity(n)); // conservatively pre-expand
 
         for (Entry<? extends K, ? extends V> e : m.entrySet())
             put(e.getKey(), e.getValue());
@@ -542,7 +537,6 @@ public class IdentityHashMap<K,V>
                 return null;
             i = nextKeyIndex(i, len);
         }
-
     }
 
     /**
@@ -1266,8 +1260,8 @@ public class IdentityHashMap<K,V>
     private static final long serialVersionUID = 8188218128353913216L;
 
     /**
-     * Save the state of the <tt>IdentityHashMap</tt> instance to a stream
-     * (i.e., serialize it).
+     * Saves the state of the <tt>IdentityHashMap</tt> instance to a stream
+     * (i.e., serializes it).
      *
      * @serialData The <i>size</i> of the HashMap (the number of key-value
      *          mappings) (<tt>int</tt>), followed by the key (Object) and
@@ -1295,8 +1289,8 @@ public class IdentityHashMap<K,V>
     }
 
     /**
-     * Reconstitute the <tt>IdentityHashMap</tt> instance from a stream (i.e.,
-     * deserialize it).
+     * Reconstitutes the <tt>IdentityHashMap</tt> instance from a stream (i.e.,
+     * deserializes it).
      */
     private void readObject(java.io.ObjectInputStream s)
         throws java.io.IOException, ClassNotFoundException  {
@@ -1305,9 +1299,10 @@ public class IdentityHashMap<K,V>
 
         // Read in size (number of Mappings)
         int size = s.readInt();
-
-        // Allow for 33% growth (i.e., capacity is >= 2* size()).
-        init(capacity((size*4)/3));
+        if (size < 0)
+            throw new java.io.StreamCorruptedException
+                ("Illegal mappings count: " + size);
+        init(capacity(size));
 
         // Read the keys and values, and put the mappings in the table
         for (int i=0; i<size; i++) {
@@ -1324,7 +1319,7 @@ public class IdentityHashMap<K,V>
      * update modCount, etc.
      */
     private void putForCreate(K key, V value)
-        throws IOException
+        throws java.io.StreamCorruptedException
     {
         Object k = maskNull(key);
         Object[] tab = table;
diff --git a/jdk/src/share/classes/java/util/logging/FileHandler.java b/jdk/src/share/classes/java/util/logging/FileHandler.java
index cad034ececb65198ab63b42a760a90f3d6aa00b0..d58fd0ebc8408e3055f1b5f362b451cd4ab8f299 100644
--- a/jdk/src/share/classes/java/util/logging/FileHandler.java
+++ b/jdk/src/share/classes/java/util/logging/FileHandler.java
@@ -25,6 +25,7 @@
 
 package java.util.logging;
 
+import static java.nio.file.StandardOpenOption.APPEND;
 import static java.nio.file.StandardOpenOption.CREATE_NEW;
 import static java.nio.file.StandardOpenOption.WRITE;
 
@@ -34,10 +35,17 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.nio.channels.FileChannel;
+import java.nio.channels.OverlappingFileLockException;
 import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.util.HashSet;
+import java.util.Set;
 
 /**
  * Simple file logging <tt>Handler</tt>.
@@ -149,7 +157,7 @@ public class FileHandler extends StreamHandler {
     private FileChannel lockFileChannel;
     private File files[];
     private static final int MAX_LOCKS = 100;
-    private static final java.util.HashMap<String, String> locks = new java.util.HashMap<>();
+    private static final Set<String> locks = new HashSet<>();
 
     /**
      * A metered stream is a subclass of OutputStream that
@@ -428,34 +436,80 @@ public class FileHandler extends StreamHandler {
             // between processes (and not within a process), we first check
             // if we ourself already have the file locked.
             synchronized(locks) {
-                if (locks.get(lockFileName) != null) {
+                if (locks.contains(lockFileName)) {
                     // We already own this lock, for a different FileHandler
                     // object.  Try again.
                     continue;
                 }
 
-                try {
-                    lockFileChannel = FileChannel.open(Paths.get(lockFileName),
-                            CREATE_NEW, WRITE);
-                } catch (FileAlreadyExistsException ix) {
-                    // try the next lock file name in the sequence
-                    continue;
+                final Path lockFilePath = Paths.get(lockFileName);
+                FileChannel channel = null;
+                int retries = -1;
+                boolean fileCreated = false;
+                while (channel == null && retries++ < 1) {
+                    try {
+                        channel = FileChannel.open(lockFilePath,
+                                CREATE_NEW, WRITE);
+                        fileCreated = true;
+                    } catch (FileAlreadyExistsException ix) {
+                        // This may be a zombie file left over by a previous
+                        // execution. Reuse it - but only if we can actually
+                        // write to its directory.
+                        // Note that this is a situation that may happen,
+                        // but not too frequently.
+                        if (Files.isRegularFile(lockFilePath, LinkOption.NOFOLLOW_LINKS)
+                            && Files.isWritable(lockFilePath.getParent())) {
+                            try {
+                                channel = FileChannel.open(lockFilePath,
+                                    WRITE, APPEND);
+                            } catch (NoSuchFileException x) {
+                                // Race condition - retry once, and if that
+                                // fails again just try the next name in
+                                // the sequence.
+                                continue;
+                            } catch(IOException x) {
+                                // the file may not be writable for us.
+                                // try the next name in the sequence
+                                break;
+                            }
+                        } else {
+                            // at this point channel should still be null.
+                            // break and try the next name in the sequence.
+                            break;
+                        }
+                    }
                 }
 
+                if (channel == null) continue; // try the next name;
+                lockFileChannel = channel;
+
                 boolean available;
                 try {
                     available = lockFileChannel.tryLock() != null;
                     // We got the lock OK.
+                    // At this point we could call File.deleteOnExit().
+                    // However, this could have undesirable side effects
+                    // as indicated by JDK-4872014. So we will instead
+                    // rely on the fact that close() will remove the lock
+                    // file and that whoever is creating FileHandlers should
+                    // be responsible for closing them.
                 } catch (IOException ix) {
                     // We got an IOException while trying to get the lock.
                     // This normally indicates that locking is not supported
                     // on the target directory.  We have to proceed without
-                    // getting a lock.   Drop through.
-                    available = true;
+                    // getting a lock.   Drop through, but only if we did
+                    // create the file...
+                    available = fileCreated;
+                } catch (OverlappingFileLockException x) {
+                    // someone already locked this file in this VM, through
+                    // some other channel - that is - using something else
+                    // than new FileHandler(...);
+                    // continue searching for an available lock.
+                    available = false;
                 }
                 if (available) {
                     // We got the lock.  Remember it.
-                    locks.put(lockFileName, lockFileName);
+                    locks.add(lockFileName);
                     break;
                 }
 
diff --git a/jdk/src/share/classes/javax/crypto/spec/SecretKeySpec.java b/jdk/src/share/classes/javax/crypto/spec/SecretKeySpec.java
index aedd9ca130c0b3f35bab02b253d6774d38389dd8..94c35e0b80d0a0172ff4e3f8ddc2da2c337c1a46 100644
--- a/jdk/src/share/classes/javax/crypto/spec/SecretKeySpec.java
+++ b/jdk/src/share/classes/javax/crypto/spec/SecretKeySpec.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, 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
@@ -26,6 +26,7 @@
 package javax.crypto.spec;
 
 import java.security.spec.KeySpec;
+import java.util.Locale;
 import javax.crypto.SecretKey;
 
 /**
@@ -194,7 +195,8 @@ public class SecretKeySpec implements KeySpec, SecretKey {
         if (this.algorithm.equalsIgnoreCase("TripleDES"))
             return (retval ^= "desede".hashCode());
         else
-            return (retval ^= this.algorithm.toLowerCase().hashCode());
+            return (retval ^=
+                    this.algorithm.toLowerCase(Locale.ENGLISH).hashCode());
     }
 
    /**
diff --git a/jdk/src/share/classes/javax/security/sasl/SaslClient.java b/jdk/src/share/classes/javax/security/sasl/SaslClient.java
index c7258f4007bb539a13651c33d0ee9e1c9916fee3..a488132301c0e11a8c6bdb7a45b9b768a5a0a6c9 100644
--- a/jdk/src/share/classes/javax/security/sasl/SaslClient.java
+++ b/jdk/src/share/classes/javax/security/sasl/SaslClient.java
@@ -204,6 +204,10 @@ public abstract interface SaslClient {
      * This method can be called only after the authentication exchange has
      * completed (i.e., when {@code isComplete()} returns true); otherwise, an
      * {@code IllegalStateException} is thrown.
+     * <p>
+     * The {@link Sasl} class includes several well-known property names
+     * (For example, {@link Sasl#QOP}). A SASL provider can support other
+     * properties which are specific to the vendor and/or a mechanism.
      *
      * @param propName The non-null property name.
      * @return The value of the negotiated property. If null, the property was
diff --git a/jdk/src/share/classes/javax/security/sasl/SaslServer.java b/jdk/src/share/classes/javax/security/sasl/SaslServer.java
index 818ae9996549fdea8db580aa4bea77f3f5317dc6..a80772cff115a138e40704f49aafd50ef0ab0764 100644
--- a/jdk/src/share/classes/javax/security/sasl/SaslServer.java
+++ b/jdk/src/share/classes/javax/security/sasl/SaslServer.java
@@ -196,6 +196,10 @@ public abstract interface SaslServer {
      * This method can be called only after the authentication exchange has
      * completed (i.e., when {@code isComplete()} returns true); otherwise, an
      * {@code IllegalStateException} is thrown.
+     * <p>
+     * The {@link Sasl} class includes several well-known property names
+     * (For example, {@link Sasl#QOP}). A SASL provider can support other
+     * properties which are specific to the vendor and/or a mechanism.
      *
      * @param propName the property
      * @return The value of the negotiated property. If null, the property was
diff --git a/jdk/src/share/classes/javax/swing/AbstractListModel.java b/jdk/src/share/classes/javax/swing/AbstractListModel.java
index cc3003dc132bafd1886e53c877d3e62489e20f68..e4956670ee06415de31b07e18990d4edfce65f2b 100644
--- a/jdk/src/share/classes/javax/swing/AbstractListModel.java
+++ b/jdk/src/share/classes/javax/swing/AbstractListModel.java
@@ -202,6 +202,7 @@ public abstract class AbstractListModel<E> implements ListModel<E>, Serializable
      * If no such listeners exist,
      * this method returns an empty array.
      *
+     * @param <T> the type of {@code EventListener} class being requested
      * @param listenerType  the type of listeners requested;
      *          this parameter should specify an interface
      *          that descends from <code>java.util.EventListener</code>
diff --git a/jdk/src/share/classes/javax/swing/CellRendererPane.java b/jdk/src/share/classes/javax/swing/CellRendererPane.java
index 70ba2afa04cd90b194ef1ba0c7075e3f02e59ec7..6050693eeeb59f3c61cf3319f8ed9ad70eafb332 100644
--- a/jdk/src/share/classes/javax/swing/CellRendererPane.java
+++ b/jdk/src/share/classes/javax/swing/CellRendererPane.java
@@ -190,8 +190,12 @@ public class CellRendererPane extends Container implements Accessible
 // Accessibility support
 ////////////////
 
+    /**
+     * {@code AccessibleContext} associated with this {@code CellRendererPan}
+     */
     protected AccessibleContext accessibleContext = null;
 
+
     /**
      * Gets the AccessibleContext associated with this CellRendererPane.
      * For CellRendererPanes, the AccessibleContext takes the form of an
diff --git a/jdk/src/share/classes/javax/swing/DefaultCellEditor.java b/jdk/src/share/classes/javax/swing/DefaultCellEditor.java
index ba8942c5b21b68ee6c9e9b2a1f4b741ead30907b..dfb9056e62c78d86fb303abcc68bfcdbb4322516 100644
--- a/jdk/src/share/classes/javax/swing/DefaultCellEditor.java
+++ b/jdk/src/share/classes/javax/swing/DefaultCellEditor.java
@@ -353,6 +353,7 @@ public class DefaultCellEditor extends AbstractCellEditor
         * Returns true to indicate that editing has begun.
         *
         * @param anEvent          the event
+        * @return true to indicate editing has begun
         */
         public boolean startCellEditing(EventObject anEvent) {
             return true;
diff --git a/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java b/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java
index 6c66c8d6cce73cf51fd471cfca9b33b15b8c0b04..ebee71521d92132a632e732068a2b6cd3f28046a 100644
--- a/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java
+++ b/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java
@@ -462,7 +462,12 @@ public class DefaultDesktopManager implements DesktopManager, java.io.Serializab
         f.revalidate();
     }
 
-    /** Convenience method to remove the desktopIcon of <b>f</b> is necessary. */
+    /**
+     * Convenience method to remove the desktopIcon of <b>f</b> is necessary.
+     *
+     * @param f the {@code JInternalFrame} for which to remove the
+     *          {@code desktopIcon}
+     */
     protected void removeIconFor(JInternalFrame f) {
         JInternalFrame.JDesktopIcon di = f.getDesktopIcon();
         Container c = di.getParent();
@@ -472,10 +477,13 @@ public class DefaultDesktopManager implements DesktopManager, java.io.Serializab
         }
     }
 
-    /** The iconifyFrame() code calls this to determine the proper bounds
-      * for the desktopIcon.
-      */
-
+    /**
+     * The {@code iconifyFrame()} code calls this to determine the proper bounds
+     * for the desktopIcon.
+     *
+     * @param f the {@code JInternalFrame} of interest
+     * @return a {@code Rectangle} containing bounds for the {@code desktopIcon}
+     */
     protected Rectangle getBoundsForIconOf(JInternalFrame f) {
       //
       // Get the icon for this internal frame and its preferred size
@@ -592,6 +600,9 @@ public class DefaultDesktopManager implements DesktopManager, java.io.Serializab
     /**
      * Sets that the component has been iconized and the bounds of the
      * <code>desktopIcon</code> are valid.
+     *
+     * @param f     the {@code JInternalFrame} of interest
+     * @param value a {@code Boolean} signifying if component has been iconized
      */
     protected void setWasIcon(JInternalFrame f, Boolean value)  {
         if (value != null) {
diff --git a/jdk/src/share/classes/javax/swing/DefaultListModel.java b/jdk/src/share/classes/javax/swing/DefaultListModel.java
index 2b10f45ad474c881b1521643a647d73694196dc8..a4a826a0f5ce60aeaba8b1bcbb5c8e7fe71d07ac 100644
--- a/jdk/src/share/classes/javax/swing/DefaultListModel.java
+++ b/jdk/src/share/classes/javax/swing/DefaultListModel.java
@@ -444,6 +444,7 @@ public class DefaultListModel<E> extends AbstractListModel<E>
      * (<code>index &lt; 0 || index &gt;= size()</code>).
      *
      * @param index index of element to return
+     * @return the element at the specified position in this list
      */
     public E get(int index) {
         return delegate.elementAt(index);
diff --git a/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java b/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java
index a1cb79f8ea6eebb066aceebe01a501788c759ae0..671b1a412f0087f36f7dbba30ebdea8673db78d6 100644
--- a/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java
+++ b/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java
@@ -160,6 +160,9 @@ public class DefaultListSelectionModel implements ListSelectionModel, Cloneable,
      * Notifies <code>ListSelectionListeners</code> that the value
      * of the selection, in the closed interval <code>firstIndex</code>,
      * <code>lastIndex</code>, has changed.
+     *
+     * @param firstIndex the first index in the interval
+     * @param lastIndex the last index in the interval
      */
     protected void fireValueChanged(int firstIndex, int lastIndex) {
         fireValueChanged(firstIndex, lastIndex, getValueIsAdjusting());
@@ -231,6 +234,7 @@ public class DefaultListSelectionModel implements ListSelectionModel, Cloneable,
      * If no such listeners exist,
      * this method returns an empty array.
      *
+     * @param <T> the type of {@code EventListener} class being requested
      * @param listenerType  the type of listeners requested;
      *          this parameter should specify an interface
      *          that descends from <code>java.util.EventListener</code>
@@ -332,6 +336,8 @@ public class DefaultListSelectionModel implements ListSelectionModel, Cloneable,
 
     /**
      * Sets the value of the leadAnchorNotificationEnabled flag.
+     *
+     * @param flag boolean value for {@code leadAnchorNotificationEnabled}
      * @see             #isLeadAnchorNotificationEnabled()
      */
     public void setLeadAnchorNotificationEnabled(boolean flag) {
diff --git a/jdk/src/share/classes/javax/swing/DefaultRowSorter.java b/jdk/src/share/classes/javax/swing/DefaultRowSorter.java
index 5b9e94537fe54798350e4eea51e6f50802bef672..68264dc89f0a6fe6fe8c0a38092a5c50c46c1776 100644
--- a/jdk/src/share/classes/javax/swing/DefaultRowSorter.java
+++ b/jdk/src/share/classes/javax/swing/DefaultRowSorter.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, 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
@@ -712,6 +712,8 @@ public abstract class DefaultRowSorter<M, I> extends RowSorter<M> {
      *
      * @param column the index of the column to test, in terms of the
      *        underlying model
+     * @return true if values are to be converted to strings before doing
+     *              comparisons when sorting
      * @throws IndexOutOfBoundsException if <code>column</code> is not valid
      */
     protected boolean useToString(int column) {
diff --git a/jdk/src/share/classes/javax/swing/InputMap.java b/jdk/src/share/classes/javax/swing/InputMap.java
index 55af730c99a2e8fc2669034e41a2fd29be1c77c0..87302b0b6e2cba6d2ba929c86c70e188b02e3601 100644
--- a/jdk/src/share/classes/javax/swing/InputMap.java
+++ b/jdk/src/share/classes/javax/swing/InputMap.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, 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
@@ -32,15 +32,12 @@ import java.util.HashMap;
 import java.util.Set;
 
 /**
- * <code>InputMap</code> provides a binding between an input event
- * (currently only <code>KeyStroke</code>s are used)
- * and an <code>Object</code>. <code>InputMap</code>s
- * are usually used with an <code>ActionMap</code>,
- * to determine an <code>Action</code> to perform
- * when a key is pressed.
- * An <code>InputMap</code> can have a parent
- * that is searched for bindings not defined in the <code>InputMap</code>.
- * <p>As with <code>ActionMap</code> if you create a cycle, eg:
+ * {@code InputMap} provides a binding between an input event (currently only
+ * {@code KeyStroke}s are used) and an {@code Object}. {@code InputMap}s are
+ * usually used with an {@code ActionMap}, to determine an {@code Action} to
+ * perform when a key is pressed. An {@code InputMap} can have a parent that
+ * is searched for bindings not defined in the {@code InputMap}.
+ * <p>As with {@code ActionMap} if you create a cycle, eg:
  * <pre>
  *   InputMap am = new InputMap();
  *   InputMap bm = new InputMap():
@@ -61,34 +58,37 @@ public class InputMap implements Serializable {
 
 
     /**
-     * Creates an <code>InputMap</code> with no parent and no mappings.
+     * Creates an {@code InputMap} with no parent and no mappings.
      */
     public InputMap() {
     }
 
     /**
-     * Sets this <code>InputMap</code>'s parent.
+     * Sets this {@code InputMap}'s parent.
      *
-     * @param map  the <code>InputMap</code> that is the parent of this one
+     * @param map the {@code InputMap} that is the parent of this one
      */
     public void setParent(InputMap map) {
         this.parent = map;
     }
 
     /**
-     * Gets this <code>InputMap</code>'s parent.
+     * Gets this {@code InputMap}'s parent.
      *
-     * @return map  the <code>InputMap</code> that is the parent of this one,
-     *              or null if this <code>InputMap</code> has no parent
+     * @return map the {@code InputMap} that is the parent of this one,
+     *             or null if this {@code InputMap} has no parent
      */
     public InputMap getParent() {
         return parent;
     }
 
     /**
-     * Adds a binding for <code>keyStroke</code> to <code>actionMapKey</code>.
-     * If <code>actionMapKey</code> is null, this removes the current binding
-     * for <code>keyStroke</code>.
+     * Adds a binding for {@code keyStroke} to {@code actionMapKey}.
+     * If {@code actionMapKey} is null, this removes the current binding
+     * for {@code keyStroke}.
+     *
+     * @param keyStroke a {@code KeyStroke}
+     * @param actionMapKey an action map key
      */
     public void put(KeyStroke keyStroke, Object actionMapKey) {
         if (keyStroke == null) {
@@ -106,8 +106,11 @@ public class InputMap implements Serializable {
     }
 
     /**
-     * Returns the binding for <code>keyStroke</code>, messaging the
-     * parent <code>InputMap</code> if the binding is not locally defined.
+     * Returns the binding for {@code keyStroke}, messaging the
+     * parent {@code InputMap} if the binding is not locally defined.
+     *
+     * @param keyStroke the {@code KeyStroke} for which to get the binding
+     * @return the binding for {@code keyStroke}
      */
     public Object get(KeyStroke keyStroke) {
         if (arrayTable == null) {
@@ -131,8 +134,9 @@ public class InputMap implements Serializable {
     }
 
     /**
-     * Removes the binding for <code>key</code> from this
-     * <code>InputMap</code>.
+     * Removes the binding for {@code key} from this {@code InputMap}.
+     *
+     * @param key the {@code KeyStroke} for which to remove the binding
      */
     public void remove(KeyStroke key) {
         if (arrayTable != null) {
@@ -141,7 +145,7 @@ public class InputMap implements Serializable {
     }
 
     /**
-     * Removes all the mappings from this <code>InputMap</code>.
+     * Removes all the mappings from this {@code InputMap}.
      */
     public void clear() {
         if (arrayTable != null) {
@@ -150,7 +154,10 @@ public class InputMap implements Serializable {
     }
 
     /**
-     * Returns the <code>KeyStroke</code>s that are bound in this <code>InputMap</code>.
+     * Returns the {@code KeyStroke}s that are bound in this {@code InputMap}.
+     *
+     * @return an array of the {@code KeyStroke}s that are bound in this
+     *         {@code InputMap}
      */
     public KeyStroke[] keys() {
         if (arrayTable == null) {
@@ -162,7 +169,9 @@ public class InputMap implements Serializable {
     }
 
     /**
-     * Returns the number of <code>KeyStroke</code> bindings.
+     * Returns the number of {@code KeyStroke} bindings.
+     *
+     * @return the number of {@code KeyStroke} bindings
      */
     public int size() {
         if (arrayTable == null) {
@@ -172,9 +181,12 @@ public class InputMap implements Serializable {
     }
 
     /**
-     * Returns an array of the <code>KeyStroke</code>s defined in this
-     * <code>InputMap</code> and its parent. This differs from <code>keys()</code> in that
-     * this method includes the keys defined in the parent.
+     * Returns an array of the {@code KeyStroke}s defined in this
+     * {@code InputMap} and its parent. This differs from {@code keys()}
+     * in that this method includes the keys defined in the parent.
+     *
+     * @return an array of the {@code KeyStroke}s defined in this
+     *         {@code InputMap} and its parent
      */
     public KeyStroke[] allKeys() {
         int             count = size();
diff --git a/jdk/src/share/classes/javax/swing/JCheckBox.java b/jdk/src/share/classes/javax/swing/JCheckBox.java
index c912a383cae736fdbce9d5af3beac244263f0569..400b8efae787bbd1c21bdc69e94aaec1903793bf 100644
--- a/jdk/src/share/classes/javax/swing/JCheckBox.java
+++ b/jdk/src/share/classes/javax/swing/JCheckBox.java
@@ -132,6 +132,7 @@ public class JCheckBox extends JToggleButton implements Accessible {
      * Creates a check box where properties are taken from the
      * Action supplied.
      *
+     * @param a the {@code Action} used to specify the new check box
      * @since 1.3
      */
     public JCheckBox(Action a) {
diff --git a/jdk/src/share/classes/javax/swing/JCheckBoxMenuItem.java b/jdk/src/share/classes/javax/swing/JCheckBoxMenuItem.java
index 962ef73f3c055055f41ad26843fef612b61cc5d4..4aaa4417caa014c5910137ba5fe021ba516656eb 100644
--- a/jdk/src/share/classes/javax/swing/JCheckBoxMenuItem.java
+++ b/jdk/src/share/classes/javax/swing/JCheckBoxMenuItem.java
@@ -109,7 +109,7 @@ public class JCheckBoxMenuItem extends JMenuItem implements SwingConstants,
     /**
      * Creates an initially unselected check box menu item with an icon.
      *
-     * @param icon the icon of the CheckBoxMenuItem.
+     * @param icon the icon of the {@code JCheckBoxMenuItem}.
      */
     public JCheckBoxMenuItem(Icon icon) {
         this(null, icon, false);
@@ -118,7 +118,7 @@ public class JCheckBoxMenuItem extends JMenuItem implements SwingConstants,
     /**
      * Creates an initially unselected check box menu item with text.
      *
-     * @param text the text of the CheckBoxMenuItem
+     * @param text the text of the {@code JCheckBoxMenuItem}
      */
     public JCheckBoxMenuItem(String text) {
         this(text, null, false);
@@ -128,6 +128,7 @@ public class JCheckBoxMenuItem extends JMenuItem implements SwingConstants,
      * Creates a menu item whose properties are taken from the
      * Action supplied.
      *
+     * @param a the action of the {@code JCheckBoxMenuItem}
      * @since 1.3
      */
     public JCheckBoxMenuItem(Action a) {
@@ -138,8 +139,8 @@ public class JCheckBoxMenuItem extends JMenuItem implements SwingConstants,
     /**
      * Creates an initially unselected check box menu item with the specified text and icon.
      *
-     * @param text the text of the CheckBoxMenuItem
-     * @param icon the icon of the CheckBoxMenuItem
+     * @param text the text of the {@code JCheckBoxMenuItem}
+     * @param icon the icon of the {@code JCheckBoxMenuItem}
      */
     public JCheckBoxMenuItem(String text, Icon icon) {
         this(text, icon, false);
diff --git a/jdk/src/share/classes/javax/swing/JEditorPane.java b/jdk/src/share/classes/javax/swing/JEditorPane.java
index d650c4816e8e7e3ffaa1f75714cb2d5718e7fabb..42951731ec1776781d1d6bcf41642b786650219f 100644
--- a/jdk/src/share/classes/javax/swing/JEditorPane.java
+++ b/jdk/src/share/classes/javax/swing/JEditorPane.java
@@ -1251,11 +1251,12 @@ public class JEditorPane extends JTextComponent {
     }
 
     /**
-     * Returns the currently registered <code>EditorKit</code>
-     * class name for the type <code>type</code>.
-     *
-     * @param type  the non-<code>null</code> content type
+     * Returns the currently registered {@code EditorKit} class name for the
+     * type {@code type}.
      *
+     * @param type  the non-{@code null} content type
+     * @return a {@code String} containing the {@code EditorKit} class name
+     *         for {@code type}
      * @since 1.3
      */
     public static String getEditorKitClassNameForContentType(String type) {
diff --git a/jdk/src/share/classes/javax/swing/JFileChooser.java b/jdk/src/share/classes/javax/swing/JFileChooser.java
index 336f57c438b940254a4cffbfc17998dbfa3feaf8..bf690ddbb5b6a12064fb0099b9e555e70fb78dbe 100644
--- a/jdk/src/share/classes/javax/swing/JFileChooser.java
+++ b/jdk/src/share/classes/javax/swing/JFileChooser.java
@@ -330,6 +330,8 @@ public class JFileChooser extends JComponent implements Accessible {
     /**
      * Constructs a <code>JFileChooser</code> using the given
      * <code>FileSystemView</code>.
+     *
+     * @param fsv a {@code FileSystemView}
      */
     public JFileChooser(FileSystemView fsv) {
         this((File) null, fsv);
@@ -339,6 +341,10 @@ public class JFileChooser extends JComponent implements Accessible {
     /**
      * Constructs a <code>JFileChooser</code> using the given current directory
      * and <code>FileSystemView</code>.
+     *
+     * @param currentDirectory a {@code File} object specifying the path to a
+     *                         file or directory
+     * @param fsv a {@code FileSystemView}
      */
     public JFileChooser(File currentDirectory, FileSystemView fsv) {
         setup(fsv);
@@ -348,6 +354,10 @@ public class JFileChooser extends JComponent implements Accessible {
     /**
      * Constructs a <code>JFileChooser</code> using the given current directory
      * path and <code>FileSystemView</code>.
+     *
+     * @param currentDirectoryPath a {@code String} specifying the path to a file
+     *                             or directory
+     * @param fsv a {@code FileSystemView}
      */
     public JFileChooser(String currentDirectoryPath, FileSystemView fsv) {
         setup(fsv);
@@ -360,6 +370,8 @@ public class JFileChooser extends JComponent implements Accessible {
 
     /**
      * Performs common constructor initialization and setup.
+     *
+     * @param view the {@code FileSystemView} used for setup
      */
     protected void setup(FileSystemView view) {
         installShowFilesListener();
@@ -512,6 +524,8 @@ public class JFileChooser extends JComponent implements Accessible {
     /**
      * Returns a list of selected files if the file chooser is
      * set to allow multiple selection.
+     *
+     * @return an array of selected {@code File}s
      */
     public File[] getSelectedFiles() {
         if(selectedFiles == null) {
@@ -525,6 +539,7 @@ public class JFileChooser extends JComponent implements Accessible {
      * Sets the list of selected files if the file chooser is
      * set to allow multiple selection.
      *
+     * @param selectedFiles an array {@code File}s to be selected
      * @beaninfo
      *       bound: true
      * description: The list of selected files if the chooser is in multiple selection mode.
@@ -971,6 +986,7 @@ public class JFileChooser extends JComponent implements Accessible {
     /**
      * Gets the string that goes in the <code>JFileChooser</code>'s titlebar.
      *
+     * @return the string from the {@code JFileChooser} window's title bar
      * @see #setDialogTitle
      */
     public String getDialogTitle() {
@@ -1158,6 +1174,8 @@ public class JFileChooser extends JComponent implements Accessible {
      * Removes a filter from the list of user choosable file filters. Returns
      * true if the file filter was removed.
      *
+     * @param f the file filter to be removed
+     * @return true if the file filter was removed, false otherwise
      * @see #addChoosableFileFilter
      * @see #getChoosableFileFilters
      * @see #resetChoosableFileFilters
@@ -1215,6 +1233,8 @@ public class JFileChooser extends JComponent implements Accessible {
     /**
      * Returns the <code>AcceptAll</code> file filter.
      * For example, on Microsoft Windows this would be All Files (*.*).
+     *
+     * @return the {@code AcceptAll} file filter
      */
     public FileFilter getAcceptAllFileFilter() {
         FileFilter filter = null;
@@ -1240,8 +1260,10 @@ public class JFileChooser extends JComponent implements Accessible {
     * If false, the <code>AcceptAll</code> file filter is removed from
     * the list of available file filters.
     * If true, the <code>AcceptAll</code> file filter will become the
-    * the actively used file filter.
+    * actively used file filter.
     *
+    * @param b a {@code boolean} which determines whether the {@code AcceptAll}
+    *          file filter is an available choice in the choosable filter list
     * @beaninfo
     *   preferred: true
     *       bound: true
@@ -1284,6 +1306,7 @@ public class JFileChooser extends JComponent implements Accessible {
      * any listeners that the accessory might have registered with the
      * file chooser.
      *
+     * @param newAccessory the accessory component to be set
      * @beaninfo
      *   preferred: true
      *       bound: true
@@ -1355,6 +1378,7 @@ public class JFileChooser extends JComponent implements Accessible {
      * Convenience call that determines if files are selectable based on the
      * current file selection mode.
      *
+     * @return true if files are selectable, false otherwise
      * @see #setFileSelectionMode
      * @see #getFileSelectionMode
      */
@@ -1366,6 +1390,7 @@ public class JFileChooser extends JComponent implements Accessible {
      * Convenience call that determines if directories are selectable based
      * on the current file selection mode.
      *
+     * @return true if directories are selectable, false otherwise
      * @see #setFileSelectionMode
      * @see #getFileSelectionMode
      */
@@ -1487,9 +1512,10 @@ public class JFileChooser extends JComponent implements Accessible {
     }
 
     /**
-     * Sets the file view to used to retrieve UI information, such as
+     * Sets the file view to be used to retrieve UI information, such as
      * the icon that represents a file or the type description of a file.
      *
+     * @param fileView a {@code FileView} to be used to retrieve UI information
      * @beaninfo
      *   preferred: true
      *       bound: true
@@ -1506,6 +1532,7 @@ public class JFileChooser extends JComponent implements Accessible {
     /**
      * Returns the current file view.
      *
+     * @return the current file view
      * @see #setFileView
      */
     public FileView getFileView() {
@@ -1765,6 +1792,8 @@ public class JFileChooser extends JComponent implements Accessible {
      * notification on this event type. The event instance
      * is lazily created using the <code>command</code> parameter.
      *
+     * @param command a string that may specify a command associated with
+     *                the event
      * @see EventListenerList
      */
     protected void fireActionPerformed(String command) {
@@ -1973,6 +2002,9 @@ public class JFileChooser extends JComponent implements Accessible {
 // Accessibility support
 ////////////////
 
+    /**
+     * {@code AccessibleContext} associated with this {@code JFileChooser}
+     */
     protected AccessibleContext accessibleContext = null;
 
     /**
diff --git a/jdk/src/share/classes/javax/swing/JFrame.java b/jdk/src/share/classes/javax/swing/JFrame.java
index e4a5efef662d11de2e9273315fd84729d2b14aee..cc3b0807f967a4bcdb6ffb1a9a1a40ff43e99f91 100644
--- a/jdk/src/share/classes/javax/swing/JFrame.java
+++ b/jdk/src/share/classes/javax/swing/JFrame.java
@@ -275,6 +275,8 @@ public class JFrame  extends Frame implements WindowConstants,
     /**
      * Called by the constructor methods to create the default
      * <code>rootPane</code>.
+     *
+     * @return a new {@code JRootPane}
      */
     protected JRootPane createRootPane() {
         JRootPane rp = new JRootPane();
@@ -874,7 +876,9 @@ public class JFrame  extends Frame implements WindowConstants,
 // Accessibility support
 ////////////////
 
-    /** The accessible context property. */
+    /**
+     * The accessible context property.
+     */
     protected AccessibleContext accessibleContext = null;
 
     /**
diff --git a/jdk/src/share/classes/javax/swing/JMenu.java b/jdk/src/share/classes/javax/swing/JMenu.java
index ea3b1b970d3576b66f9e1055f721ba4760a6b754..02285e0047fe563bd64b4df240dbb580526943ec 100644
--- a/jdk/src/share/classes/javax/swing/JMenu.java
+++ b/jdk/src/share/classes/javax/swing/JMenu.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -608,16 +608,18 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement
      * it to the end of this menu.
      *
      * @param s the string for the menu item to be added
+     * @return the new {@code JMenuItem}
      */
     public JMenuItem add(String s) {
         return add(new JMenuItem(s));
     }
 
     /**
-     * Creates a new menu item attached to the specified
-     * <code>Action</code> object and appends it to the end of this menu.
+     * Creates a new menu item attached to the specified {@code Action} object
+     * and appends it to the end of this menu.
      *
-     * @param a the <code>Action</code> for the menu item to be added
+     * @param a the {@code Action} for the menu item to be added
+     * @return the new {@code JMenuItem}
      * @see Action
      */
     public JMenuItem add(Action a) {
@@ -653,8 +655,11 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement
     }
 
     /**
-     * Returns a properly configured <code>PropertyChangeListener</code>
-     * which updates the control as changes to the <code>Action</code> occur.
+     * Returns a properly configured {@code PropertyChangeListener}
+     * which updates the control as changes to the {@code Action} occur.
+     *
+     * @param b a menu item for which to create a {@code PropertyChangeListener}
+     * @return a {@code PropertyChangeListener} for {@code b}
      */
     protected PropertyChangeListener createActionChangeListener(JMenuItem b) {
         return b.createActionPropertyChangeListener0(b.getAction());
@@ -714,6 +719,7 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement
      * @param a the <code>Action</code> object for the menu item to add
      * @param pos an integer specifying the position at which to add the
      *               new menu item
+     * @return the new menu item
      * @exception IllegalArgumentException if the value of
      *                  <code>pos</code> &lt; 0
      */
@@ -748,16 +754,16 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement
     }
 
     /**
-     * Returns the <code>JMenuItem</code> at the specified position.
-     * If the component at <code>pos</code> is not a menu item,
-     * <code>null</code> is returned.
+     * Returns the {@code JMenuItem} at the specified position.
+     * If the component at {@code pos} is not a menu item,
+     * {@code null} is returned.
      * This method is included for AWT compatibility.
      *
-     * @param pos    an integer specifying the position
-     * @exception   IllegalArgumentException if the value of
-     *                       <code>pos</code> &lt; 0
+     * @param pos  an integer specifying the position
      * @return  the menu item at the specified position; or <code>null</code>
      *          if the item as the specified position is not a menu item
+     * @exception  IllegalArgumentException if the value of
+     *             {@code pos} &lt; 0
      */
     public JMenuItem getItem(int pos) {
         if (pos < 0) {
@@ -975,6 +981,8 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement
     /**
      * Returns the popupmenu associated with this menu.  If there is
      * no popupmenu, it will create one.
+     *
+     * @return the {@code JPopupMenu} associated with this menu
      */
     public JPopupMenu getPopupMenu() {
         ensurePopupMenuCreated();
@@ -1159,6 +1167,8 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement
         JPopupMenu popupMenu;
         /**
          *  Create the window listener for the specified popup.
+         *
+         * @param p the popup menu for which to create a listener
          * @since 1.4
          */
         public WinListener(JPopupMenu p) {
diff --git a/jdk/src/share/classes/javax/swing/JMenuBar.java b/jdk/src/share/classes/javax/swing/JMenuBar.java
index 4b4f6f916437d3a042d7f6e3c9ff1c6b02787181..c8fcb6673c614c1c3a8cdca9efb0ddd7d3b60563 100644
--- a/jdk/src/share/classes/javax/swing/JMenuBar.java
+++ b/jdk/src/share/classes/javax/swing/JMenuBar.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -124,6 +124,8 @@ public class JMenuBar extends JComponent implements Accessible,MenuElement
 
     /**
      * Returns the menubar's current UI.
+     *
+     * @return a {@code MenuBarUI} which is the menubar's current L&amp;F object
      * @see #setUI
      */
     public MenuBarUI getUI() {
diff --git a/jdk/src/share/classes/javax/swing/JSlider.java b/jdk/src/share/classes/javax/swing/JSlider.java
index 09129a479f0545bdac3cdfa992a9aca12963ccfa..a2524d9b244ed8f2de0cb79c4c563415a8e94c69 100644
--- a/jdk/src/share/classes/javax/swing/JSlider.java
+++ b/jdk/src/share/classes/javax/swing/JSlider.java
@@ -281,6 +281,8 @@ public class JSlider extends JComponent implements SwingConstants, Accessible {
     /**
      * Creates a horizontal slider using the specified
      * BoundedRangeModel.
+     *
+     * @param brm a {@code BoundedRangeModel} for the slider
      */
     public JSlider(BoundedRangeModel brm)
     {
@@ -363,6 +365,8 @@ public class JSlider extends JComponent implements SwingConstants, Accessible {
      * {@code fireStateChanged} method to forward {@code ChangeEvent}s
      * to the {@code ChangeListener}s that have been added directly to the
      * slider.
+     *
+     * @return a instance of new {@code ChangeListener}
      * @see #changeListener
      * @see #fireStateChanged
      * @see javax.swing.event.ChangeListener
diff --git a/jdk/src/share/classes/javax/swing/JTabbedPane.java b/jdk/src/share/classes/javax/swing/JTabbedPane.java
index c3b135ac85e07f263cc97e58975db21e1138c54d..96c050529fe3db541b9c074d0786a9f35b07deb7 100644
--- a/jdk/src/share/classes/javax/swing/JTabbedPane.java
+++ b/jdk/src/share/classes/javax/swing/JTabbedPane.java
@@ -278,6 +278,7 @@ public class JTabbedPane extends JComponent
      * can override this to return a subclass of <code>ModelListener</code> or
      * another <code>ChangeListener</code> implementation.
      *
+     * @return a {@code ChangeListener}
      * @see #fireStateChanged
      */
     protected ChangeListener createChangeListener() {
@@ -423,6 +424,7 @@ public class JTabbedPane extends JComponent
     /**
      * Returns the model associated with this tabbedpane.
      *
+     * @return the {@code SingleSelectionModel} associated with this tabbedpane
      * @see #setModel
      */
     public SingleSelectionModel getModel() {
@@ -459,6 +461,8 @@ public class JTabbedPane extends JComponent
 
     /**
      * Returns the placement of the tabs for this tabbedpane.
+     *
+     * @return an {@code int} specifying the placement for the tabs
      * @see #setTabPlacement
      */
     public int getTabPlacement() {
@@ -507,6 +511,8 @@ public class JTabbedPane extends JComponent
     /**
      * Returns the policy used by the tabbedpane to layout the tabs when all the
      * tabs will not fit within a single run.
+     *
+     * @return an {@code int} specifying the policy used to layout the tabs
      * @see #setTabLayoutPolicy
      * @since 1.4
      */
@@ -664,6 +670,7 @@ public class JTabbedPane extends JComponent
      * will automatically set the <code>selectedIndex</code> to the index
      * corresponding to the specified component.
      *
+     * @param c the selected {@code Component} for this {@code TabbedPane}
      * @exception IllegalArgumentException if component not found in tabbed
      *          pane
      * @see #getSelectedComponent
diff --git a/jdk/src/share/classes/javax/swing/JTable.java b/jdk/src/share/classes/javax/swing/JTable.java
index f4573926a950df40b6a44888604f4b4894dd5ddd..1c7f72c947deb985d077e25b5630b98a3ee0f12e 100644
--- a/jdk/src/share/classes/javax/swing/JTable.java
+++ b/jdk/src/share/classes/javax/swing/JTable.java
@@ -865,6 +865,8 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
     /**
      * Equivalent to <code>new JScrollPane(aTable)</code>.
      *
+     * @param aTable a {@code JTable} to be used for the scroll pane
+     * @return a {@code JScrollPane} created using {@code aTable}
      * @deprecated As of Swing version 1.0.2,
      * replaced by <code>new JScrollPane(aTable)</code>.
      */
@@ -1961,6 +1963,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
      * <code>JList</code>. See the <code>setSelectionMode</code> method
      * in <code>JList</code> for details about the modes.
      *
+     * @param selectionMode the mode used by the row and column selection models
      * @see JList#setSelectionMode
      * @beaninfo
      * description: The selection mode used by the row and column selection models.
@@ -2321,6 +2324,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
      * Returns true if the specified index is in the valid range of rows,
      * and the row at that index is selected.
      *
+     * @param row a row in the row model
      * @return true if <code>row</code> is a valid index and the row at
      *              that index is selected (where 0 is the first row)
      */
@@ -3174,6 +3178,8 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
 
     /**
      * Sizes the table columns to fit the available space.
+     *
+     * @param lastColumnOnly determines whether to resize last column only
      * @deprecated As of Swing version 1.0.3,
      * replaced by <code>doLayout()</code>.
      * @see #doLayout
@@ -6692,7 +6698,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
 
     // Listeners to echo changes to the AccessiblePropertyChange mechanism
 
-        /*
+        /**
          * Describes a change in the accessible table model.
          */
         protected class AccessibleJTableModelChange
@@ -6737,6 +6743,8 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
 
         /**
          * Track changes to the table contents
+         *
+         * @param e a {@code TableModelEvent} describing the event
          */
         public void tableChanged(TableModelEvent e) {
            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
@@ -6764,6 +6772,8 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
 
         /**
          * Track changes to the table contents (row insertions)
+         *
+         * @param e a {@code TableModelEvent} describing the event
          */
         public void tableRowsInserted(TableModelEvent e) {
            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
@@ -6789,6 +6799,8 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
 
         /**
          * Track changes to the table contents (row deletions)
+         *
+         * @param e a {@code TableModelEvent} describing the event
          */
         public void tableRowsDeleted(TableModelEvent e) {
            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
@@ -7922,6 +7934,11 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
 
             /**
              *  Constructs an <code>AccessibleJTableHeaderEntry</code>.
+             *
+             * @param t a {@code JTable}
+             * @param r an {@code int} specifying a row
+             * @param c an {@code int} specifying a column
+             * @param i an {@code int} specifying the index to this cell
              * @since 1.4
              */
             public AccessibleJTableCell(JTable t, int r, int c, int i) {
diff --git a/jdk/src/share/classes/javax/swing/MenuElement.java b/jdk/src/share/classes/javax/swing/MenuElement.java
index 916811e08eb7ab6b2b05bc5fe3ee2a55c3e04500..4dc310b55bcb616c8e03df598fd2129182448a2a 100644
--- a/jdk/src/share/classes/javax/swing/MenuElement.java
+++ b/jdk/src/share/classes/javax/swing/MenuElement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -29,7 +29,7 @@ import java.awt.event.*;
 
 /**
  * Any component that can be placed into a menu should implement this interface.
- * This interface is used by <code>MenuSelectionManager</code>
+ * This interface is used by {@code MenuSelectionManager}
  * to handle selection and navigation in menu hierarchies.
  *
  * @author Arnaud Weber
@@ -39,46 +39,56 @@ import java.awt.event.*;
 public interface MenuElement {
 
     /**
-     * Processes a mouse event. <code>event</code> is a <code>MouseEvent</code>
-     * with source being the receiving element's component.
-     * <code>path</code> is the path of the receiving element in the menu
-     * hierarchy including the receiving element itself.
-     * <code>manager</code> is the <code>MenuSelectionManager</code>
-     * for the menu hierarchy.
-     * This method should process the <code>MouseEvent</code> and change
-     * the menu selection if necessary
-     * by using <code>MenuSelectionManager</code>'s API
-     * Note: you do not have to forward the event to sub-components.
-     * This is done automatically by the <code>MenuSelectionManager</code>.
+     * Processes a mouse event. {@code event} is a {@code MouseEvent} with
+     * source being the receiving element's component. {@code path} is the
+     * path of the receiving element in the menu hierarchy including the
+     * receiving element itself. {@code manager} is the
+     * {@code MenuSelectionManager}for the menu hierarchy. This method should
+     * process the {@code MouseEvent} and change the menu selection if necessary
+     * by using {@code MenuSelectionManager}'s API Note: you do not have to
+     * forward the event to sub-components. This is done automatically by the
+     * {@code MenuSelectionManager}.
+     *
+     * @param event a {@code MouseEvent} to be processed
+     * @param path the path of the receiving element in the menu hierarchy
+     * @param manager the {@code MenuSelectionManager} for the menu hierarchy
      */
-    public void processMouseEvent(MouseEvent event,MenuElement path[],MenuSelectionManager manager);
+    public void processMouseEvent(MouseEvent event, MenuElement path[], MenuSelectionManager manager);
 
 
     /**
      *  Process a key event.
+     *
+     * @param event a {@code KeyEvent} to be processed
+     * @param path the path of the receiving element in the menu hierarchy
+     * @param manager the {@code MenuSelectionManager} for the menu hierarchy
      */
-    public void processKeyEvent(KeyEvent event,MenuElement path[],MenuSelectionManager manager);
+    public void processKeyEvent(KeyEvent event, MenuElement path[], MenuSelectionManager manager);
 
     /**
-     * Call by the <code>MenuSelectionManager</code> when the
-     * <code>MenuElement</code> is added or remove from
-     * the menu selection.
+     * Call by the {@code MenuSelectionManager} when the {@code MenuElement} is
+     * added or removed from the menu selection.
+     *
+     * @param isIncluded can be used to indicate if this {@code MenuElement} is
+     *        active (if it is a menu) or is on the part of the menu path that
+     *        changed (if it is a menu item).
      */
     public void menuSelectionChanged(boolean isIncluded);
 
     /**
-     * This method should return an array containing the sub-elements for the receiving menu element
+     * This method should return an array containing the sub-elements for the
+     * receiving menu element.
      *
-     * @return an array of MenuElements
+     * @return an array of {@code MenuElement}s
      */
     public MenuElement[] getSubElements();
 
     /**
-     * This method should return the java.awt.Component used to paint the receiving element.
-     * The returned component will be used to convert events and detect if an event is inside
-     * a MenuElement's component.
+     * This method should return the {@code java.awt.Component} used to paint the
+     * receiving element. The returned component will be used to convert events
+     * and detect if an event is inside a {@code MenuElement}'s component.
      *
-     * @return the Component value
+     * @return the {@code Component} value
      */
     public Component getComponent();
 }
diff --git a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java
index 8a691c1b9cd0da15fe2adff5f3a8e3fc8560c8e3..dda2736eb499c3a0115e175dc873f5e93ce93a1d 100644
--- a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java
+++ b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java
@@ -80,6 +80,7 @@ public class MenuSelectionManager {
      * generated is always "this".
      */
     protected transient ChangeEvent changeEvent = null;
+    /** The collection of registered listeners */
     protected EventListenerList listenerList = new EventListenerList();
 
     /**
@@ -477,7 +478,11 @@ public class MenuSelectionManager {
     }
 
     /**
-     * Return true if c is part of the currently used menu
+     * Return true if {@code c} is part of the currently used menu
+     *
+     * @param c a {@code Component}
+     * @return true if {@code c} is part of the currently used menu,
+     *         false otherwise
      */
     public boolean isComponentPartOfCurrentMenu(Component c) {
         if(selection.size() > 0) {
diff --git a/jdk/src/share/classes/javax/swing/RowFilter.java b/jdk/src/share/classes/javax/swing/RowFilter.java
index 8201add8bdcbdf1295823ac37831b7bfb4081e1e..bdcdb15786bbeca5a41e374e44a8fb07b9209313 100644
--- a/jdk/src/share/classes/javax/swing/RowFilter.java
+++ b/jdk/src/share/classes/javax/swing/RowFilter.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, 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
@@ -159,6 +159,8 @@ public abstract class RowFilter<M,I> {
      * {@link java.util.regex.Pattern} for a complete description of
      * the supported regular-expression constructs.
      *
+     * @param <M> the type of the model to which the {@code RowFilter} applies
+     * @param <I> the type of the identifier passed to the {@code RowFilter}
      * @param regex the regular expression to filter on
      * @param indices the indices of the values to check.  If not supplied all
      *               values are evaluated
@@ -186,6 +188,8 @@ public abstract class RowFilter<M,I> {
      *   RowFilter.dateFilter(ComparisonType.AFTER, new Date());
      * </pre>
      *
+     * @param <M> the type of the model to which the {@code RowFilter} applies
+     * @param <I> the type of the identifier passed to the {@code RowFilter}
      * @param type the type of comparison to perform
      * @param date the date to compare against
      * @param indices the indices of the values to check.  If not supplied all
@@ -214,7 +218,10 @@ public abstract class RowFilter<M,I> {
      *   RowFilter.numberFilter(ComparisonType.EQUAL, 10);
      * </pre>
      *
+     * @param <M> the type of the model to which the {@code RowFilter} applies
+     * @param <I> the type of the identifier passed to the {@code RowFilter}
      * @param type the type of comparison to perform
+     * @param number a {@code Number} value to compare against
      * @param indices the indices of the values to check.  If not supplied all
      *               values are evaluated
      * @return a <code>RowFilter</code> implementing the specified criteria
@@ -241,6 +248,8 @@ public abstract class RowFilter<M,I> {
      *   RowFilter&lt;Object,Object&gt; fooBarFilter = RowFilter.orFilter(filters);
      * </pre>
      *
+     * @param <M> the type of the model to which the {@code RowFilter} applies
+     * @param <I> the type of the identifier passed to the {@code RowFilter}
      * @param filters the <code>RowFilter</code>s to test
      * @throws IllegalArgumentException if any of the filters
      *         are <code>null</code>
@@ -267,6 +276,8 @@ public abstract class RowFilter<M,I> {
      *   RowFilter&lt;Object,Object&gt; fooBarFilter = RowFilter.andFilter(filters);
      * </pre>
      *
+     * @param <M> the type of the model the {@code RowFilter} applies to
+     * @param <I> the type of the identifier passed to the {@code RowFilter}
      * @param filters the <code>RowFilter</code>s to test
      * @return a <code>RowFilter</code> implementing the specified criteria
      * @throws IllegalArgumentException if any of the filters
@@ -283,6 +294,8 @@ public abstract class RowFilter<M,I> {
      * Returns a <code>RowFilter</code> that includes entries if the
      * supplied filter does not include the entry.
      *
+     * @param <M> the type of the model to which the {@code RowFilter} applies
+     * @param <I> the type of the identifier passed to the {@code RowFilter}
      * @param filter the <code>RowFilter</code> to negate
      * @return a <code>RowFilter</code> implementing the specified criteria
      * @throws IllegalArgumentException if <code>filter</code> is
diff --git a/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java b/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java
index 2c4850b8ff44a5be257fc85f6450fcec642bc48b..c542ebc48f821117d5d093e26c6327b10b56e56a 100644
--- a/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java
+++ b/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java
@@ -100,6 +100,8 @@ public class SortingFocusTraversalPolicy
 
     /**
      * Constructs a SortingFocusTraversalPolicy with the specified Comparator.
+     *
+     * @param comparator the {@code Comparator} to sort by
      */
     public SortingFocusTraversalPolicy(Comparator<? super Component> comparator) {
         this.comparator = comparator;
diff --git a/jdk/src/share/classes/javax/swing/Spring.java b/jdk/src/share/classes/javax/swing/Spring.java
index 75b2a510f00aaebb11d3218a0f50fd061a61ccc2..366b95fec78f8541ce6e9ba4450152cfa16224e5 100644
--- a/jdk/src/share/classes/javax/swing/Spring.java
+++ b/jdk/src/share/classes/javax/swing/Spring.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, 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,9 +547,10 @@ public abstract class Spring {
 
 
     /**
-     * Returns <code>-s</code>: a spring running in the opposite direction to <code>s</code>.
+     * Returns {@code -s}: a spring running in the opposite direction to {@code s}.
      *
-     * @return <code>-s</code>: a spring running in the opposite direction to <code>s</code>
+     * @param s a {@code Spring} object
+     * @return {@code -s}: a spring running in the opposite direction to {@code s}
      *
      * @see Spring
      */
@@ -582,6 +583,8 @@ public abstract class Spring {
      * the <em>value</em>s of <code>s1</code> and <code>s2</code> is exactly equal to
      * the <em>value</em> of <code>s3</code>.
      *
+     * @param s1 a {@code Spring} object
+     * @param s2 a {@code Spring} object
      * @return <code>s1+s2</code>: a spring representing <code>s1</code> and <code>s2</code> in series
      *
      * @see Spring
@@ -591,11 +594,13 @@ public abstract class Spring {
      }
 
     /**
-     * Returns <code>max(s1, s2)</code>: a spring whose value is always greater than (or equal to)
-     *         the values of both <code>s1</code> and <code>s2</code>.
+     * Returns {@code max(s1, s2)}: a spring whose value is always greater than (or equal to)
+     *         the values of both {@code s1} and {@code s2}.
      *
-     * @return <code>max(s1, s2)</code>: a spring whose value is always greater than (or equal to)
-     *         the values of both <code>s1</code> and <code>s2</code>
+     * @param s1 a {@code Spring} object
+     * @param s2 a {@code Spring} object
+     * @return {@code max(s1, s2)}: a spring whose value is always greater than (or equal to)
+     *         the values of both {@code s1} and {@code s2}
      * @see Spring
      */
     public static Spring max(Spring s1, Spring s2) {
diff --git a/jdk/src/share/classes/javax/swing/UIManager.java b/jdk/src/share/classes/javax/swing/UIManager.java
index 951d0f6c239aaab437719095a9679bec06b44199..27f243b4d6c516531d5743f1d639ecf1c83eb470 100644
--- a/jdk/src/share/classes/javax/swing/UIManager.java
+++ b/jdk/src/share/classes/javax/swing/UIManager.java
@@ -1107,6 +1107,8 @@ public class UIManager implements Serializable
      * UI class is created or when the default look and feel is changed
      * on a component instance.
      * <p>Note these are not the same as the installed look and feels.
+     *
+     * @param laf the {@code LookAndFeel} to be removed
      * @return true if the <code>LookAndFeel</code> was removed from the list
      * @see #removeAuxiliaryLookAndFeel
      * @see #getAuxiliaryLookAndFeels
diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java
index 0004c32884901a6e083485cec0b6065de767047d..71a13c3605c42d4140d979276e87430605203794 100644
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java
@@ -221,24 +221,24 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
         }
 
         OutputStream os = new UnsyncBufferedOutputStream(bos);
-        try {
-            os.close();
-        } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
-            // Impossible
-        }
 
         DOMSubTreeData subTree = new DOMSubTreeData(localSiElem, true);
-
         try {
             ((DOMCanonicalizationMethod)
-                canonicalizationMethod).canonicalize(subTree, context, bos);
+                canonicalizationMethod).canonicalize(subTree, context, os);
         } catch (TransformException te) {
             throw new XMLSignatureException(te);
         }
 
+        try {
+            os.flush();
+        } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            // Impossible
+        }
+
         byte[] signedInfoBytes = bos.toByteArray();
 
         // this whole block should only be done if logging is enabled
@@ -253,6 +253,15 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
         }
 
         this.canonData = new ByteArrayInputStream(signedInfoBytes);
+
+        try {
+            os.close();
+        } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            // Impossible
+        }
     }
 
     public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
diff --git a/jdk/src/share/classes/sun/jvmstat/monitor/event/MonitorStatusChangeEvent.java b/jdk/src/share/classes/sun/jvmstat/monitor/event/MonitorStatusChangeEvent.java
index 618ef6f7a3eff544bcd272b450ee58c6819a8fca..0333151fbdfcc9cf778c5a45e4be5bc8a8a4c9df 100644
--- a/jdk/src/share/classes/sun/jvmstat/monitor/event/MonitorStatusChangeEvent.java
+++ b/jdk/src/share/classes/sun/jvmstat/monitor/event/MonitorStatusChangeEvent.java
@@ -27,6 +27,7 @@ package sun.jvmstat.monitor.event;
 
 import java.util.List;
 import sun.jvmstat.monitor.MonitoredVm;
+import sun.jvmstat.monitor.Monitor;
 
 /**
  * Provides a description of a change in status of the instrumentation
@@ -42,13 +43,13 @@ public class MonitorStatusChangeEvent extends VmEvent {
      * List of instrumentation objects inserted since the last event.
      * Elements of this list will always be of type Monitor.
      */
-    protected List inserted;
+    protected List<Monitor> inserted;
 
     /**
      * List of instrumentation objects removed since the last event.
      * Elements of this list will always be of type Monitor.
      */
-    protected List removed;
+    protected List<Monitor> removed;
 
     /**
      * Construct a new MonitorStatusChangeEvent.
@@ -59,8 +60,8 @@ public class MonitorStatusChangeEvent extends VmEvent {
      * @param removed the list of instrumentation objects removed since
      *                the last event.
      */
-    public MonitorStatusChangeEvent(MonitoredVm vm, List inserted,
-                                    List removed) {
+    public MonitorStatusChangeEvent(MonitoredVm vm, List<Monitor> inserted,
+                                    List<Monitor> removed) {
         super(vm);
         this.inserted = inserted;
         this.removed = removed;
@@ -75,7 +76,7 @@ public class MonitorStatusChangeEvent extends VmEvent {
      *                new instrumentation was inserted, an emply List is
      *                returned.
      */
-    public List getInserted() {
+    public List<Monitor> getInserted() {
         return inserted;
     }
 
@@ -87,7 +88,7 @@ public class MonitorStatusChangeEvent extends VmEvent {
      *                instrumentation exported by the MonitoredHost. If no
      *                instrumentation was removed, an emply List is returned.
      */
-    public List getRemoved() {
+    public List<Monitor> getRemoved() {
         return removed;
     }
 }
diff --git a/jdk/src/share/classes/sun/jvmstat/monitor/event/VmStatusChangeEvent.java b/jdk/src/share/classes/sun/jvmstat/monitor/event/VmStatusChangeEvent.java
index 73509a0a2bb45f591a87165c3dc0cb850561c8ef..176d56bd8977e8ce9ca823497902f34d1c6de4ce 100644
--- a/jdk/src/share/classes/sun/jvmstat/monitor/event/VmStatusChangeEvent.java
+++ b/jdk/src/share/classes/sun/jvmstat/monitor/event/VmStatusChangeEvent.java
@@ -44,7 +44,7 @@ public class VmStatusChangeEvent extends HostEvent {
      * active Java Virtual Machine on the MonitoredHost. This Set will only
      * contain Integer objects.
      */
-    protected Set active;
+    protected Set<Integer> active;
 
     /**
      * The set of Java Virtual Machines started on MonitoredHost since the
@@ -52,7 +52,7 @@ public class VmStatusChangeEvent extends HostEvent {
      * <em>lvmid</em> for each Java Virtual Machine started on the
      * MonitoredHost. This Set will only contain Integer objects.
      */
-    protected Set started;
+    protected Set<Integer> started;
 
     /**
      * The set of Java Virtual Machines terminated on MonitoredHost since the
@@ -60,7 +60,7 @@ public class VmStatusChangeEvent extends HostEvent {
      * <em>lvmid</em> for each Java Virtual Machine started on the
      * MonitoredHost. This Set will only contain Integer objects.
      */
-    protected Set terminated;
+    protected Set<Integer> terminated;
 
     /**
      * Construct a new VmStatusChangeEvent instance.
@@ -72,8 +72,8 @@ public class VmStatusChangeEvent extends HostEvent {
      * @param terminated the set of Java Virtual Machines terminated since
      *                   the last event.
      */
-    public VmStatusChangeEvent(MonitoredHost host, Set active,
-                               Set started, Set terminated) {
+    public VmStatusChangeEvent(MonitoredHost host, Set<Integer> active,
+                               Set<Integer> started, Set<Integer> terminated) {
         super(host);
         this.active = active;
         this.started = started;
@@ -90,7 +90,7 @@ public class VmStatusChangeEvent extends HostEvent {
      *               there are no active Java Virtual Machines on the host,
      *               an empty Set is returned.
      */
-    public Set getActive() {
+    public Set<Integer> getActive() {
         return active;
     }
 
@@ -105,7 +105,7 @@ public class VmStatusChangeEvent extends HostEvent {
      *               no Java Virtual Machines were recently started on the
      *               host, an empty Set is returned.
      */
-    public Set getStarted() {
+    public Set<Integer> getStarted() {
         return started;
     }
 
@@ -120,7 +120,7 @@ public class VmStatusChangeEvent extends HostEvent {
      *               no Java Virtual Machines were recently terminated on the
      *               host, an empty Set is returned.
      */
-    public Set getTerminated() {
+    public Set<Integer> getTerminated() {
         return terminated;
     }
 }
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/AbstractPerfDataBuffer.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/AbstractPerfDataBuffer.java
index 1a1820a53bab32567a603eb08c6abe8b46992776..90931ecc00a135671ad47b3f689598ab9dfc2698 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/AbstractPerfDataBuffer.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/AbstractPerfDataBuffer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -169,7 +169,7 @@ public abstract class AbstractPerfDataBuffer {
 
         try {
             Class<?> implClass = Class.forName(classname);
-            Constructor cons = implClass.getConstructor(new Class[] {
+            Constructor<?> cons = implClass.getConstructor(new Class<?>[] {
                     Class.forName("java.nio.ByteBuffer"),
                     Integer.TYPE
             });
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/MonitorStatus.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/MonitorStatus.java
index 60697f2f0ded6945eaf20e58b8278ab3eed960cd..23e8f0633d384142de5b727319b33a7bb7431600 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/MonitorStatus.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/MonitorStatus.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -26,6 +26,7 @@
 package sun.jvmstat.perfdata.monitor;
 
 import java.util.List;
+import sun.jvmstat.monitor.Monitor;
 
 /**
  * Immutable class containing the list of inserted and deleted
@@ -39,12 +40,12 @@ public class MonitorStatus {
     /**
      * The list of Monitors inserted since the last query.
      */
-    protected List inserted;
+    protected List<Monitor> inserted;
 
     /**
      * The list of Monitors removed since the last query.
      */
-    protected List removed;
+    protected List<Monitor> removed;
 
     /**
      * Create a MonitorStatus instance.
@@ -52,7 +53,7 @@ public class MonitorStatus {
      * @param inserted the list of Monitors inserted
      * @param removed the list of Monitors removed
      */
-    public MonitorStatus(List inserted, List removed) {
+    public MonitorStatus(List<Monitor> inserted, List<Monitor> removed) {
         this.inserted = inserted;
         this.removed = removed;
     }
@@ -62,7 +63,7 @@ public class MonitorStatus {
      *
      * @return List - the List of Monitor objects inserted or an empty List.
      */
-    public List getInserted() {
+    public List<Monitor> getInserted() {
         return inserted;
     }
 
@@ -71,7 +72,7 @@ public class MonitorStatus {
      *
      * @return List - the List of Monitor objects removed or an empty List.
      */
-    public List getRemoved() {
+    public List<Monitor> getRemoved() {
         return removed;
     }
 }
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/PerfDataBufferImpl.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/PerfDataBufferImpl.java
index e1a5a380841c7453a568458066eaa67afc57902e..2bde91cf719c48badd77c8347bf01d79e325fba5 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/PerfDataBufferImpl.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/PerfDataBufferImpl.java
@@ -66,7 +66,7 @@ public abstract class PerfDataBufferImpl {
     /**
      * A cache of resolved monitor aliases.
      */
-    protected Map aliasCache;
+    protected Map<String, Monitor> aliasCache;
 
 
     /**
@@ -79,9 +79,9 @@ public abstract class PerfDataBufferImpl {
     protected PerfDataBufferImpl(ByteBuffer buffer, int lvmid) {
         this.buffer = buffer;
         this.lvmid = lvmid;
-        this.monitors = new TreeMap<String, Monitor>();
-        this.aliasMap = new HashMap<String, ArrayList<String>>();
-        this.aliasCache = new HashMap();
+        this.monitors = new TreeMap<>();
+        this.aliasMap = new HashMap<>();
+        this.aliasCache = new HashMap<>();
     }
 
     /**
@@ -200,12 +200,12 @@ public abstract class PerfDataBufferImpl {
     protected Monitor findByAlias(String name) {
         assert Thread.holdsLock(this);
 
-        Monitor  m = (Monitor)aliasCache.get(name);
+        Monitor  m = aliasCache.get(name);
         if (m == null) {
-            ArrayList al = aliasMap.get(name);
+            ArrayList<String> al = aliasMap.get(name);
             if (al != null) {
-                for (Iterator i = al.iterator(); i.hasNext() && m == null; ) {
-                    String alias = (String)i.next();
+                for (Iterator<String> i = al.iterator(); i.hasNext() && m == null; ) {
+                    String alias = i.next();
                     m = monitors.get(alias);
                 }
             }
@@ -287,21 +287,21 @@ public abstract class PerfDataBufferImpl {
 
         Pattern pattern = Pattern.compile(patternString);
         Matcher matcher = pattern.matcher("");
-        List<Monitor> matches = new ArrayList<Monitor>();
+        List<Monitor> matches = new ArrayList<>();
 
-        Set monitorSet = monitors.entrySet();
+        Set<Map.Entry<String,Monitor>> monitorSet = monitors.entrySet();
 
-        for (Iterator i = monitorSet.iterator(); i.hasNext(); /* empty */) {
-            Map.Entry me = (Map.Entry)i.next();
-            String name = (String)me.getKey();
-            Monitor m = (Monitor)me.getValue();
+        for (Iterator<Map.Entry<String, Monitor>> i = monitorSet.iterator(); i.hasNext(); /* empty */) {
+            Map.Entry<String, Monitor> me = i.next();
+            String name = me.getKey();
+            Monitor m = me.getValue();
 
             // apply pattern to monitor item name
             matcher.reset(name);
 
             // if the pattern matches, then add monitor to list
             if (matcher.lookingAt()) {
-                 matches.add((Monitor)me.getValue());
+                 matches.add(me.getValue());
             }
         }
         return matches;
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/LocalMonitoredVm.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/LocalMonitoredVm.java
index d9a9084f3b1bdefa32eb9a404d3cd17a5f7c8843..ca1b210aaac5c8d46ef79f3189c73814bf58f68c 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/LocalMonitoredVm.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/LocalMonitoredVm.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -143,16 +143,17 @@ public class LocalMonitoredVm extends AbstractMonitoredVm {
      * @param inserted List of Monitor objects inserted.
      * @param removed List of Monitor objects removed.
      */
-    void fireMonitorStatusChangedEvents(List inserted, List removed) {
+    @SuppressWarnings("unchecked") // Cast of result of clone
+    void fireMonitorStatusChangedEvents(List<Monitor> inserted, List<Monitor> removed) {
         MonitorStatusChangeEvent ev = null;
-        ArrayList registered = null;
+        ArrayList<VmListener> registered = null;
 
         synchronized (listeners) {
             registered = (ArrayList)listeners.clone();
         }
 
-        for (Iterator i = registered.iterator(); i.hasNext(); /* empty */) {
-            VmListener l = (VmListener)i.next();
+        for (Iterator<VmListener> i = registered.iterator(); i.hasNext(); /* empty */) {
+            VmListener l = i.next();
             // lazily create the event object;
             if (ev == null) {
                 ev = new MonitorStatusChangeEvent(this, inserted, removed);
@@ -190,8 +191,8 @@ public class LocalMonitoredVm extends AbstractMonitoredVm {
             super.run();
             try {
                 MonitorStatus status = getMonitorStatus();
-                List inserted = status.getInserted();
-                List removed = status.getRemoved();
+                List<Monitor> inserted = status.getInserted();
+                List<Monitor> removed = status.getRemoved();
 
                 if (!inserted.isEmpty() || !removed.isEmpty()) {
                     fireMonitorStatusChangedEvents(inserted, removed);
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/MonitoredHostProvider.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/MonitoredHostProvider.java
index 0b3ec64eac84a2dfeef657fabd353f60651657cc..851cde20b4878b40309c8d7e28875801771f72ab 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/MonitoredHostProvider.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/MonitoredHostProvider.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -160,17 +160,18 @@ public class MonitoredHostProvider extends MonitoredHost {
      * @param terminated a set of Integer objects containing the vmid of
      *                   terminated Vms since last interval.
      */
-    private void fireVmStatusChangedEvents(Set active, Set started,
-                                           Set terminated) {
-        ArrayList registered = null;
+    @SuppressWarnings("unchecked") // Cast of result of clone
+    private void fireVmStatusChangedEvents(Set<Integer> active, Set<Integer> started,
+                                           Set<Integer> terminated) {
+        ArrayList<HostListener> registered = null;
         VmStatusChangeEvent ev = null;
 
         synchronized(listeners) {
             registered = (ArrayList)listeners.clone();
         }
 
-        for (Iterator i = registered.iterator(); i.hasNext(); /* empty */) {
-            HostListener l = (HostListener)i.next();
+        for (Iterator<HostListener> i = registered.iterator(); i.hasNext(); /* empty */) {
+            HostListener l = i.next();
             if (ev == null) {
                 ev = new VmStatusChangeEvent(this, active, started, terminated);
             }
@@ -186,7 +187,7 @@ public class MonitoredHostProvider extends MonitoredHost {
             super.run();
 
             // save the last set of active JVMs
-            Set lastActiveVms = activeVms;
+            Set<Integer> lastActiveVms = activeVms;
 
             // get the current set of active JVMs
             activeVms = (HashSet<Integer>)vmManager.activeVms();
@@ -194,20 +195,20 @@ public class MonitoredHostProvider extends MonitoredHost {
             if (activeVms.isEmpty()) {
                 return;
             }
-            Set<Integer> startedVms = new HashSet<Integer>();
-            Set<Object> terminatedVms = new HashSet<Object>();
+            Set<Integer> startedVms = new HashSet<>();
+            Set<Integer> terminatedVms = new HashSet<>();
 
-            for (Iterator i = activeVms.iterator(); i.hasNext(); /* empty */) {
-                Integer vmid = (Integer)i.next();
+            for (Iterator<Integer> i = activeVms.iterator(); i.hasNext(); /* empty */) {
+                Integer vmid = i.next();
                 if (!lastActiveVms.contains(vmid)) {
                     // a new file has been detected, add to set
                     startedVms.add(vmid);
                 }
             }
 
-            for (Iterator i = lastActiveVms.iterator(); i.hasNext();
+            for (Iterator<Integer> i = lastActiveVms.iterator(); i.hasNext();
                     /* empty */) {
-                Object o = i.next();
+                Integer o = i.next();
                 if (!activeVms.contains(o)) {
                     // JVM has terminated, remove it from the active list
                     terminatedVms.add(o);
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/MonitoredHostProvider.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/MonitoredHostProvider.java
index 1b07c4e5faeefb60b8612563f6026213574e48bb..09467dc74ab856a60cc7d35d52854d8affcbd98a 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/MonitoredHostProvider.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/MonitoredHostProvider.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -246,17 +246,18 @@ public class MonitoredHostProvider extends MonitoredHost {
      *                   Vm Identifiers of terminated JVMs since last
      *                   interval.
      */
-    private void fireVmStatusChangedEvents(Set active, Set started,
-                                           Set terminated) {
-        ArrayList registered = null;
+    @SuppressWarnings("unchecked") // Cast of result of clone
+    private void fireVmStatusChangedEvents(Set<Integer> active, Set<Integer> started,
+                                           Set<Integer> terminated) {
+        ArrayList<HostListener> registered = null;
         VmStatusChangeEvent ev = null;
 
         synchronized(listeners) {
             registered = (ArrayList)listeners.clone();
         }
 
-        for (Iterator i = registered.iterator(); i.hasNext(); /* empty */) {
-            HostListener l = (HostListener)i.next();
+        for (Iterator<HostListener> i = registered.iterator(); i.hasNext(); /* empty */) {
+            HostListener l = i.next();
             if (ev == null) {
                 ev = new VmStatusChangeEvent(this, active, started, terminated);
             }
@@ -267,16 +268,17 @@ public class MonitoredHostProvider extends MonitoredHost {
     /**
      * Fire hostDisconnectEvent events.
      */
+    @SuppressWarnings("unchecked") // Cast of result of clone
     void fireDisconnectedEvents() {
-        ArrayList registered = null;
+        ArrayList<HostListener> registered = null;
         HostEvent ev = null;
 
         synchronized(listeners) {
             registered = (ArrayList)listeners.clone();
         }
 
-        for (Iterator i = registered.iterator(); i.hasNext(); /* empty */) {
-            HostListener l = (HostListener)i.next();
+        for (Iterator<HostListener> i = registered.iterator(); i.hasNext(); /* empty */) {
+            HostListener l = i.next();
             if (ev == null) {
                 ev = new HostEvent(this);
             }
@@ -292,7 +294,7 @@ public class MonitoredHostProvider extends MonitoredHost {
             super.run();
 
             // save the last set of active JVMs
-            Set lastActiveVms = activeVms;
+            Set<Integer> lastActiveVms = activeVms;
 
             try {
                 // get the current set of active JVMs
@@ -313,20 +315,20 @@ public class MonitoredHostProvider extends MonitoredHost {
                 return;
             }
 
-            Set<Integer> startedVms = new HashSet<Integer>();
-            Set<Object> terminatedVms = new HashSet<Object>();
+            Set<Integer> startedVms = new HashSet<>();
+            Set<Integer> terminatedVms = new HashSet<>();
 
-            for (Iterator i = activeVms.iterator(); i.hasNext(); /* empty */ ) {
-                Integer vmid = (Integer)i.next();
+            for (Iterator<Integer> i = activeVms.iterator(); i.hasNext(); /* empty */ ) {
+                Integer vmid = i.next();
                 if (!lastActiveVms.contains(vmid)) {
                     // a new file has been detected, add to set
                     startedVms.add(vmid);
                 }
             }
 
-            for (Iterator i = lastActiveVms.iterator(); i.hasNext();
+            for (Iterator<Integer> i = lastActiveVms.iterator(); i.hasNext();
                     /* empty */ ) {
-                Object o = i.next();
+                Integer o = i.next();
                 if (!activeVms.contains(o)) {
                     // JVM has terminated, remove it from the active list
                     terminatedVms.add(o);
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/RemoteMonitoredVm.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/RemoteMonitoredVm.java
index 72e48f2cb042de1b886df5435c1c19e45a1ebd3c..2a38e52df66e2eb6d196f00075cee4c77125de9e 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/RemoteMonitoredVm.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/RemoteMonitoredVm.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -198,16 +198,17 @@ public class RemoteMonitoredVm extends AbstractMonitoredVm {
      * @param inserted List of Monitor objects inserted.
      * @param removed List of Monitor objects removed.
      */
-    void fireMonitorStatusChangedEvents(List inserted, List removed) {
-        ArrayList registered = null;
+    @SuppressWarnings("unchecked") // Cast of result of clone
+    void fireMonitorStatusChangedEvents(List<Monitor> inserted, List<Monitor> removed) {
+        ArrayList<VmListener> registered = null;
         MonitorStatusChangeEvent ev = null;
 
         synchronized(listeners) {
             registered = (ArrayList)listeners.clone();
         }
 
-        for (Iterator i = registered.iterator(); i.hasNext(); /* empty */) {
-            VmListener l = (VmListener)i.next();
+        for (Iterator<VmListener> i = registered.iterator(); i.hasNext(); /* empty */) {
+            VmListener l = i.next();
             if (ev == null) {
                 ev = new MonitorStatusChangeEvent(this, inserted, removed);
             }
@@ -218,16 +219,17 @@ public class RemoteMonitoredVm extends AbstractMonitoredVm {
     /**
      * Fire MonitoredVmStructureChanged events.
      */
+    @SuppressWarnings("unchecked") // Cast of result of clone
     void fireMonitorsUpdatedEvents() {
-        ArrayList registered = null;
+        ArrayList<VmListener> registered = null;
         VmEvent ev = null;
 
         synchronized(listeners) {
             registered = (ArrayList)listeners.clone();
         }
 
-        for (Iterator i = registered.iterator(); i.hasNext(); /* empty */) {
-            VmListener l = (VmListener)i.next();
+        for (Iterator<VmListener> i = registered.iterator(); i.hasNext(); /* empty */) {
+            VmListener l = i.next();
             if (ev == null) {
                 ev = new VmEvent(this);
             }
@@ -256,8 +258,8 @@ public class RemoteMonitoredVm extends AbstractMonitoredVm {
             try {
                 MonitorStatus status = getMonitorStatus();
 
-                List inserted = status.getInserted();
-                List removed = status.getRemoved();
+                List<Monitor> inserted = status.getInserted();
+                List<Monitor> removed = status.getRemoved();
 
                 if (!inserted.isEmpty() || !removed.isEmpty()) {
                     fireMonitorStatusChangedEvents(inserted, removed);
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/v1_0/PerfDataBuffer.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/v1_0/PerfDataBuffer.java
index a065258a73f8849ce8fe7da0d9b232bb52b6edd9..a6eafba6954db48b75de47a66448bbd00d9f2ee0 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/v1_0/PerfDataBuffer.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/v1_0/PerfDataBuffer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -47,7 +47,7 @@ public class PerfDataBuffer extends PerfDataBufferImpl {
     private static final boolean DEBUG = false;
     private static final int syncWaitMs =
             Integer.getInteger("sun.jvmstat.perdata.syncWaitMs", 5000);
-    private static final ArrayList EMPTY_LIST = new ArrayList(0);
+    private static final ArrayList<Monitor> EMPTY_LIST = new ArrayList<Monitor>(0);
 
     /*
      * the following constants must be kept in sync with struct
@@ -190,8 +190,8 @@ public class PerfDataBuffer extends PerfDataBufferImpl {
         getNewMonitors(map);
 
         // current implementation doesn't support deletion or reuse of entries
-        ArrayList removed = EMPTY_LIST;
-        ArrayList inserted = insertedMonitors;
+        ArrayList<Monitor> removed = EMPTY_LIST;
+        ArrayList<Monitor> inserted = insertedMonitors;
 
         insertedMonitors = new ArrayList<Monitor>();
         return new MonitorStatus(inserted, removed);
@@ -618,14 +618,14 @@ public class PerfDataBuffer extends PerfDataBufferImpl {
     /**
      * Method to dump debugging information
      */
-    private void dumpAll(Map map, int lvmid) {
+    private void dumpAll(Map<String, Monitor> map, int lvmid) {
         if (DEBUG) {
-            Set keys = map.keySet();
+            Set<String> keys = map.keySet();
 
             System.err.println("Dump for " + lvmid);
             int j = 0;
-            for (Iterator i = keys.iterator(); i.hasNext(); j++) {
-                Monitor monitor = (Monitor)map.get(i.next());
+            for (Iterator<String> i = keys.iterator(); i.hasNext(); j++) {
+                Monitor monitor = map.get(i.next());
                 System.err.println(j + "\t" + monitor.getName()
                                    + "=" + monitor.getValue());
             }
diff --git a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/v2_0/PerfDataBuffer.java b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/v2_0/PerfDataBuffer.java
index 746145095ec955ea8b3fdf6cbc6c4a31e1255cbb..2c2a944e0d7480edb7d7b0cf12bcde9460a0801e 100644
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/v2_0/PerfDataBuffer.java
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/v2_0/PerfDataBuffer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -65,7 +65,7 @@ public class PerfDataBuffer extends PerfDataBufferImpl {
     private static final boolean DEBUG = false;
     private static final int syncWaitMs =
             Integer.getInteger("sun.jvmstat.perdata.syncWaitMs", 5000);
-    private static final ArrayList EMPTY_LIST = new ArrayList(0);
+    private static final ArrayList<Monitor> EMPTY_LIST = new ArrayList<>(0);
 
     /*
      * These are primarily for documentary purposes and the match up
@@ -198,10 +198,10 @@ public class PerfDataBuffer extends PerfDataBufferImpl {
         getNewMonitors(map);
 
         // current implementation doesn't support deletion of reuse of entries
-        ArrayList removed = EMPTY_LIST;
-        ArrayList inserted = insertedMonitors;
+        ArrayList<Monitor> removed = EMPTY_LIST;
+        ArrayList<Monitor> inserted = insertedMonitors;
 
-        insertedMonitors = new ArrayList<Monitor>();
+        insertedMonitors = new ArrayList<>();
         return new MonitorStatus(inserted, removed);
     }
 
@@ -524,7 +524,7 @@ public class PerfDataBuffer extends PerfDataBufferImpl {
 
             System.err.println("Dump for " + lvmid);
             int j = 0;
-            for (Iterator i = keys.iterator(); i.hasNext(); j++) {
+            for (Iterator<String> i = keys.iterator(); i.hasNext(); j++) {
                 Monitor monitor = map.get(i.next());
                 System.err.println(j + "\t" + monitor.getName()
                                    + "=" + monitor.getValue());
diff --git a/jdk/src/share/classes/sun/management/DiagnosticCommandImpl.java b/jdk/src/share/classes/sun/management/DiagnosticCommandImpl.java
index 27f6399337d2f4861306dad51a7d7cd8147aaf8e..27730898f1be24fe969a0f691502b17e40acbcbc 100644
--- a/jdk/src/share/classes/sun/management/DiagnosticCommandImpl.java
+++ b/jdk/src/share/classes/sun/management/DiagnosticCommandImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, 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
@@ -84,10 +84,10 @@ class DiagnosticCommandImpl extends NotificationEmitterSupport
             Exception cause = null;
             if (info.getPermissionClass() != null) {
                 try {
-                    Class c = Class.forName(info.getPermissionClass());
+                    Class<?> c = Class.forName(info.getPermissionClass());
                     if (info.getPermissionAction() == null) {
                         try {
-                            Constructor constructor = c.getConstructor(String.class);
+                            Constructor<?> constructor = c.getConstructor(String.class);
                             permission = (Permission) constructor.newInstance(info.getPermissionName());
 
                         } catch (InstantiationException | IllegalAccessException
@@ -98,7 +98,7 @@ class DiagnosticCommandImpl extends NotificationEmitterSupport
                     }
                     if (permission == null) {
                         try {
-                            Constructor constructor = c.getConstructor(String.class, String.class);
+                            Constructor<?> constructor = c.getConstructor(String.class, String.class);
                             permission = (Permission) constructor.newInstance(
                                     info.getPermissionName(),
                                     info.getPermissionAction());
@@ -158,7 +158,7 @@ class DiagnosticCommandImpl extends NotificationEmitterSupport
         SortedSet<MBeanOperationInfo> operations = new TreeSet<>(new OperationInfoComparator());
         Map<String, Wrapper> wrappersmap;
         if (!isSupported) {
-            wrappersmap = (Map<String, Wrapper>) Collections.EMPTY_MAP;
+            wrappersmap = Collections.emptyMap();
         } else {
             try {
                 String[] command = getDiagnosticCommands();
@@ -189,7 +189,7 @@ class DiagnosticCommandImpl extends NotificationEmitterSupport
                     }
                 }
             } catch (IllegalArgumentException | UnsupportedOperationException e) {
-                wrappersmap = (Map<String, Wrapper>) Collections.EMPTY_MAP;
+                wrappersmap = Collections.emptyMap();
             }
         }
         wrappers =  Collections.unmodifiableMap(wrappersmap);
diff --git a/jdk/src/share/classes/sun/management/GarbageCollectionNotifInfoCompositeData.java b/jdk/src/share/classes/sun/management/GarbageCollectionNotifInfoCompositeData.java
index 2d62ce3b0e6f89432bc67d2c844f12ab35137992..722c0dfc55faa5f1f40c8eb9e2e02571168fce38 100644
--- a/jdk/src/share/classes/sun/management/GarbageCollectionNotifInfoCompositeData.java
+++ b/jdk/src/share/classes/sun/management/GarbageCollectionNotifInfoCompositeData.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, 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
@@ -65,7 +65,7 @@ public class GarbageCollectionNotifInfoCompositeData extends LazyCompositeData {
         final GcInfoBuilder builder = AccessController.doPrivileged (new PrivilegedAction<GcInfoBuilder>() {
                 public GcInfoBuilder run() {
                     try {
-                        Class cl = Class.forName("com.sun.management.GcInfo");
+                        Class<?> cl = Class.forName("com.sun.management.GcInfo");
                         Field f = cl.getDeclaredField("builder");
                         f.setAccessible(true);
                         return (GcInfoBuilder)f.get(gcNotifInfo.getGcInfo());
diff --git a/jdk/src/share/classes/sun/management/GcInfoBuilder.java b/jdk/src/share/classes/sun/management/GcInfoBuilder.java
index 523dcd5eee5fc211549be1c13baf90d44c51ea14..b503df57ad9039e97fb0c957dbebdbd6c27cf84c 100644
--- a/jdk/src/share/classes/sun/management/GcInfoBuilder.java
+++ b/jdk/src/share/classes/sun/management/GcInfoBuilder.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, 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
@@ -98,7 +98,7 @@ public class GcInfoBuilder {
 
         // First, fill with the attributes in the GcInfo
         String[] gcInfoItemNames = GcInfoCompositeData.getBaseGcInfoItemNames();
-        OpenType[] gcInfoItemTypes = GcInfoCompositeData.getBaseGcInfoItemTypes();
+        OpenType<?>[] gcInfoItemTypes = GcInfoCompositeData.getBaseGcInfoItemTypes();
         int numGcInfoItems = gcInfoItemNames.length;
 
         int itemCount = numGcInfoItems + gcExtItemCount;
diff --git a/jdk/src/share/classes/sun/management/GcInfoCompositeData.java b/jdk/src/share/classes/sun/management/GcInfoCompositeData.java
index a7730300e762e9dd52572016c63f86006db5802e..b1cb38e16b1b1f73a9112732ae63e246968d0d42 100644
--- a/jdk/src/share/classes/sun/management/GcInfoCompositeData.java
+++ b/jdk/src/share/classes/sun/management/GcInfoCompositeData.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, 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
@@ -72,7 +72,7 @@ public class GcInfoCompositeData extends LazyCompositeData {
         final GcInfoBuilder builder = AccessController.doPrivileged (new PrivilegedAction<GcInfoBuilder>() {
                         public GcInfoBuilder run() {
                             try {
-                                Class cl = Class.forName("com.sun.management.GcInfo");
+                                Class<?> cl = Class.forName("com.sun.management.GcInfo");
                                 Field f = cl.getDeclaredField("builder");
                                 f.setAccessible(true);
                                 return (GcInfoBuilder)f.get(info);
@@ -84,7 +84,7 @@ public class GcInfoCompositeData extends LazyCompositeData {
         final Object[] extAttr = AccessController.doPrivileged (new PrivilegedAction<Object[]>() {
                         public Object[] run() {
                             try {
-                                Class cl = Class.forName("com.sun.management.GcInfo");
+                                Class<?> cl = Class.forName("com.sun.management.GcInfo");
                                 Field f = cl.getDeclaredField("extAttributes");
                                 f.setAccessible(true);
                                 return (Object[])f.get(info);
@@ -182,8 +182,8 @@ public class GcInfoCompositeData extends LazyCompositeData {
         return baseGcInfoItemNames;
     }
 
-    private static OpenType[] baseGcInfoItemTypes = null;
-    static synchronized OpenType[] getBaseGcInfoItemTypes() {
+    private static OpenType<?>[] baseGcInfoItemTypes = null;
+    static synchronized OpenType<?>[] getBaseGcInfoItemTypes() {
         if (baseGcInfoItemTypes == null) {
             OpenType<?> memoryUsageOpenType = memoryUsageMapType.getOpenType();
             baseGcInfoItemTypes = new OpenType<?>[] {
diff --git a/jdk/src/share/classes/sun/management/MappedMXBeanType.java b/jdk/src/share/classes/sun/management/MappedMXBeanType.java
index ae2055557c54cf46400fa0e695ca4543b69ae037..9bfcbd9c682838f496595edfdec30124b7c67a87 100644
--- a/jdk/src/share/classes/sun/management/MappedMXBeanType.java
+++ b/jdk/src/share/classes/sun/management/MappedMXBeanType.java
@@ -227,6 +227,7 @@ public abstract class MappedMXBeanType {
     //   Enum <-> enum's name
     //
     static class EnumMXBeanType extends MappedMXBeanType {
+        @SuppressWarnings("rawtypes")
         final Class enumClass;
         EnumMXBeanType(Class<?> c) {
             this.enumClass = c;
@@ -754,7 +755,7 @@ public abstract class MappedMXBeanType {
         }
     }
 
-    private static class InProgress extends OpenType {
+    private static class InProgress<T> extends OpenType<T> {
         private static final String description =
                   "Marker to detect recursive type use -- internal use only!";
 
@@ -783,7 +784,7 @@ public abstract class MappedMXBeanType {
     static {
         OpenType<?> t;
         try {
-            t = new InProgress();
+            t = new InProgress<>();
         } catch (OpenDataException e) {
             // Should not reach here
             throw new AssertionError(e);
@@ -791,7 +792,7 @@ public abstract class MappedMXBeanType {
         inProgress = t;
     }
 
-    private static final OpenType[] simpleTypes = {
+    private static final OpenType<?>[] simpleTypes = {
         BIGDECIMAL, BIGINTEGER, BOOLEAN, BYTE, CHARACTER, DATE,
         DOUBLE, FLOAT, INTEGER, LONG, OBJECTNAME, SHORT, STRING,
         VOID,
diff --git a/jdk/src/share/classes/sun/misc/JavaAWTFontAccess.java b/jdk/src/share/classes/sun/misc/JavaAWTFontAccess.java
new file mode 100644
index 0000000000000000000000000000000000000000..079d94fb39b98b8bb8d5e469b0d78561238a61ac
--- /dev/null
+++ b/jdk/src/share/classes/sun/misc/JavaAWTFontAccess.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2014, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+/**
+ * SharedSecrets interface used for the access from java.text.Bidi
+ */
+
+package sun.misc;
+
+public interface JavaAWTFontAccess {
+
+    // java.awt.font.TextAttribute constants
+    public Object getTextAttributeConstant(String name);
+
+    // java.awt.font.NumericShaper
+    public void shape(Object shaper, char[] text, int start, int count);
+}
diff --git a/jdk/src/share/classes/sun/misc/SharedSecrets.java b/jdk/src/share/classes/sun/misc/SharedSecrets.java
index 3e268759bc79578520415f05ca88e18e680c0674..49f06b5d39b649d36c57ac6db0f2fa325ebf2892 100644
--- a/jdk/src/share/classes/sun/misc/SharedSecrets.java
+++ b/jdk/src/share/classes/sun/misc/SharedSecrets.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, 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
@@ -55,6 +55,7 @@ public class SharedSecrets {
     private static JavaSecurityAccess javaSecurityAccess;
     private static JavaUtilZipFileAccess javaUtilZipFileAccess;
     private static JavaAWTAccess javaAWTAccess;
+    private static JavaAWTFontAccess javaAWTFontAccess;
     private static JavaBeansIntrospectorAccess javaBeansIntrospectorAccess;
 
     public static JavaUtilJarAccess javaUtilJarAccess() {
@@ -180,12 +181,19 @@ public class SharedSecrets {
     public static JavaAWTAccess getJavaAWTAccess() {
         // this may return null in which case calling code needs to
         // provision for.
-        if (javaAWTAccess == null) {
-            return null;
-        }
         return javaAWTAccess;
     }
 
+    public static void setJavaAWTFontAccess(JavaAWTFontAccess jafa) {
+        javaAWTFontAccess = jafa;
+    }
+
+    public static JavaAWTFontAccess getJavaAWTFontAccess() {
+        // this may return null in which case calling code needs to
+        // provision for.
+        return javaAWTFontAccess;
+    }
+
     public static JavaBeansIntrospectorAccess getJavaBeansIntrospectorAccess() {
         return javaBeansIntrospectorAccess;
     }
diff --git a/jdk/src/share/classes/sun/security/jca/ProviderConfig.java b/jdk/src/share/classes/sun/security/jca/ProviderConfig.java
index d6c243b183415d2ec81102fc91568d72ff105fb1..edbc899f0766b1bc44bb6fe852eac4f364226dfd 100644
--- a/jdk/src/share/classes/sun/security/jca/ProviderConfig.java
+++ b/jdk/src/share/classes/sun/security/jca/ProviderConfig.java
@@ -255,6 +255,14 @@ final class ProviderConfig {
                         disableLoad();
                     }
                     return null;
+                } catch (ExceptionInInitializerError err) {
+                    // no sufficient permission to initialize provider class
+                    if (debug != null) {
+                        debug.println("Error loading provider " + ProviderConfig.this);
+                        err.printStackTrace();
+                    }
+                    disableLoad();
+                    return null;
                 }
             }
         });
diff --git a/jdk/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java b/jdk/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java
index 35564498c0e1dd5f7dc42b82beaa36b2f936d1d6..9861bc86bdf8f079cc8167030a0e2df5f5ad2814 100644
--- a/jdk/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java
+++ b/jdk/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, 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
@@ -900,7 +900,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi {
     private static ObjectIdentifier mapPBEAlgorithmToOID(String algorithm)
         throws NoSuchAlgorithmException {
         // Check for PBES2 algorithms
-        if (algorithm.toLowerCase().startsWith("pbewithhmacsha")) {
+        if (algorithm.toLowerCase(Locale.ENGLISH).startsWith("pbewithhmacsha")) {
             return pbes2_OID;
         }
         return AlgorithmId.get(algorithm).getOID();
diff --git a/jdk/src/share/classes/sun/security/provider/ConfigFile.java b/jdk/src/share/classes/sun/security/provider/ConfigFile.java
index f3c041ac0b3a246fdcf8d59db76b3fb26e7f8e60..6e243c4a612c21a781aabc5ad80ac15b7e31fe3d 100644
--- a/jdk/src/share/classes/sun/security/provider/ConfigFile.java
+++ b/jdk/src/share/classes/sun/security/provider/ConfigFile.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, 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
@@ -451,7 +451,7 @@ public final class ConfigFile extends Configuration {
 
                 // controlFlag (required, optional, etc)
                 LoginModuleControlFlag controlFlag;
-                String sflag = match("controlFlag").toUpperCase();
+                String sflag = match("controlFlag").toUpperCase(Locale.ENGLISH);
                 switch (sflag) {
                     case "REQUIRED":
                         controlFlag = LoginModuleControlFlag.REQUIRED;
diff --git a/jdk/src/share/classes/sun/security/provider/PolicyParser.java b/jdk/src/share/classes/sun/security/provider/PolicyParser.java
index b13345f7c559fb166dff1180d32573314a6aba45..8d037b4bb4a364d52fd504408832ac40f75dc706 100644
--- a/jdk/src/share/classes/sun/security/provider/PolicyParser.java
+++ b/jdk/src/share/classes/sun/security/provider/PolicyParser.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -707,7 +707,7 @@ public class PolicyParser {
             } catch (PropertyExpander.ExpandException peee) {
                 throw new IOException(peee.getLocalizedMessage());
             }
-            properties.put(key.toLowerCase(), value);
+            properties.put(key.toLowerCase(Locale.ENGLISH), value);
         }
 
         return properties;
diff --git a/jdk/src/share/classes/sun/security/tools/keytool/Main.java b/jdk/src/share/classes/sun/security/tools/keytool/Main.java
index 2947a3081a1b6d21aa13b2f4bb269002a177b082..1b52d51385a5a24205b7456d943748820e2f1ab5 100644
--- a/jdk/src/share/classes/sun/security/tools/keytool/Main.java
+++ b/jdk/src/share/classes/sun/security/tools/keytool/Main.java
@@ -1540,7 +1540,7 @@ public final class Main {
         boolean useDefaultPBEAlgorithm = true;
         SecretKey secKey = null;
 
-        if (keyAlgName.toUpperCase().startsWith("PBE")) {
+        if (keyAlgName.toUpperCase(Locale.ENGLISH).startsWith("PBE")) {
             SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");
 
             // User is prompted for PBE credential
diff --git a/jdk/src/share/classes/sun/text/bidi/BidiBase.java b/jdk/src/share/classes/sun/text/bidi/BidiBase.java
index f13155d06d5bd57099fd14f4cf1b044d75df9112..bbf1b4b6a214d98761b134c6f98d3f344d38e94b 100644
--- a/jdk/src/share/classes/sun/text/bidi/BidiBase.java
+++ b/jdk/src/share/classes/sun/text/bidi/BidiBase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, 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
@@ -54,13 +54,12 @@ package sun.text.bidi;
 
 import java.io.IOException;
 import java.lang.reflect.Array;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
 import java.text.AttributedCharacterIterator;
 import java.text.Bidi;
 import java.util.Arrays;
 import java.util.MissingResourceException;
+import sun.misc.JavaAWTFontAccess;
+import sun.misc.SharedSecrets;
 import sun.text.normalizer.UBiDiProps;
 import sun.text.normalizer.UCharacter;
 import sun.text.normalizer.UTF16;
@@ -3446,7 +3445,13 @@ public class BidiBase {
      * java.awt.font.TextAttribute without creating a static dependency.
      */
     private static class TextAttributeConstants {
-        private static final Class<?> clazz = getClass("java.awt.font.TextAttribute");
+        // Make sure to load the AWT's TextAttribute class before using the constants, if any.
+        static {
+            try {
+                Class.forName("java.awt.font.TextAttribute", true, null);
+            } catch (ClassNotFoundException e) {}
+        }
+        static final JavaAWTFontAccess jafa = SharedSecrets.getJavaAWTFontAccess();
 
         /**
          * TextAttribute instances (or a fake Attribute type if
@@ -3462,88 +3467,41 @@ public class BidiBase {
         /**
          * TextAttribute.RUN_DIRECTION_LTR
          */
-        static final Boolean RUN_DIRECTION_LTR = (clazz == null) ?
-            Boolean.FALSE : (Boolean)getStaticField(clazz, "RUN_DIRECTION_LTR");
-
-
-        private static Class<?> getClass(String name) {
-            try {
-                return Class.forName(name, true, null);
-            } catch (ClassNotFoundException e) {
-                return null;
-            }
-        }
-
-        private static Object getStaticField(Class<?> clazz, String name) {
-            try {
-                Field f = clazz.getField(name);
-                return f.get(null);
-            } catch (NoSuchFieldException | IllegalAccessException x) {
-                throw new AssertionError(x);
-            }
-        }
+        static final Boolean RUN_DIRECTION_LTR = (jafa == null) ?
+            Boolean.FALSE : (Boolean)jafa.getTextAttributeConstant("RUN_DIRECTION_LTR");
 
         @SuppressWarnings("serial")
         private static AttributedCharacterIterator.Attribute
             getTextAttribute(String name)
         {
-            if (clazz == null) {
+            if (jafa == null) {
                 // fake attribute
                 return new AttributedCharacterIterator.Attribute(name) { };
             } else {
-                return (AttributedCharacterIterator.Attribute)getStaticField(clazz, name);
+                return (AttributedCharacterIterator.Attribute)jafa.getTextAttributeConstant(name);
             }
         }
     }
 
     /**
-     * A class that provides access to java.awt.font.NumericShaping without
+     * A class that provides access to java.awt.font.NumericShaper without
      * creating a static dependency.
      */
     private static class NumericShapings {
-        private static final Class<?> clazz =
-            getClass("java.awt.font.NumericShaper");
-        private static final Method shapeMethod =
-            getMethod(clazz, "shape", char[].class, int.class, int.class);
-
-        private static Class<?> getClass(String name) {
+        // Make sure to load the AWT's NumericShaper class before calling shape, if any.
+        static {
             try {
-                return Class.forName(name, true, null);
-            } catch (ClassNotFoundException e) {
-                return null;
-            }
-        }
-
-        private static Method getMethod(Class<?> clazz,
-                                        String name,
-                                        Class<?>... paramTypes)
-        {
-            if (clazz != null) {
-                try {
-                    return clazz.getMethod(name, paramTypes);
-                } catch (NoSuchMethodException e) {
-                    throw new AssertionError(e);
-                }
-            } else {
-                return null;
-            }
+                Class.forName("java.awt.font.NumericShaper", true, null);
+            } catch (ClassNotFoundException e) {}
         }
+        static final JavaAWTFontAccess jafa = SharedSecrets.getJavaAWTFontAccess();
 
         /**
          * Invokes NumericShaping shape(text,start,count) method.
          */
         static void shape(Object shaper, char[] text, int start, int count) {
-            if (shapeMethod == null)
-                throw new AssertionError("Should not get here");
-            try {
-                shapeMethod.invoke(shaper, text, start, count);
-            } catch (InvocationTargetException e) {
-                Throwable cause = e.getCause();
-                if (cause instanceof RuntimeException)
-                    throw (RuntimeException)cause;
-                throw new AssertionError(e);
-            } catch (IllegalAccessException iae) {
-                throw new AssertionError(iae);
+            if (jafa != null) {
+                jafa.shape(shaper, text, start, count);
             }
         }
     }
diff --git a/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java b/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java
index 915bb2eaa20d26712fbf894f5ca42a62a8da0627..5594e4c08befec67cc4686d3b15de9e53ea2ca6e 100644
--- a/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java
+++ b/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, 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
@@ -154,7 +154,7 @@ public abstract class ProviderSkeleton implements InvocationHandler, Provider {
      * @return always null, if the method is a user-defined probe
      */
     public Object invoke(Object proxy, Method method, Object[] args) {
-        Class declaringClass = method.getDeclaringClass();
+        Class<?> declaringClass = method.getDeclaringClass();
         // not a provider subtype's own method
         if (declaringClass != providerType) {
             try {
diff --git a/jdk/src/share/classes/sun/tracing/dtrace/DTraceProvider.java b/jdk/src/share/classes/sun/tracing/dtrace/DTraceProvider.java
index 12ad7a53dec4c6483337d82955bd13e753f37b17..d03625d45b790a4c9371767460b7a8fff6162672 100644
--- a/jdk/src/share/classes/sun/tracing/dtrace/DTraceProvider.java
+++ b/jdk/src/share/classes/sun/tracing/dtrace/DTraceProvider.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, 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
@@ -50,7 +50,7 @@ class DTraceProvider extends ProviderSkeleton {
     private Object proxy;
 
     // For proxy generation
-    private final static Class[] constructorParams = { InvocationHandler.class };
+    private final static Class<?>[] constructorParams = { InvocationHandler.class };
     private final String proxyClassNamePrefix = "$DTraceTracingProxy";
 
     static final String DEFAULT_MODULE = "java_tracing";
@@ -135,7 +135,7 @@ class DTraceProvider extends ProviderSkeleton {
          * Invoke its constructor with the designated invocation handler.
          */
         try {
-            Constructor cons = proxyClass.getConstructor(constructorParams);
+            Constructor<?> cons = proxyClass.getConstructor(constructorParams);
             return (T)cons.newInstance(new Object[] { this });
         } catch (ReflectiveOperationException e) {
             throw new InternalError(e.toString(), e);
diff --git a/jdk/src/share/javavm/export/jvm.h b/jdk/src/share/javavm/export/jvm.h
index 2bef0812054f6a71e90f00e1273a1684750deb51..396ca68558e20b3023db6c55809fa23cbe0db769 100644
--- a/jdk/src/share/javavm/export/jvm.h
+++ b/jdk/src/share/javavm/export/jvm.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, 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
@@ -426,9 +426,6 @@ JVM_GetClassName(JNIEnv *env, jclass cls);
 JNIEXPORT jobjectArray JNICALL
 JVM_GetClassInterfaces(JNIEnv *env, jclass cls);
 
-JNIEXPORT jobject JNICALL
-JVM_GetClassLoader(JNIEnv *env, jclass cls);
-
 JNIEXPORT jboolean JNICALL
 JVM_IsInterface(JNIEnv *env, jclass cls);
 
diff --git a/jdk/src/share/lib/security/blacklisted.certs b/jdk/src/share/lib/security/blacklisted.certs
deleted file mode 100644
index cb1e4d59e3862339dfd1ab6ae38b33aade2bcbc6..0000000000000000000000000000000000000000
--- a/jdk/src/share/lib/security/blacklisted.certs
+++ /dev/null
@@ -1,19 +0,0 @@
-Algorithm=SHA-256
-76A45A496031E4DD2D7ED23E8F6FF97DBDEA980BAAC8B0BA94D7EDB551348645
-4CBBF8256BC9888A8007B2F386940A2E394378B0D903CBB3863C5A6394B889CE
-D24566BF315F4E597D6E381C87119FB4198F5E9E2607F5F4AB362EF7E2E7672F
-14E6D2764A4B06701C6CBC376A253775F79C782FBCB6C0EE6F99DE4BA1024ADD
-D3A936E1A7775A45217C8296A1F22AC5631DCDEC45594099E78EEEBBEDCBA967
-5E83124D68D24E8E177E306DF643D5EA99C5A94D6FC34B072F7544A1CABB7C7B
-9ED8F9B0E8E42A1656B8E1DD18F42BA42DC06FE52686173BA2FC70E756F207DC
-FDEDB5BDFCB67411513A61AEE5CB5B5D7C52AF06028EFC996CC1B05B1D6CEA2B
-A686FEE577C88AB664D0787ECDFFF035F4806F3DE418DC9E4D516324FFF02083
-4FEE0163686ECBD65DB968E7494F55D84B25486D438E9DE558D629D28CD4D176
-8A1BD21661C60015065212CC98B1ABB50DFD14C872A208E66BAE890F25C448AF
-B8686723E415534BC0DBD16326F9486F85B0B0799BF6639334E61DAAE67F36CD
-3946901F46B0071E90D78279E82FABABCA177231A704BE72C5B0E8918566EA66
-31C8FD37DB9B56E708B03D1F01848B068C6DA66F36FB5D82C008C6040FA3E133
-450F1B421BB05C8609854884559C323319619E8B06B001EA2DCBB74A23AA3BE2
-FC02FD48DB92D4DCE6F11679D38354CF750CFC7F584A520EB90BDE80E241F2BD
-DF21016B00FC54F9FE3BC8B039911BB216E9162FAD2FD14D990AB96E951B49BE
-F5B6F88F75D391A4B1EB336F9E201239FB6B1377DB8CFA7B84736216E5AFFFD7
diff --git a/jdk/src/share/lib/security/java.policy b/jdk/src/share/lib/security/java.policy
index b3165881ac4bf8b051302f6505f49072e87d0ffd..4ff0425959a02585a1a30f060a8b0f1046e61749 100644
--- a/jdk/src/share/lib/security/java.policy
+++ b/jdk/src/share/lib/security/java.policy
@@ -26,15 +26,36 @@ grant codeBase "file:${java.home}/lib/ext/nashorn.jar" {
 };
 
 grant codeBase "file:${java.home}/lib/ext/sunec.jar" {
-        permission java.security.AllPermission;
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunec";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunEC";
+        permission java.security.SecurityPermission "clearProviderProperties.SunEC";
+        permission java.security.SecurityPermission "removeProviderProperty.SunEC";
 };
 
 grant codeBase "file:${java.home}/lib/ext/sunjce_provider.jar" {
-        permission java.security.AllPermission;
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+        permission java.security.SecurityPermission "clearProviderProperties.SunJCE";
+        permission java.security.SecurityPermission "removeProviderProperty.SunJCE";
 };
 
 grant codeBase "file:${java.home}/lib/ext/sunpkcs11.jar" {
-        permission java.security.AllPermission;
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2pkcs11";
+        // needs "security.pkcs11.allowSingleThreadedModules"
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.*";
+        permission java.security.SecurityPermission "clearProviderProperties.*";
+        permission java.security.SecurityPermission "removeProviderProperty.*";
+        permission java.security.SecurityPermission "getProperty.auth.login.defaultCallbackHandler";
+        permission java.security.SecurityPermission "authProvider.*";
+        // Needed for reading PKCS11 config file and NSS library check
+        permission java.io.FilePermission "<<ALL FILES>>", "read";
 };
 
 // default permissions granted to all domains
diff --git a/jdk/src/share/lib/security/java.security-aix b/jdk/src/share/lib/security/java.security-aix
index 2734cb43a90a41eecad953beafc1212ea05aecf2..77540a3e506bc6609409bc9c34e9d572b5efa42a 100644
--- a/jdk/src/share/lib/security/java.security-aix
+++ b/jdk/src/share/lib/security/java.security-aix
@@ -206,7 +206,6 @@ package.access=sun.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
-               oracle.jrockit.jfr.,\
                org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
@@ -253,7 +252,6 @@ package.definition=sun.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
-                   oracle.jrockit.jfr.,\
                    org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
diff --git a/jdk/src/share/lib/security/java.security-linux b/jdk/src/share/lib/security/java.security-linux
index 2734cb43a90a41eecad953beafc1212ea05aecf2..77540a3e506bc6609409bc9c34e9d572b5efa42a 100644
--- a/jdk/src/share/lib/security/java.security-linux
+++ b/jdk/src/share/lib/security/java.security-linux
@@ -206,7 +206,6 @@ package.access=sun.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
-               oracle.jrockit.jfr.,\
                org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
@@ -253,7 +252,6 @@ package.definition=sun.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
-                   oracle.jrockit.jfr.,\
                    org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
diff --git a/jdk/src/share/lib/security/java.security-macosx b/jdk/src/share/lib/security/java.security-macosx
index 5c3122d64202f8e5beb0d78b7ee28b3a5b182d0f..fad693da976bbbe2a0db292127455ba9f98991b9 100644
--- a/jdk/src/share/lib/security/java.security-macosx
+++ b/jdk/src/share/lib/security/java.security-macosx
@@ -207,7 +207,6 @@ package.access=sun.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
-               oracle.jrockit.jfr.,\
                org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
@@ -254,7 +253,6 @@ package.definition=sun.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
-                   oracle.jrockit.jfr.,\
                    org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
diff --git a/jdk/src/share/lib/security/java.security-solaris b/jdk/src/share/lib/security/java.security-solaris
index 1d3fb6ae428d6d34fd7c0c9e8e7ef4d6495b08e4..c6015fb07bfb1f648ef7574da227c959b62ec8e4 100644
--- a/jdk/src/share/lib/security/java.security-solaris
+++ b/jdk/src/share/lib/security/java.security-solaris
@@ -208,7 +208,6 @@ package.access=sun.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
-               oracle.jrockit.jfr.,\
                org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
@@ -254,7 +253,6 @@ package.definition=sun.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
-                   oracle.jrockit.jfr.,\
                    org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
diff --git a/jdk/src/share/lib/security/java.security-windows b/jdk/src/share/lib/security/java.security-windows
index 2566f113cc987aaafd4df181297a6c6cc953a6fd..466a4849bad300bd5d4aa651b30b164776944703 100644
--- a/jdk/src/share/lib/security/java.security-windows
+++ b/jdk/src/share/lib/security/java.security-windows
@@ -207,7 +207,6 @@ package.access=sun.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
-               oracle.jrockit.jfr.,\
                org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
@@ -254,7 +253,6 @@ package.definition=sun.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
-                   oracle.jrockit.jfr.,\
                    org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
diff --git a/jdk/src/share/native/common/check_code.c b/jdk/src/share/native/common/check_code.c
index 92d96b19675c1a852e27b672811876d2b2b0d44f..4ffbd67eaf246a6c68ec4a68365c9a7d82f5cb06 100644
--- a/jdk/src/share/native/common/check_code.c
+++ b/jdk/src/share/native/common/check_code.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2014, 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
@@ -1357,16 +1357,9 @@ verify_opcode_operands(context_type *context, unsigned int inumber, int offset)
                 }
                 (*env)->DeleteLocalRef(env, super);
 
-                /* The optimizer make cause this to happen on local code */
+                /* The optimizer may cause this to happen on local code */
                 if (not_found) {
-#ifdef BROKEN_JAVAC
-                    jobject loader = JVM_GetClassLoader(env, context->class);
-                    int has_loader = (loader != 0);
-                    (*env)->DeleteLocalRef(env, loader);
-                    if (has_loader)
-#endif /* BROKEN_JAVAC */
-                        CCerror(context,
-                                "Illegal use of nonvirtual function call");
+                    CCerror(context, "Illegal use of nonvirtual function call");
                 }
             }
         }
diff --git a/jdk/src/share/native/java/lang/Class.c b/jdk/src/share/native/java/lang/Class.c
index b0ba34349d8d19ebcaffc1d77cfabd5e57c01124..c5e717fe0df57c6736376189aa5c8d980ae16ba3 100644
--- a/jdk/src/share/native/java/lang/Class.c
+++ b/jdk/src/share/native/java/lang/Class.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2014, 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
@@ -45,7 +45,6 @@ extern jboolean VerifyFixClassname(char *utf_name);
 #define CLS "Ljava/lang/Class;"
 #define CPL "Lsun/reflect/ConstantPool;"
 #define STR "Ljava/lang/String;"
-#define JCL "Ljava/lang/ClassLoader;"
 #define FLD "Ljava/lang/reflect/Field;"
 #define MHD "Ljava/lang/reflect/Method;"
 #define CTR "Ljava/lang/reflect/Constructor;"
@@ -56,7 +55,6 @@ static JNINativeMethod methods[] = {
     {"getName0",         "()" STR,          (void *)&JVM_GetClassName},
     {"getSuperclass",    "()" CLS,          NULL},
     {"getInterfaces0",   "()[" CLS,         (void *)&JVM_GetClassInterfaces},
-    {"getClassLoader0",  "()" JCL,          (void *)&JVM_GetClassLoader},
     {"isInterface",      "()Z",             (void *)&JVM_IsInterface},
     {"getSigners",       "()[" OBJ,         (void *)&JVM_GetClassSigners},
     {"setSigners",       "([" OBJ ")V",     (void *)&JVM_SetClassSigners},
@@ -81,7 +79,6 @@ static JNINativeMethod methods[] = {
 #undef OBJ
 #undef CLS
 #undef STR
-#undef JCL
 #undef FLD
 #undef MHD
 #undef CTR
diff --git a/jdk/src/share/native/java/lang/java_props.h b/jdk/src/share/native/java/lang/java_props.h
index 21207d9fb920ec88a7ac75353da125b31203cd87..98caf63fccafd5db943b0a860b5b8ab7a35d70df 100644
--- a/jdk/src/share/native/java/lang/java_props.h
+++ b/jdk/src/share/native/java/lang/java_props.h
@@ -117,7 +117,7 @@ typedef struct {
 
     char *exceptionList;
 
-    char *awt_headless  /* java.awt.headless setting, if NULL (default) will not be set */
+    char *awt_headless;  /* java.awt.headless setting, if NULL (default) will not be set */
 #endif
 
 } java_props_t;
diff --git a/jdk/src/solaris/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java b/jdk/src/solaris/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java
index 3554d31c558412a3a5fca8172b3543e124416b86..6211811e512cb2ee167887f694048b055e535eb8 100644
--- a/jdk/src/solaris/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java
+++ b/jdk/src/solaris/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java
@@ -77,8 +77,7 @@ public class NTLMAuthentication extends AuthenticationInfo {
 
     static {
         defaultDomain = java.security.AccessController.doPrivileged(
-            new sun.security.action.GetPropertyAction("http.auth.ntlm.domain",
-                                                      "domain"));
+            new sun.security.action.GetPropertyAction("http.auth.ntlm.domain", ""));
     };
 
     public static boolean supportsTransparentAuth () {
@@ -100,17 +99,13 @@ public class NTLMAuthentication extends AuthenticationInfo {
             public String run() {
                 String localhost;
                 try {
-                    localhost = InetAddress.getLocalHost().getHostName().toUpperCase();
+                    localhost = InetAddress.getLocalHost().getHostName();
                 } catch (UnknownHostException e) {
                      localhost = "localhost";
                 }
                 return localhost;
             }
         });
-        int x = hostname.indexOf ('.');
-        if (x != -1) {
-            hostname = hostname.substring (0, x);
-        }
     };
 
     PasswordAuthentication pw;
diff --git a/jdk/src/solaris/native/java/lang/locale_str.h b/jdk/src/solaris/native/java/lang/locale_str.h
index d63e26ce37da84a20f7d4cc826c74219446c754e..72a796c7a9f0a0562876a1e19268862f5b551735 100644
--- a/jdk/src/solaris/native/java/lang/locale_str.h
+++ b/jdk/src/solaris/native/java/lang/locale_str.h
@@ -135,7 +135,7 @@
     "sr_SP", "sr_YU",
     "tchinese", "zh_TW",
 #endif
-    ""
+    "", "",
  };
 
 /*
@@ -188,7 +188,7 @@ static char *language_names[] = {
     "japanese", "ja",
     "korean", "ko",
 #endif
-    "",
+    "", "",
 };
 
 /*
@@ -201,7 +201,7 @@ static char *script_names[] = {
     "iqtelif", "Latn",
     "latin", "Latn",
 #endif
-    "",
+    "", "",
 };
 
 /*
@@ -212,7 +212,7 @@ static char *country_names[] = {
     "RN", "US", // used on Linux, not clear what it stands for
 #endif
     "YU", "CS", // YU has been removed from ISO 3166
-    "",
+    "", "",
 };
 
 /*
@@ -220,5 +220,5 @@ static char *country_names[] = {
  */
 static char *variant_names[] = {
     "nynorsk", "NY",
-    "",
+    "", "",
 };
diff --git a/jdk/src/windows/lib/security/java.policy b/jdk/src/windows/lib/security/java.policy
index 05368dee3cf50a596a9d976cc650fcf0b809d091..590e5df3081734dda298eedea693ac92f41c5477 100644
--- a/jdk/src/windows/lib/security/java.policy
+++ b/jdk/src/windows/lib/security/java.policy
@@ -1,3 +1,8 @@
 grant codeBase "file:${java.home}/lib/ext/sunmscapi.jar" {
-        permission java.security.AllPermission;
+        Permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunmscapi";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunMSCAPI";
+        permission java.security.SecurityPermission "clearProviderProperties.SunMSCAPI";
+        permission java.security.SecurityPermission "removeProviderProperty.SunMSCAPI";
 };
diff --git a/jdk/src/windows/native/java/net/net_util_md.c b/jdk/src/windows/native/java/net/net_util_md.c
index f9a61bf5787e35fb8d04a0ea7f23d075ea2f299f..ae71733d8ad83ac891b06f5f69ff3a85b7172f95 100644
--- a/jdk/src/windows/native/java/net/net_util_md.c
+++ b/jdk/src/windows/native/java/net/net_util_md.c
@@ -443,6 +443,13 @@ NET_GetSockOpt(int s, int level, int optname, void *optval,
 {
     int rv;
 
+    if (level == IPPROTO_IPV6 && optname == IPV6_TCLASS) {
+        int *intopt = (int *)optval;
+        *intopt = 0;
+        *optlen = sizeof(*intopt);
+        return 0;
+    }
+
     rv = getsockopt(s, level, optname, optval, optlen);
 
 
diff --git a/jdk/src/windows/native/sun/nio/ch/Net.c b/jdk/src/windows/native/sun/nio/ch/Net.c
index fc96ea206aeda1d8344c6b35834840c7dd3fe59a..fb0faa87b84fa90a34826eb0aa01cc9b182e6c63 100644
--- a/jdk/src/windows/native/sun/nio/ch/Net.c
+++ b/jdk/src/windows/native/sun/nio/ch/Net.c
@@ -295,9 +295,9 @@ Java_sun_nio_ch_Net_getIntOption0(JNIEnv *env, jclass clazz, jobject fdo,
     /**
      * HACK: IP_TOS is deprecated on Windows and querying the option
      * returns a protocol error. NET_GetSockOpt handles this and uses
-     * a fallback mechanism.
+     * a fallback mechanism. Same applies to IPV6_TCLASS
      */
-    if (level == IPPROTO_IP && opt == IP_TOS) {
+    if ((level == IPPROTO_IP && opt == IP_TOS) || (level == IPPROTO_IPV6 && opt == IPV6_TCLASS)) {
         mayNeedConversion = JNI_TRUE;
     }
 
@@ -340,6 +340,11 @@ Java_sun_nio_ch_Net_setIntOption0(JNIEnv *env, jclass clazz, jobject fdo,
         arglen = sizeof(arg);
     }
 
+    if (level == IPPROTO_IPV6 && opt == IPV6_TCLASS) {
+        /* No op */
+        return;
+    }
+
     if (mayNeedConversion) {
         n = NET_SetSockOpt(fdval(env, fdo), level, opt, parg, arglen);
     } else {
diff --git a/jdk/test/TEST.groups b/jdk/test/TEST.groups
index 9efa1bd05c3efbb85602fcaa1c69a3d1bd8d00de..3cd7450172ec961a41a3efb10cbc95e307cb4512 100644
--- a/jdk/test/TEST.groups
+++ b/jdk/test/TEST.groups
@@ -362,7 +362,8 @@ needs_jdk = \
   sun/reflect/CallerSensitive/CallerSensitiveFinder.java \
   sun/reflect/CallerSensitive/MissingCallerSensitive.java \
   sun/security/util/Resources/NewNamesFormat.java \
-  vm/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java
+  vm/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java \
+  javax/xml/ws/clientjar/TestWsImport.java 
 
 # JRE adds further tests to compact3
 #
@@ -388,6 +389,7 @@ needs_jre = \
   java/security/Security/ClassLoaderDeadlock/Deadlock.sh \
   java/util/jar/Manifest/CreateManifest.java \
   java/util/logging/TestMainAppContext.java \
+  java/util/logging/TestLoggingWithMainAppContext.java \
   java/util/ResourceBundle/Control/Bug6530694.java \
   java/text/Bidi/BidiConformance.java \
   java/text/Bidi/BidiEmbeddingTest.java \
diff --git a/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBESealedObject.java b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBESealedObject.java
new file mode 100644
index 0000000000000000000000000000000000000000..2420b9bc4a3ad6ca53cdef8d859503187ece220b
--- /dev/null
+++ b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBESealedObject.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 2012, 2014, 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.
+ */
+
+import java.io.PrintStream;
+import java.security.AlgorithmParameters;
+import java.security.InvalidKeyException;
+import java.security.Provider;
+import java.security.Security;
+import java.security.spec.AlgorithmParameterSpec;
+import java.util.Arrays;
+import java.util.Random;
+import java.util.StringTokenizer;
+import javax.crypto.Cipher;
+import javax.crypto.SealedObject;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.PBEParameterSpec;
+
+/**
+ * @test
+ * @bug 8041781
+ * @summary test if seal/unseal works correctly with PBE algorithms
+ * @author Yun Ke
+ * @author Bill Situ
+ * @author Alexander Fomin
+ * @run main PBESealedObject
+ */
+public class PBESealedObject {
+
+    private static final String[] PBEAlgorithms = {
+        "pbeWithMD5ANDdes",
+        "PBEWithMD5AndDES/CBC/PKCS5Padding",
+        "PBEWithMD5AndTripleDES",
+        "PBEWithMD5AndTripleDES/CBC/PKCS5Padding",
+        "PBEwithSHA1AndDESede",
+        "PBEwithSHA1AndDESede/CBC/PKCS5Padding",
+        "PBEwithSHA1AndRC2_40",
+        "PBEwithSHA1Andrc2_40/CBC/PKCS5Padding",
+        "PBEWithSHA1AndRC2_128",
+        "PBEWithSHA1andRC2_128/CBC/PKCS5Padding",
+        "PBEWithSHA1AndRC4_40",
+        "PBEWithsha1AndRC4_40/ECB/NoPadding",
+        "PBEWithSHA1AndRC4_128",
+        "pbeWithSHA1AndRC4_128/ECB/NoPadding",
+        "PBEWithHmacSHA1AndAES_128",
+        "PBEWithHmacSHA224AndAES_128",
+        "PBEWithHmacSHA256AndAES_128",
+        "PBEWithHmacSHA384AndAES_128",
+        "PBEWithHmacSHA512AndAES_128",
+        "PBEWithHmacSHA1AndAES_256",
+        "PBEWithHmacSHA224AndAES_256",
+        "PBEWithHmacSHA256AndAES_256",
+        "PBEWithHmacSHA384AndAES_256",
+        "PBEWithHmacSHA512AndAES_256"
+    };
+
+    public static void main(String[] args) {
+        PBESealedObject test = new PBESealedObject();
+        Provider sunjce = Security.getProvider("SunJCE");
+
+        if (!test.runAll(sunjce, System.out)) {
+            throw new RuntimeException("One or more tests have failed....");
+        }
+    }
+
+    public boolean runAll(Provider p, PrintStream out) {
+        boolean finalResult = true;
+
+        for (String algorithm : PBEAlgorithms) {
+            out.println("Running test with " + algorithm + ":");
+            try {
+                if (!runTest(p, algorithm, out)) {
+                    finalResult = false;
+                    out.println("STATUS: Failed");
+                } else {
+                    out.println("STATUS: Passed");
+                }
+            } catch (Exception ex) {
+                finalResult = false;
+                ex.printStackTrace(out);
+                out.println("STATUS:Failed");
+            }
+        }
+
+        return finalResult;
+    }
+
+    // Have a generic throws Exception as it can throw many different exceptions
+    public boolean runTest(Provider p, String algo, PrintStream out)
+            throws Exception {
+
+        byte[] salt = new byte[8];
+        int ITERATION_COUNT = 1000;
+        AlgorithmParameters pbeParams = null;
+
+        String baseAlgo
+                = new StringTokenizer(algo, "/").nextToken().toUpperCase();
+        boolean isAES = baseAlgo.contains("AES");
+
+        try {
+            // Initialization
+            Cipher ci = Cipher.getInstance(algo, p);
+            new Random().nextBytes(salt);
+            AlgorithmParameterSpec aps = new PBEParameterSpec(salt,
+                    ITERATION_COUNT);
+            SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
+            SecretKey key = skf.generateSecret(
+                    new PBEKeySpec("Secret Lover".toCharArray()));
+
+            // Seal
+            if (isAES) {
+                ci.init(Cipher.ENCRYPT_MODE, key);
+                pbeParams = ci.getParameters();
+            } else {
+                ci.init(Cipher.ENCRYPT_MODE, key, aps);
+            }
+
+            SealedObject so = new SealedObject(key, ci);
+
+            // Unseal and compare
+            if (isAES) {
+                ci.init(Cipher.DECRYPT_MODE, key, pbeParams);
+            } else {
+                ci.init(Cipher.DECRYPT_MODE, key, aps);
+            }
+
+            SecretKey unsealedKey;
+
+            unsealedKey = (SecretKey) so.getObject(ci);
+            if (!Arrays.equals(unsealedKey.getEncoded(), key.getEncoded())) {
+                return false;
+            }
+
+            unsealedKey = (SecretKey) so.getObject(key);
+            if (!Arrays.equals(unsealedKey.getEncoded(), key.getEncoded())) {
+                return false;
+            }
+
+            unsealedKey = (SecretKey) so.getObject(key, "SunJCE");
+            return Arrays.equals(unsealedKey.getEncoded(), key.getEncoded());
+        } catch (InvalidKeyException ex) {
+            if (baseAlgo.endsWith("TRIPLEDES") || baseAlgo.endsWith("AES_256")) {
+                out.println(
+                        "Expected exception , keyStrength > 128 within" + algo);
+                return true;
+            }
+
+            throw ex;
+        }
+    }
+
+}
diff --git a/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBKDF2Translate.java b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBKDF2Translate.java
new file mode 100644
index 0000000000000000000000000000000000000000..36681591e46e06435b5677d7a21935719b701b4e
--- /dev/null
+++ b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBKDF2Translate.java
@@ -0,0 +1,311 @@
+/*
+ * Copyright (c) 2012, 2014, 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.
+ */
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+import java.util.Arrays;
+import java.util.Random;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.interfaces.PBEKey;
+import javax.crypto.spec.PBEKeySpec;
+
+/**
+ * @test
+ * @bug 8041781
+ * @summary Verify if the SecretKeyFactory.translateKey() method works
+ * @author Alexander Fomin
+ * @run main PBKDF2Translate
+ */
+public class PBKDF2Translate {
+
+    private static final String[] ALGO_TO_TEST = {
+        "PBKDF2WithHmacSHA1",
+        "PBKDF2WithHmacSHA224",
+        "PBKDF2WithHmacSHA256",
+        "PBKDF2WithHmacSHA384",
+        "PBKDF2WithHmacSHA512"
+    };
+
+    private static final String PASS_PHRASE = "some hidden string";
+    private static final int ITERATION_COUNT = 1000;
+    private static final int KEY_SIZE = 128;
+
+    private final String algoToTest;
+    private final byte[] salt = new byte[8];
+
+    public static void main(String[] args) throws Exception {
+
+        boolean failed = false;
+
+        for (String algo : ALGO_TO_TEST) {
+
+            System.out.println("Testing " + algo + ":");
+            PBKDF2Translate theTest = new PBKDF2Translate(algo);
+
+            try {
+                if (!theTest.testMyOwnSecretKey()
+                        || !theTest.generateAndTranslateKey()
+                        || !theTest.translateSpoiledKey()) {
+                    // we don't want to set failed to false
+                    failed = true;
+                }
+            } catch (InvalidKeyException | NoSuchAlgorithmException |
+                    InvalidKeySpecException e) {
+                e.printStackTrace(System.err);
+                failed = true;
+            }
+        }
+
+        if (failed) {
+            throw new RuntimeException("One or more tests failed....");
+        }
+    }
+
+    public PBKDF2Translate(String algoToTest) {
+        this.algoToTest = algoToTest;
+        new Random().nextBytes(this.salt);
+    }
+
+    /**
+     * The test case scenario implemented in the method: - derive PBKDF2 key
+     * using the given algorithm; - translate the key - check if the translated
+     * and original keys have the same key value.
+     *
+     * @return true if the test case passed; false - otherwise.
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     * @throws InvalidKeyException
+     */
+    public boolean generateAndTranslateKey() throws NoSuchAlgorithmException,
+            InvalidKeySpecException, InvalidKeyException {
+        // derive PBKDF2 key
+        SecretKey key1 = getSecretKeyForPBKDF2(algoToTest);
+
+        // translate key
+        SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
+        SecretKey key2 = skf.translateKey(key1);
+
+        // check if it still the same after translation
+        if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
+            System.err.println("generateAndTranslateKey test case failed: the "
+                    + "key1 and key2 values in its primary encoding format are "
+                    + "not the same for " + algoToTest + "algorithm.");
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * The test case scenario implemented in the method: - derive Key1 for the
+     * given PBKDF2 algorithm - create my own secret Key2 as an instance of a
+     * class implements PBEKey - translate Key2 - check if the key value of the
+     * translated key and Key1 are the same.
+     *
+     * @return true if the test case passed; false - otherwise.
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     * @throws InvalidKeyException
+     */
+    public boolean testMyOwnSecretKey()
+            throws NoSuchAlgorithmException, InvalidKeySpecException,
+            InvalidKeyException {
+        SecretKey key1 = getSecretKeyForPBKDF2(algoToTest);
+        SecretKey key2 = getMyOwnSecretKey();
+
+        // Is it actually the same?
+        if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
+            System.err.println("We shouldn't be here. The key1 and key2 values "
+                    + "in its primary encoding format have to be the same!");
+            return false;
+        }
+
+        // Translate key
+        SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
+        SecretKey key3 = skf.translateKey(key2);
+
+        // Check if it still the same after translation
+        if (!Arrays.equals(key1.getEncoded(), key3.getEncoded())) {
+            System.err.println("testMyOwnSecretKey test case failed: the key1 "
+                    + "and key3 values in its primary encoding format are not "
+                    + "the same for " + algoToTest + "algorithm.");
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * The test case scenario implemented in the method: - create my own secret
+     * Key2 as an instance of a class implements PBEKey - spoil the key (set
+     * iteration count to 0, for example) - try to translate key -
+     * InvalidKeyException is expected.
+     *
+     * @return true if InvalidKeyException occurred; false - otherwise.
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     */
+    public boolean translateSpoiledKey() throws NoSuchAlgorithmException,
+            InvalidKeySpecException {
+        // derive the key
+        SecretKey key1 = getMyOwnSecretKey();
+
+        // spoil the key
+        ((MyPBKDF2SecretKey) key1).spoil();
+
+        // translate key
+        SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
+        try {
+            SecretKey key2 = skf.translateKey(key1);
+        } catch (InvalidKeyException ike) {
+            // this is expected
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Generate a PBKDF2 secret key using given algorithm.
+     *
+     * @param algoToDeriveKey PBKDF2 algorithm
+     * @return PBKDF2 secret key
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     */
+    private SecretKey getSecretKeyForPBKDF2(String algoToDeriveKey)
+            throws NoSuchAlgorithmException, InvalidKeySpecException {
+        SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToDeriveKey);
+
+        PBEKeySpec spec = new PBEKeySpec(PASS_PHRASE.toCharArray(),
+                this.salt, ITERATION_COUNT, KEY_SIZE);
+
+        return skf.generateSecret(spec);
+    }
+
+    /**
+     * Generate a secrete key as an instance of a class implements PBEKey.
+     *
+     * @return secrete key
+     * @throws InvalidKeySpecException
+     * @throws NoSuchAlgorithmException
+     */
+    private SecretKey getMyOwnSecretKey() throws InvalidKeySpecException,
+            NoSuchAlgorithmException {
+        return new MyPBKDF2SecretKey(PASS_PHRASE, this.algoToTest, this.salt,
+                ITERATION_COUNT, KEY_SIZE);
+    }
+}
+
+/**
+ * An utility class to check the SecretKeyFactory.translateKey() method.
+ */
+class MyPBKDF2SecretKey implements PBEKey {
+
+    private final byte[] key;
+    private final byte[] salt;
+    private final String algorithm;
+    private final int keySize, keyLength;
+    private int itereationCount;
+    private final String pass;
+
+    @Override
+    public String getAlgorithm() {
+        return algorithm;
+    }
+
+    @Override
+    public String getFormat() {
+        return "RAW";
+    }
+
+    @Override
+    public byte[] getEncoded() {
+        byte[] copy = new byte[keyLength];
+        System.arraycopy(this.key, 0, copy, 0, keyLength);
+        return copy;
+    }
+
+    /**
+     * The key is generating by SecretKeyFactory and its value just copying in
+     * the key field of MySecretKey class. So, this is real key derived using
+     * the given algorithm.
+     *
+     * @param passPhrase some string intended to be a password
+     * @param algo PBKDF2 algorithm
+     * @param salt slat for PBKDF2
+     * @param iterationCount iteration count
+     * @param keySize key size in bits
+     * @throws InvalidKeySpecException
+     * @throws NoSuchAlgorithmException
+     */
+    public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt,
+            int iterationCount, int keySize)
+            throws InvalidKeySpecException, NoSuchAlgorithmException {
+        this.algorithm = algo;
+        this.salt = salt;
+        this.itereationCount = iterationCount;
+        this.keySize = keySize;
+        this.pass = passPhrase;
+
+        PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(),
+                this.salt, iterationCount, this.keySize);
+
+        SecretKeyFactory keyFactory
+                = SecretKeyFactory.getInstance(algo);
+
+        SecretKey realKey = keyFactory.generateSecret(spec);
+
+        this.keyLength = realKey.getEncoded().length;
+
+        this.key = new byte[this.keyLength];
+        System.arraycopy(realKey.getEncoded(), 0, this.key, 0,
+                this.keyLength);
+    }
+
+    @Override
+    public int getIterationCount() {
+        return itereationCount;
+    }
+
+    @Override
+    public byte[] getSalt() {
+        return salt;
+    }
+
+    @Override
+    public char[] getPassword() {
+        return this.pass.toCharArray();
+    }
+
+    /**
+     * Spoil the generated key (before translation) to cause an
+     * InvalidKeyException
+     */
+    public void spoil() {
+        this.itereationCount = -1;
+    }
+
+}
diff --git a/jdk/test/com/sun/crypto/provider/Cipher/PBE/TestCipherKeyWrapperPBEKey.java b/jdk/test/com/sun/crypto/provider/Cipher/PBE/TestCipherKeyWrapperPBEKey.java
new file mode 100644
index 0000000000000000000000000000000000000000..cc237d0549da316c5761b435bd1518080eff3d7e
--- /dev/null
+++ b/jdk/test/com/sun/crypto/provider/Cipher/PBE/TestCipherKeyWrapperPBEKey.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2012, 2014, 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.
+ */
+
+import java.io.PrintStream;
+import java.security.AlgorithmParameters;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.Provider;
+import java.security.Security;
+import java.security.spec.AlgorithmParameterSpec;
+import java.util.Arrays;
+import java.util.Random;
+import java.util.StringTokenizer;
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.PBEParameterSpec;
+
+/**
+ * @test
+ * @bug 8041781
+ * @summary Test to see if key wrapper works correctly with PBEKey
+ * @author Yu-Ching (Valerie) PENG
+ * @author Bill Situ
+ * @author Yun Ke
+ * @run main TestCipherKeyWrapperPBEKey
+ */
+public class TestCipherKeyWrapperPBEKey {
+
+    private static final String[] PBEAlgorithms = {
+        "pbeWithMD5ANDdes",
+        "PBEWithMD5AndDES/CBC/PKCS5Padding",
+        "PBEWithMD5AndTripleDES",
+        "PBEWithMD5AndTripleDES/CBC/PKCS5Padding",
+        "PBEwithSHA1AndDESede",
+        "PBEwithSHA1AndDESede/CBC/PKCS5Padding",
+        "PBEwithSHA1AndRC2_40",
+        "PBEwithSHA1Andrc2_40/CBC/PKCS5Padding",
+        "PBEWithSHA1AndRC2_128",
+        "PBEWithSHA1andRC2_128/CBC/PKCS5Padding",
+        "PBEWithSHA1AndRC4_40",
+        "PBEWithsha1AndRC4_40/ECB/NoPadding",
+        "PBEWithSHA1AndRC4_128",
+        "pbeWithSHA1AndRC4_128/ECB/NoPadding",
+        "PBEWithHmacSHA1AndAES_128",
+        "PBEWithHmacSHA224AndAES_128",
+        "PBEWithHmacSHA256AndAES_128",
+        "PBEWithHmacSHA384AndAES_128",
+        "PBEWithHmacSHA512AndAES_128",
+        "PBEWithHmacSHA1AndAES_256",
+        "PBEWithHmacSHA224AndAES_256",
+        "PBEWithHmacSHA256AndAES_256",
+        "PBEWithHmacSHA384AndAES_256",
+        "PBEWithHmacSHA512AndAES_256"
+    };
+
+    public static void main(String[] args) {
+
+        TestCipherKeyWrapperPBEKey test = new TestCipherKeyWrapperPBEKey();
+        Provider sunjce = Security.getProvider("SunJCE");
+
+        if (!test.runAll(sunjce, System.out)) {
+            throw new RuntimeException("One or more tests have failed....");
+        }
+    }
+
+    public boolean runAll(Provider p, PrintStream out) {
+        boolean finalResult = true;
+
+        for (String algorithm : PBEAlgorithms) {
+            out.println("Running test with " + algorithm + ":");
+            try {
+                if (!runTest(p, algorithm, out)) {
+                    finalResult = false;
+                    out.println("STATUS: Failed");
+                } else {
+                    out.println("STATUS: Passed");
+                }
+            } catch (Exception ex) {
+                finalResult = false;
+                ex.printStackTrace(out);
+                out.println("STATUS:Failed");
+            }
+        }
+
+        return finalResult;
+    }
+
+    // Have a generic throws Exception as it can throw many different exceptions
+    public boolean runTest(Provider p, String algo, PrintStream out)
+            throws Exception {
+
+        byte[] salt = new byte[8];
+        int ITERATION_COUNT = 1000;
+        AlgorithmParameters pbeParams = null;
+
+        String baseAlgo
+                = new StringTokenizer(algo, "/").nextToken().toUpperCase();
+        boolean isAES = baseAlgo.contains("AES");
+
+        try {
+            // Initialization
+            new Random().nextBytes(salt);
+            AlgorithmParameterSpec aps = new PBEParameterSpec(salt,
+                    ITERATION_COUNT);
+            SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
+            SecretKey key = skf.generateSecret(new PBEKeySpec(
+                    "Secret Key".toCharArray()));
+            Cipher ci = Cipher.getInstance(algo);
+
+            if (isAES) {
+                ci.init(Cipher.WRAP_MODE, key);
+                pbeParams = ci.getParameters();
+            } else {
+                ci.init(Cipher.WRAP_MODE, key, aps);
+            }
+
+            byte[] keyWrapper = ci.wrap(key);
+            if (isAES) {
+                ci.init(Cipher.UNWRAP_MODE, key, pbeParams);
+            } else {
+                ci.init(Cipher.UNWRAP_MODE, key, aps);
+            }
+
+            Key unwrappedKey = ci.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);
+
+            if (baseAlgo.endsWith("TRIPLEDES")
+                    || baseAlgo.endsWith("AES_256")) {
+                out.print(
+                        "InvalidKeyException not thrown when keyStrength > 128");
+                return false;
+            }
+
+            return (Arrays.equals(key.getEncoded(), unwrappedKey.getEncoded()));
+
+        } catch (InvalidKeyException ex) {
+
+            if ((baseAlgo.endsWith("TRIPLEDES")
+                    || baseAlgo.endsWith("AES_256"))) {
+                out.println("Expected InvalidKeyException, keyStrength > 128");
+                return true;
+            } else {
+                throw ex;
+            }
+        }
+    }
+}
diff --git a/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java b/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
index 3927037448867444e3be8861a9e5c32e930b15ff..ba507479e02144bd2557160c708c518b69305c6a 100644
--- a/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
+++ b/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
@@ -23,10 +23,13 @@
 
 /**
  * @test
+ * @run main/othervm LdapTimeoutTest
  * @bug 7094377 8000487 6176036 7056489
  * @summary Timeout tests for ldap
  */
 
+import com.sun.jndi.ldap.Connection;
+
 import java.net.Socket;
 import java.net.ServerSocket;
 import java.net.SocketTimeoutException;
@@ -38,7 +41,9 @@ import java.util.concurrent.Callable;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
 
 public class LdapTimeoutTest {
     private static final ScheduledExecutorService pool =
@@ -85,7 +90,7 @@ public class LdapTimeoutTest {
     void ldapReadTimeoutTest(Hashtable env, boolean ssl) {
         InitialContext ctx = null;
         if (ssl) env.put(Context.SECURITY_PROTOCOL, "ssl");
-        ScheduledFuture killer = killSwitch(5000);
+        ScheduledFuture killer = killSwitch(5_000);
         long start = System.nanoTime();
         try {
             ctx = new InitialDirContext(env);
@@ -113,7 +118,7 @@ public class LdapTimeoutTest {
 
     void simpleAuthConnectTest(Hashtable env) {
         InitialContext ctx = null;
-        ScheduledFuture killer = killSwitch(5000);
+        ScheduledFuture killer = killSwitch(5_000);
         long start = System.nanoTime();
         try {
             ctx = new InitialDirContext(env);
@@ -123,7 +128,7 @@ public class LdapTimeoutTest {
         } catch (NamingException e) {
             long end = System.nanoTime();
             if (e.getCause() instanceof SocketTimeoutException) {
-                if (TimeUnit.NANOSECONDS.toMillis(end - start) < 2900) {
+                if (NANOSECONDS.toMillis(end - start) < 2_900) {
                     pass();
                 } else {
                     System.err.println("Fail: Waited too long");
@@ -142,8 +147,8 @@ public class LdapTimeoutTest {
 
     void deadServerNoTimeout(Hashtable env) {
         InitialContext ctx = null;
-        ScheduledFuture killer = killSwitch(30000);
-        long start = System.nanoTime();
+        ScheduledFuture killer = killSwitch(30_000);
+        long start = System.currentTimeMillis();
         try {
             ctx = new InitialDirContext(env);
             SearchControls scl = new SearchControls();
@@ -153,10 +158,12 @@ public class LdapTimeoutTest {
             // shouldn't reach here
             fail();
         } catch (NamingException e) {
-            long end = System.nanoTime();
-            if (TimeUnit.NANOSECONDS.toMillis(end - start) < 14000) {
-                System.err.println("fail: timeout should be at least 15 seconds, actual time: "
-                                   + TimeUnit.NANOSECONDS.toMillis(end - start));
+            long elapsed = System.currentTimeMillis() - start;
+            if (elapsed < Connection.DEFAULT_READ_TIMEOUT_MILLIS) {
+                System.err.printf("fail: timeout should be at least %s ms, " +
+                                "actual time is %s ms%n",
+                        Connection.DEFAULT_READ_TIMEOUT_MILLIS, elapsed);
+                e.printStackTrace();
                 fail();
             } else {
                 pass();
@@ -184,7 +191,7 @@ public class LdapTimeoutTest {
                 System.exit(0);
                 return null;
             }
-        }, ms, TimeUnit.MILLISECONDS);
+        }, ms, MILLISECONDS);
     }
 
     static class Server extends Thread {
diff --git a/jdk/test/com/sun/security/sasl/ntlm/NTLMTest.java b/jdk/test/com/sun/security/sasl/ntlm/NTLMTest.java
index 64f5eae184c1e9ddf8c509ee5922ccdc4d153d0a..46d2f0413832b4b045d06db12eac25f6dde41065 100644
--- a/jdk/test/com/sun/security/sasl/ntlm/NTLMTest.java
+++ b/jdk/test/com/sun/security/sasl/ntlm/NTLMTest.java
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 6911951
+ * @bug 6911951 7150092
  * @summary NTLM should be a supported Java SASL mechanism
  */
 import java.io.IOException;
@@ -59,7 +59,6 @@ public class NTLMTest {
 
         checkAuthOnly();
         checkClientNameOverride();
-        checkServerDomainOverride();
         checkClientDomainOverride();
         checkVersions();
         checkClientHostname();
@@ -116,15 +115,12 @@ public class NTLMTest {
         Map<String,Object> ps = new HashMap<>();
         ps.put("com.sun.security.sasl.ntlm.version", vs);
         SaslClient clnt = Sasl.createSaslClient(
-                new String[]{MECH}, USER1, PROTOCOL, null, pc,
+                new String[]{MECH}, USER1, PROTOCOL, REALM, pc,
                 new CallbackHandler() {
                     public void handle(Callback[] callbacks)
                             throws IOException, UnsupportedCallbackException {
                         for (Callback cb: callbacks) {
-                            if (cb instanceof NameCallback) {
-                                NameCallback ncb = (NameCallback)cb;
-                                ncb.setName(ncb.getDefaultName());
-                            } else if (cb instanceof PasswordCallback) {
+                            if (cb instanceof PasswordCallback) {
                                 ((PasswordCallback)cb).setPassword(PASS1);
                             }
                         }
@@ -159,15 +155,12 @@ public class NTLMTest {
         Map<String,Object> pc = new HashMap<>();
         pc.put("com.sun.security.sasl.ntlm.hostname", "this.is.com");
         SaslClient clnt = Sasl.createSaslClient(
-                new String[]{MECH}, USER1, PROTOCOL, null, pc,
+                new String[]{MECH}, USER1, PROTOCOL, REALM, pc,
                 new CallbackHandler() {
                     public void handle(Callback[] callbacks)
                             throws IOException, UnsupportedCallbackException {
                         for (Callback cb: callbacks) {
-                            if (cb instanceof NameCallback) {
-                                NameCallback ncb = (NameCallback)cb;
-                                ncb.setName(ncb.getDefaultName());
-                            } else if (cb instanceof PasswordCallback) {
+                            if (cb instanceof PasswordCallback) {
                                 ((PasswordCallback)cb).setPassword(PASS1);
                             }
                         }
@@ -212,12 +205,8 @@ public class NTLMTest {
                     public void handle(Callback[] callbacks)
                             throws IOException, UnsupportedCallbackException {
                         for (Callback cb: callbacks) {
-                            if (cb instanceof NameCallback) {
-                                NameCallback ncb = (NameCallback)cb;
-                                ncb.setName(ncb.getDefaultName());
-                            } else if(cb instanceof RealmCallback) {
-                                RealmCallback dcb = (RealmCallback)cb;
-                                dcb.setText("THIRDDOMAIN");
+                            if (cb instanceof RealmCallback) {
+                                ((RealmCallback)cb).setText(REALM);
                             } else if (cb instanceof PasswordCallback) {
                                 ((PasswordCallback)cb).setPassword(PASS1);
                             }
@@ -255,13 +244,13 @@ public class NTLMTest {
      */
     private static void checkClientNameOverride() throws Exception {
         SaslClient clnt = Sasl.createSaslClient(
-                new String[]{MECH}, null, PROTOCOL, null, null,
+                new String[]{MECH}, "someone", PROTOCOL, REALM, null,
                 new CallbackHandler() {
                     public void handle(Callback[] callbacks)
                             throws IOException, UnsupportedCallbackException {
                         for (Callback cb: callbacks) {
                             if (cb instanceof NameCallback) {
-                                NameCallback ncb = (NameCallback)cb;
+                                NameCallback ncb = (NameCallback) cb;
                                 ncb.setName(USER1);
                             } else if (cb instanceof PasswordCallback) {
                                 ((PasswordCallback)cb).setPassword(PASS1);
@@ -270,54 +259,7 @@ public class NTLMTest {
                     }
                 });
 
-        SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, REALM, null,
-                new CallbackHandler() {
-                    public void handle(Callback[] callbacks)
-                            throws IOException, UnsupportedCallbackException {
-                        String domain = null, name = null;
-                        PasswordCallback pcb = null;
-                        for (Callback cb: callbacks) {
-                            if (cb instanceof NameCallback) {
-                                name = ((NameCallback)cb).getDefaultName();
-                            } else if (cb instanceof RealmCallback) {
-                                domain = ((RealmCallback)cb).getDefaultText();
-                            } else if (cb instanceof PasswordCallback) {
-                                pcb = (PasswordCallback)cb;
-                            }
-                        }
-                        if (pcb != null) {
-                            pcb.setPassword(getPass(domain, name));
-                        }
-                    }
-                });
-
-        handshake(clnt, srv);
-    }
-
-    /**
-     * server side domain provided in props.
-     * @throws Exception
-     */
-    private static void checkServerDomainOverride() throws Exception {
-        SaslClient clnt = Sasl.createSaslClient(
-                new String[]{MECH}, USER1, PROTOCOL, null, null,
-                new CallbackHandler() {
-                    public void handle(Callback[] callbacks)
-                            throws IOException, UnsupportedCallbackException {
-                        for (Callback cb: callbacks) {
-                            if (cb instanceof NameCallback) {
-                                NameCallback ncb = (NameCallback)cb;
-                                ncb.setName(ncb.getDefaultName());
-                            } else if (cb instanceof PasswordCallback) {
-                                ((PasswordCallback)cb).setPassword(PASS1);
-                            }
-                        }
-                    }
-                });
-
-        Map<String,Object> ps = new HashMap<>();
-        ps.put("com.sun.security.sasl.ntlm.domain", REALM);
-        SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, null, ps,
+        SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, "FAKE", null,
                 new CallbackHandler() {
                     public void handle(Callback[] callbacks)
                             throws IOException, UnsupportedCallbackException {
diff --git a/jdk/test/java/io/Serializable/subclassGC/security.policy b/jdk/test/java/io/Serializable/subclassGC/security.policy
index 299734564865bdf53ada773685118b26d2ad8ff7..894df4cd2dd450606e1de6995ef7c8137ad0cb88 100644
--- a/jdk/test/java/io/Serializable/subclassGC/security.policy
+++ b/jdk/test/java/io/Serializable/subclassGC/security.policy
@@ -1,6 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-	permission java.security.AllPermission;
-};
 
 grant {
 	permission java.lang.RuntimePermission "createClassLoader";
diff --git a/jdk/test/java/lang/Class/forName/NonJavaNames.sh b/jdk/test/java/lang/Class/forName/NonJavaNames.sh
index 77a3ae25624a84463746fb29f74bc40e4f36aaec..f7114e4612b8df9e1384d695151474f507b068b0 100644
--- a/jdk/test/java/lang/Class/forName/NonJavaNames.sh
+++ b/jdk/test/java/lang/Class/forName/NonJavaNames.sh
@@ -25,19 +25,17 @@
 # @bug 4952558
 # @summary Verify names that aren't legal Java names are accepted by forName.
 # @author Joseph D. Darcy
-# @compile -source 1.5 -target 1.5 NonJavaNames.java
+# @compile NonJavaNames.java
 # @run shell NonJavaNames.sh
 
 # This test uses hand-generated class files stored in the ./classes
 # directory.  After the renaming done below, those class files have
-# single character names that are legal class names under class file
-# version 49 but *not* legal Java language identifiers; e.g. "3" and
-# "+".  First, Z.java is compiled to Z.class using "-target 1.5."
-# Next, to create a test class file, the appropriate name structures
-# within the class files are updated, as is the "Hello world" string
-# the class's main method prints out.  If the definition of the
-# semantics of "-target 1.5" changes, the test class files should be
-# regenerated.
+# single character names that are legal class names under in the class
+# file but *not* legal Java language identifiers; e.g. "3" and "+".
+# First, Z.java is compiled to Z.class.  Next, to create a test class
+# file, the appropriate name structures within the class files are
+# updated, as is the "Hello world" string the class's main method
+# prints out.
 
 # Verify directory context variables are set
 if [ "${TESTJAVA}" = "" ]
diff --git a/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java b/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java
index a8e75896a6f4961aa949cdf6fa28a9671db0f585..cbde18a378d3093495a0f27d1b58bb8862d77842 100644
--- a/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java
+++ b/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java
@@ -80,7 +80,6 @@ public class CheckPackageAccess {
         "com.sun.org.glassfish.",
         "com.oracle.xmlns.internal.",
         "com.oracle.webservices.internal.",
-        "oracle.jrockit.jfr.",
         "org.jcp.xml.dsig.internal.",
         "jdk.internal.",
         "jdk.nashorn.internal.",
diff --git a/jdk/test/java/lang/System/System.policy b/jdk/test/java/lang/System/System.policy
index 9ce33d151137bd2093b5647567f677c51cb8375f..f42ab696949e0735e3393af19403d306ec988202 100644
--- a/jdk/test/java/lang/System/System.policy
+++ b/jdk/test/java/lang/System/System.policy
@@ -1,10 +1,5 @@
 //
 // Used by SecurityRace.java 
-// Standard extensions get all permissions by default
-
-grant codeBase "file:${{java.ext.dirs}}/*" {
-	permission java.security.AllPermission;
-};
 
 // default permissions granted to all domains
 
diff --git a/jdk/test/java/net/URLPermission/policy.1 b/jdk/test/java/net/URLPermission/policy.1
index 5816cdbfce69f9e92502b126fa99664b2892b5bc..a74687191654dbd6dede6bfd39021e942915452a 100644
--- a/jdk/test/java/net/URLPermission/policy.1
+++ b/jdk/test/java/net/URLPermission/policy.1
@@ -37,9 +37,56 @@ grant {
 };
 
 // Normal permissions that aren't granted when run under jtreg
+grant codeBase "file:${java.home}/lib/ext/ucrypto.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2ucrypto";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.OracleUcrypto";
+        permission java.security.SecurityPermission "clearProviderProperties.OracleUcrypto";
+        permission java.security.SecurityPermission "removeProviderProperty.OracleUcrypto";
+        permission java.io.FilePermission "${java.home}/lib/security/ucrypto-solaris.cfg", "read";
+};
 
-grant codeBase "file:${{java.ext.dirs}}/*" {
-        permission java.security.AllPermission;
+grant codeBase "file:${java.home}/lib/ext/sunec.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunec";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunEC";
+        permission java.security.SecurityPermission "clearProviderProperties.SunEC";
+        permission java.security.SecurityPermission "removeProviderProperty.SunEC";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunjce_provider.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+        permission java.security.SecurityPermission "clearProviderProperties.SunJCE";
+        permission java.security.SecurityPermission "removeProviderProperty.SunJCE";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunpkcs11.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2pkcs11";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.*";
+        permission java.security.SecurityPermission "clearProviderProperties.*";
+        permission java.security.SecurityPermission "removeProviderProperty.*";
+        permission java.security.SecurityPermission "getProperty.auth.login.defaultCallbackHandler";
+        permission java.security.SecurityPermission "authProvider.*";
+        // Needed for reading PKCS11 config file and NSS library check
+        permission java.io.FilePermission "<<ALL FILES>>", "read";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunmscapi.jar" {
+        Permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunmscapi";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunMSCAPI";
+        permission java.security.SecurityPermission "clearProviderProperties.SunMSCAPI";
+        permission java.security.SecurityPermission "removeProviderProperty.SunMSCAPI";
 };
 
 grant codeBase "file:${{java.home}}/jre/lib/rt.jar" {
diff --git a/jdk/test/java/net/URLPermission/policy.2 b/jdk/test/java/net/URLPermission/policy.2
index d1d774f4c35e87a308b414bfbcdfb37c26478dc6..b71126a9ab96b45c4df956a7a8359fb4bb3a4160 100644
--- a/jdk/test/java/net/URLPermission/policy.2
+++ b/jdk/test/java/net/URLPermission/policy.2
@@ -36,8 +36,57 @@ grant {
     permission "java.lang.RuntimePermission" "setFactory";
 };
 
-grant codeBase "file:${{java.ext.dirs}}/*" {
-        permission java.security.AllPermission;
+// Normal permissions that aren't granted when run under jtreg
+grant codeBase "file:${java.home}/lib/ext/ucrypto.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2ucrypto";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.OracleUcrypto";
+        permission java.security.SecurityPermission "clearProviderProperties.OracleUcrypto";
+        permission java.security.SecurityPermission "removeProviderProperty.OracleUcrypto";
+        permission java.io.FilePermission "${java.home}/lib/security/ucrypto-solaris.cfg", "read";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunec.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunec";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunEC";
+        permission java.security.SecurityPermission "clearProviderProperties.SunEC";
+        permission java.security.SecurityPermission "removeProviderProperty.SunEC";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunjce_provider.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+        permission java.security.SecurityPermission "clearProviderProperties.SunJCE";
+        permission java.security.SecurityPermission "removeProviderProperty.SunJCE";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunpkcs11.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2pkcs11";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.*";
+        permission java.security.SecurityPermission "clearProviderProperties.*";
+        permission java.security.SecurityPermission "removeProviderProperty.*";
+        permission java.security.SecurityPermission "getProperty.auth.login.defaultCallbackHandler";
+        permission java.security.SecurityPermission "authProvider.*";
+        // Needed for reading PKCS11 config file and NSS library check
+        permission java.io.FilePermission "<<ALL FILES>>", "read";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunmscapi.jar" {
+        Permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunmscapi";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunMSCAPI";
+        permission java.security.SecurityPermission "clearProviderProperties.SunMSCAPI";
+        permission java.security.SecurityPermission "removeProviderProperty.SunMSCAPI";
 };
 
 grant codeBase "file:///export/repos/jdk8/build/linux-x86_64-normal-server-fastdebug/images/j2sdk-image/jre/lib/rt.jar" {
diff --git a/jdk/test/java/net/URLPermission/policy.3 b/jdk/test/java/net/URLPermission/policy.3
index 47f213fae5cfbe00d4cd543a8fdb69b5c48045e7..9c29ce37096d82018cc5c8fc46b5d6e3a20de3d8 100644
--- a/jdk/test/java/net/URLPermission/policy.3
+++ b/jdk/test/java/net/URLPermission/policy.3
@@ -37,9 +37,56 @@ grant {
 };
 
 // Normal permissions that aren't granted when run under jtreg
+grant codeBase "file:${java.home}/lib/ext/ucrypto.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2ucrypto";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.OracleUcrypto";
+        permission java.security.SecurityPermission "clearProviderProperties.OracleUcrypto";
+        permission java.security.SecurityPermission "removeProviderProperty.OracleUcrypto";
+        permission java.io.FilePermission "${java.home}/lib/security/ucrypto-solaris.cfg", "read";
+};
 
-grant codeBase "file:${{java.ext.dirs}}/*" {
-        permission java.security.AllPermission;
+grant codeBase "file:${java.home}/lib/ext/sunec.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunec";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunEC";
+        permission java.security.SecurityPermission "clearProviderProperties.SunEC";
+        permission java.security.SecurityPermission "removeProviderProperty.SunEC";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunjce_provider.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+        permission java.security.SecurityPermission "clearProviderProperties.SunJCE";
+        permission java.security.SecurityPermission "removeProviderProperty.SunJCE";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunpkcs11.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2pkcs11";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.*";
+        permission java.security.SecurityPermission "clearProviderProperties.*";
+        permission java.security.SecurityPermission "removeProviderProperty.*";
+        permission java.security.SecurityPermission "getProperty.auth.login.defaultCallbackHandler";
+        permission java.security.SecurityPermission "authProvider.*";
+        // Needed for reading PKCS11 config file and NSS library check
+        permission java.io.FilePermission "<<ALL FILES>>", "read";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunmscapi.jar" {
+        Permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunmscapi";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunMSCAPI";
+        permission java.security.SecurityPermission "clearProviderProperties.SunMSCAPI";
+        permission java.security.SecurityPermission "removeProviderProperty.SunMSCAPI";
 };
 
 grant codeBase "file:${{java.home}}/jre/lib/rt.jar" {
diff --git a/jdk/test/java/nio/charset/spi/default-pol b/jdk/test/java/nio/charset/spi/default-pol
index 557979ef936012305c79024c823c78d467255bba..1f5acba9cc04b1a422f447e322fbb9ccbf6605c1 100644
--- a/jdk/test/java/nio/charset/spi/default-pol
+++ b/jdk/test/java/nio/charset/spi/default-pol
@@ -1,10 +1,4 @@
 
-// Standard extensions get all permissions by default
-
-grant codeBase "file:${java.home}/lib/ext/*" {
-	permission java.security.AllPermission;
-};
-
 // default permissions granted to all domains
 
 grant { 
diff --git a/jdk/test/java/rmi/activation/Activatable/checkActivateRef/security.policy b/jdk/test/java/rmi/activation/Activatable/checkActivateRef/security.policy
index dfe43b5610fa9c1448953429515a928949ef48ff..d847e377e905c70aa711617c1a180783e434bf0a 100644
--- a/jdk/test/java/rmi/activation/Activatable/checkActivateRef/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/checkActivateRef/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // test explicitly acccesses sun.rmi.server.ActivatableRef
   permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.server";
diff --git a/jdk/test/java/rmi/activation/Activatable/checkAnnotations/security.policy b/jdk/test/java/rmi/activation/Activatable/checkAnnotations/security.policy
index a66e2347ace618108ea923161771aac810930e34..572e29ce30951287ec71df04979d138ae7535d65 100644
--- a/jdk/test/java/rmi/activation/Activatable/checkAnnotations/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/checkAnnotations/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/security.policy b/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/security.policy
index e1f626a741f5fec09ec558bca78f934afbf180a4..300b2fc4f71d62f654e3561887d26b45645a5899 100644
--- a/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // need to move some classes out of the tests classpath; specific to this test
   permission java.io.FilePermission "${test.classes}", "read,write,delete";
diff --git a/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/security.policy b/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/security.policy
index 5dc768f4b0b382128d739adc3ed1518436029c09..0c257a26879880a7a7ce5eb3c00272f7d29d7588 100644
--- a/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/security.policy b/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/security.policy
index 5dc768f4b0b382128d739adc3ed1518436029c09..0c257a26879880a7a7ce5eb3c00272f7d29d7588 100644
--- a/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/security.policy b/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/security.policy
index 6040d293183d8f446934a0adea06124c95a1e445..de2a5cf74e8965fc31ddd3c3367adf4c66c4414f 100644
--- a/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // need to move some classes out of the tests classpath; specific to this test
   permission java.io.FilePermission "${test.classes}", "read,write,delete";
diff --git a/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/security.policy b/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/security.policy
index 021293f9b1c132c02ecbd8a324180d2aa7daf8af..2348c442bb5301fc58a5800f11246e4883cd413e 100644
--- a/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // Needed because of bug#: 4182104
   permission java.lang.RuntimePermission "modifyThreadGroup";
diff --git a/jdk/test/java/rmi/activation/Activatable/extLoadedImpl/security.policy b/jdk/test/java/rmi/activation/Activatable/extLoadedImpl/security.policy
index 17eee960528f9e70f5ac5e935d93f1bfe425207a..0c9ca1ab750320a692807d0443ae3c1e05e46759 100644
--- a/jdk/test/java/rmi/activation/Activatable/extLoadedImpl/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/extLoadedImpl/security.policy
@@ -1,6 +1,3 @@
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
 
 grant {
   // standard activation permissions
diff --git a/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/security.policy b/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/security.policy
index 5dc768f4b0b382128d739adc3ed1518436029c09..0c257a26879880a7a7ce5eb3c00272f7d29d7588 100644
--- a/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/inactiveGroup/security.policy b/jdk/test/java/rmi/activation/Activatable/inactiveGroup/security.policy
index 5dc768f4b0b382128d739adc3ed1518436029c09..0c257a26879880a7a7ce5eb3c00272f7d29d7588 100644
--- a/jdk/test/java/rmi/activation/Activatable/inactiveGroup/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/inactiveGroup/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/nestedActivate/security.policy b/jdk/test/java/rmi/activation/Activatable/nestedActivate/security.policy
index 0360715a13e3391910ec1bd92d6bda57454ccb08..7349f99226e1f980bfd084c73892a51601e70de5 100644
--- a/jdk/test/java/rmi/activation/Activatable/nestedActivate/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/nestedActivate/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/security.policy b/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/security.policy
index 7507759080f1053d0be982a97b4aa27ff84c663b..74a40dd36af815726a46d612ae35d3b565c4ed0b 100644
--- a/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/restartCrashedService/security.policy b/jdk/test/java/rmi/activation/Activatable/restartCrashedService/security.policy
index 7d39957fbed644512d63ddf0f2d4e8f9a1c474cc..73fdf10507cafcc5463e28a88257be18362fb1bf 100644
--- a/jdk/test/java/rmi/activation/Activatable/restartCrashedService/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/restartCrashedService/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/restartLatecomer/security.policy b/jdk/test/java/rmi/activation/Activatable/restartLatecomer/security.policy
index c8d41ab3bf24d31b4afe5c8a73f613b700da39b4..c30b6e6c9a84a00bd852893e108a783363eba5fa 100644
--- a/jdk/test/java/rmi/activation/Activatable/restartLatecomer/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/restartLatecomer/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/restartService/security.policy b/jdk/test/java/rmi/activation/Activatable/restartService/security.policy
index c8d41ab3bf24d31b4afe5c8a73f613b700da39b4..c30b6e6c9a84a00bd852893e108a783363eba5fa 100644
--- a/jdk/test/java/rmi/activation/Activatable/restartService/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/restartService/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/security.policy b/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/security.policy
index 608548bffd2aeb52dd38d412b9dcaa830f71db2a..257bb5369a3e30ef5817f7afa2060c56e4f969f8 100644
--- a/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/Activatable/unregisterInactive/security.policy b/jdk/test/java/rmi/activation/Activatable/unregisterInactive/security.policy
index dc187840881378c0c433897b250c5f16a9027207..6fd298d6a2ba5324eddb5b14c177d56346ef6e98 100644
--- a/jdk/test/java/rmi/activation/Activatable/unregisterInactive/security.policy
+++ b/jdk/test/java/rmi/activation/Activatable/unregisterInactive/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/ActivationSystem/activeGroup/security.policy b/jdk/test/java/rmi/activation/ActivationSystem/activeGroup/security.policy
index 50a0955c7664d20eb885c69d1c8824b6051ce557..a6851ff680e150995043fc12872d49e7ba205235 100644
--- a/jdk/test/java/rmi/activation/ActivationSystem/activeGroup/security.policy
+++ b/jdk/test/java/rmi/activation/ActivationSystem/activeGroup/security.policy
@@ -1,6 +1,3 @@
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
 
 grant {
   // standard test activation permissions
diff --git a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/security.policy b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/security.policy
index a66e2347ace618108ea923161771aac810930e34..572e29ce30951287ec71df04979d138ae7535d65 100644
--- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/security.policy
+++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/security.policy b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/security.policy
index a372f5c292ec5544375b11449b9a9adce5d0c8c8..4fc5934ff33bf94444794aab433c2540240bb719 100644
--- a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/security.policy
+++ b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/activation/CommandEnvironment/security.policy b/jdk/test/java/rmi/activation/CommandEnvironment/security.policy
index b94b19d4ff26d2aaf471e77db1a76f2eb23cfa30..de4eaa178342631af7f98f2c6ad134a40948d978 100644
--- a/jdk/test/java/rmi/activation/CommandEnvironment/security.policy
+++ b/jdk/test/java/rmi/activation/CommandEnvironment/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // standard test activation permissions
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/dgc/VMID/security.policy b/jdk/test/java/rmi/dgc/VMID/security.policy
index 34dac373edb34e5652bac017eeecdc507c82b3c7..d61012dad31ef86f06680d21ceb110bc05b88baf 100644
--- a/jdk/test/java/rmi/dgc/VMID/security.policy
+++ b/jdk/test/java/rmi/dgc/VMID/security.policy
@@ -1,11 +1,6 @@
 /*
  * security policy used by MarshalForeignStub test
  */
-
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
 
     // used by TestLibrary to determine test environment
diff --git a/jdk/test/java/rmi/dgc/dgcImplInsulation/security.policy b/jdk/test/java/rmi/dgc/dgcImplInsulation/security.policy
index 927b31143b616a7f39b59e3511f6e443292e4106..047846ac892bb96fa637e11179dee927d499461a 100644
--- a/jdk/test/java/rmi/dgc/dgcImplInsulation/security.policy
+++ b/jdk/test/java/rmi/dgc/dgcImplInsulation/security.policy
@@ -1,11 +1,6 @@
 /*
  * security policy used by the test process
  */
-
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // so that synchronous DGC dirty call will succeed
   permission java.net.SocketPermission "*:1024-", "accept,connect,listen";
diff --git a/jdk/test/java/rmi/registry/classPathCodebase/security.policy b/jdk/test/java/rmi/registry/classPathCodebase/security.policy
index 1bd7df667492a72a825acb3f9df9066618b185bf..e45924702f27460447e20f864d43671d7fd3b89f 100644
--- a/jdk/test/java/rmi/registry/classPathCodebase/security.policy
+++ b/jdk/test/java/rmi/registry/classPathCodebase/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // need to move some classes out of the test's classpath; specific to this test
   permission java.io.FilePermission "${test.classes}", "read,write,delete";
diff --git a/jdk/test/java/rmi/server/RMIClassLoader/delegateToContextLoader/security.policy b/jdk/test/java/rmi/server/RMIClassLoader/delegateToContextLoader/security.policy
index 1091602fc15463132a9aca4b3dddf3c113ef5025..989ed1c731f6dd75087d9052301c086f2e84a69f 100644
--- a/jdk/test/java/rmi/server/RMIClassLoader/delegateToContextLoader/security.policy
+++ b/jdk/test/java/rmi/server/RMIClassLoader/delegateToContextLoader/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // test must create a context loader for the current thread.
   permission java.lang.RuntimePermission "createClassLoader";
diff --git a/jdk/test/java/rmi/server/RMIClassLoader/downloadArrayClass/security.policy b/jdk/test/java/rmi/server/RMIClassLoader/downloadArrayClass/security.policy
index da38143213b9ee889ccf0c01751223892a743883..3e843ebdc5fcb77212ddfa67d3a501ca3fc81eeb 100644
--- a/jdk/test/java/rmi/server/RMIClassLoader/downloadArrayClass/security.policy
+++ b/jdk/test/java/rmi/server/RMIClassLoader/downloadArrayClass/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
     permission java.util.PropertyPermission
         "java.rmi.server.codebase", "read,write";
diff --git a/jdk/test/java/rmi/server/RMIClassLoader/getClassLoader/security.policy b/jdk/test/java/rmi/server/RMIClassLoader/getClassLoader/security.policy
index 07a51234010ad34b96f7e5f53ee67d75accf4d64..ca6fedbe2bfb720269d995062c5873b6f466978a 100644
--- a/jdk/test/java/rmi/server/RMIClassLoader/getClassLoader/security.policy
+++ b/jdk/test/java/rmi/server/RMIClassLoader/getClassLoader/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
     // permissions needed to move classes into separate codebase directories
     permission java.io.FilePermission
diff --git a/jdk/test/java/rmi/server/RMIClassLoader/loadProxyClasses/security.policy b/jdk/test/java/rmi/server/RMIClassLoader/loadProxyClasses/security.policy
index 64b54c0668c9e7d06f62b7aa0172e22cbf6c1f50..194493983e40ba37c44f66a05fcd4d0c09bd947e 100644
--- a/jdk/test/java/rmi/server/RMIClassLoader/loadProxyClasses/security.policy
+++ b/jdk/test/java/rmi/server/RMIClassLoader/loadProxyClasses/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
 
     // permissions needed to move classes into separate codebase directories
diff --git a/jdk/test/java/rmi/server/RMIClassLoader/spi/security.policy b/jdk/test/java/rmi/server/RMIClassLoader/spi/security.policy
index e0f42085879ea4b62744ae5d0139ed10faad2bdb..fc8a55fd793d9582314c895953911db6615eda4e 100644
--- a/jdk/test/java/rmi/server/RMIClassLoader/spi/security.policy
+++ b/jdk/test/java/rmi/server/RMIClassLoader/spi/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
 
     // permissions needed to move classes into separate codebase directories
diff --git a/jdk/test/java/rmi/server/RMIClassLoader/useCodebaseOnly/security.policy b/jdk/test/java/rmi/server/RMIClassLoader/useCodebaseOnly/security.policy
index 56ee500423e02a791af8c77c9345a63f8e466a59..2ec8b5349c53281112aef8b3f653bd2110e76393 100644
--- a/jdk/test/java/rmi/server/RMIClassLoader/useCodebaseOnly/security.policy
+++ b/jdk/test/java/rmi/server/RMIClassLoader/useCodebaseOnly/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
 
     // specific property access needed by this test
diff --git a/jdk/test/java/rmi/server/RMIClassLoader/useGetURLs/security.policy b/jdk/test/java/rmi/server/RMIClassLoader/useGetURLs/security.policy
index 632e365db138da70a1a49584c73811d9c892bf01..4b97ac42f5386213a6f9ccaaca083be6ce765f2d 100644
--- a/jdk/test/java/rmi/server/RMIClassLoader/useGetURLs/security.policy
+++ b/jdk/test/java/rmi/server/RMIClassLoader/useGetURLs/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // the test needs to move classfiles out of its classpath
   permission java.io.FilePermission "${test.classes}", "read,write,delete";
diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/security.policy b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/security.policy
index 32bad22496fe8b4a28dde3f9a12386abcd67cb04..6c8a471c993f9f8ef37b426546e76e1b596854fe 100644
--- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/security.policy
+++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // property specifically accessed by this test
   permission java.util.PropertyPermission "user.name", "read";
diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/security.policy b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/security.policy
index cf981186069e837ac112ec2e5fd3f28c5bc94b47..523ea94a7a2bb1e4035ecac1543ff771c83efa9c 100644
--- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/security.policy
+++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // used by TestLibrary to determine extra commandline properties
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/security.policy b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/security.policy
index efc7293079c5be1ceeef8a25e5f68c81f3679b4b..70bf79ac69ec010d116428896f1e92f989121ab7 100644
--- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/security.policy
+++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // used by TestLibrary to determine extra commandline properties
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/server/RemoteServer/setLogPermission/java.policy b/jdk/test/java/rmi/server/RemoteServer/setLogPermission/java.policy
index 69b80e2ab6075aa41f9e09cbf301f275e049f16f..e41f260730ec2b0e52373799ac75c5d511d8a58e 100644
--- a/jdk/test/java/rmi/server/RemoteServer/setLogPermission/java.policy
+++ b/jdk/test/java/rmi/server/RemoteServer/setLogPermission/java.policy
@@ -1,7 +1,3 @@
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
     permission java.util.logging.LoggingPermission "control";
 };
diff --git a/jdk/test/java/rmi/server/clientStackTrace/security.policy b/jdk/test/java/rmi/server/clientStackTrace/security.policy
index a1539df552976eb306c25c944dd0dd6cd138b106..2913666a0ee44f3ca39171913f78e2d4bf812c97 100644
--- a/jdk/test/java/rmi/server/clientStackTrace/security.policy
+++ b/jdk/test/java/rmi/server/clientStackTrace/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // test needs to export rmid and communicate with objects on arbitrary ports
   permission java.net.SocketPermission "*:1024-", "connect,accept,listen";
diff --git a/jdk/test/java/rmi/server/useCustomRef/security.policy b/jdk/test/java/rmi/server/useCustomRef/security.policy
index 4697584b455034a1da78213fe993146664c64e9e..6f5e0c9ad370d02106e5e19dbfca8667c5fa5df1 100644
--- a/jdk/test/java/rmi/server/useCustomRef/security.policy
+++ b/jdk/test/java/rmi/server/useCustomRef/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // the test uses a class in the package sun.rmi.server
   permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.registry";
diff --git a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/security.policy b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/security.policy
index b0d94405c8816599691aea89445c9fd190bdad3d..2ae9c27386decc02c96eadb4aa51149721c31916 100644
--- a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/security.policy
+++ b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // used by TestLibrary to determine extra commandline properties
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/transport/dgcDeadLock/security.policy b/jdk/test/java/rmi/transport/dgcDeadLock/security.policy
index 3a8acd6b6c5fff0ac1e73f5dd4d474236d759fa5..b1caaba7e00722cc607d6cf8a4b472e2b37a3a32 100644
--- a/jdk/test/java/rmi/transport/dgcDeadLock/security.policy
+++ b/jdk/test/java/rmi/transport/dgcDeadLock/security.policy
@@ -2,10 +2,6 @@
  * security policy used by the test process
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
   // used by TestLibrary to determine extra commandline properties
   permission java.io.FilePermission "..${/}..${/}test.props", "read";
diff --git a/jdk/test/java/rmi/transport/httpSocket/security.policy b/jdk/test/java/rmi/transport/httpSocket/security.policy
index a0e932009e6b417f655283246f898dd8c57726b5..f1960c9772d3c5d71abb4a0b1cee7c2b06853537 100644
--- a/jdk/test/java/rmi/transport/httpSocket/security.policy
+++ b/jdk/test/java/rmi/transport/httpSocket/security.policy
@@ -1,6 +1,3 @@
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
 
 grant {
     permission java.net.SocketPermission "*:1024-", "accept,connect,listen";
diff --git a/jdk/test/java/security/KeyRep/Serial.policy b/jdk/test/java/security/KeyRep/Serial.policy
index d6aca88985aa14142451742c7038868e14c1d2c3..b538d57b791ea52cf97d14785e5e8edec918640d 100644
--- a/jdk/test/java/security/KeyRep/Serial.policy
+++ b/jdk/test/java/security/KeyRep/Serial.policy
@@ -1,5 +1,10 @@
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
+grant codeBase "file:${java.home}/lib/ext/sunjce_provider.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+        permission java.security.SecurityPermission "clearProviderProperties.SunJCE";
+        permission java.security.SecurityPermission "removeProviderProperty.SunJCE";
 };
 
 grant {
diff --git a/jdk/test/java/security/KeyRep/SerialOld.policy b/jdk/test/java/security/KeyRep/SerialOld.policy
index 4d3483cdf8c6197886ccdc0ae9f9eaef623c15f9..b13f3b7399ba29c0b45df4fe6b7890c240d83318 100644
--- a/jdk/test/java/security/KeyRep/SerialOld.policy
+++ b/jdk/test/java/security/KeyRep/SerialOld.policy
@@ -1,5 +1,53 @@
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
+grant codeBase "file:${java.home}/lib/ext/ucrypto.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2ucrypto";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.OracleUcrypto";
+        permission java.security.SecurityPermission "clearProviderProperties.OracleUcrypto";
+        permission java.security.SecurityPermission "removeProviderProperty.OracleUcrypto";
+        permission java.io.FilePermission "${java.home}/lib/security/ucrypto-solaris.cfg", "read";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunec.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunec";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunEC";
+        permission java.security.SecurityPermission "clearProviderProperties.SunEC";
+        permission java.security.SecurityPermission "removeProviderProperty.SunEC";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunjce_provider.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+        permission java.security.SecurityPermission "clearProviderProperties.SunJCE";
+        permission java.security.SecurityPermission "removeProviderProperty.SunJCE";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunpkcs11.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2pkcs11";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.*";
+        permission java.security.SecurityPermission "clearProviderProperties.*";
+        permission java.security.SecurityPermission "removeProviderProperty.*";
+        permission java.security.SecurityPermission "getProperty.auth.login.defaultCallbackHandler";
+        permission java.security.SecurityPermission "authProvider.*";
+        // Needed for reading PKCS11 config file and NSS library check
+        permission java.io.FilePermission "<<ALL FILES>>", "read";
+};
+
+grant codeBase "file:${java.home}/lib/ext/sunmscapi.jar" {
+        Permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "loadLibrary.sunmscapi";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunMSCAPI";
+        permission java.security.SecurityPermission "clearProviderProperties.SunMSCAPI";
+        permission java.security.SecurityPermission "removeProviderProperty.SunMSCAPI";
 };
 
 grant {
@@ -8,11 +56,11 @@ grant {
     permission java.util.PropertyPermission "test.src", "read";
 
     permission java.lang.RuntimePermission
-	"accessClassInPackage.sun.security.provider";
+        "accessClassInPackage.sun.security.provider";
     permission java.lang.RuntimePermission
-	"accessClassInPackage.sun.security.pkcs";
+        "accessClassInPackage.sun.security.pkcs";
     permission java.lang.RuntimePermission
-	"accessClassInPackage.sun.security.x509";
+        "accessClassInPackage.sun.security.x509";
     permission java.lang.RuntimePermission
-	"accessClassInPackage.sun.security.rsa";
+        "accessClassInPackage.sun.security.rsa";
 };
diff --git a/jdk/test/java/security/Policy/GetInstance/GetInstance.policy b/jdk/test/java/security/Policy/GetInstance/GetInstance.policy
index 4d00233644f0abd9408d82b8fbc6b432ea839d8e..6fa7f37ae16456c8a33641f1bcec76ea12eee20f 100644
--- a/jdk/test/java/security/Policy/GetInstance/GetInstance.policy
+++ b/jdk/test/java/security/Policy/GetInstance/GetInstance.policy
@@ -1,6 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-        permission java.security.AllPermission;
-};
 
 grant {
     permission java.security.SecurityPermission
diff --git a/jdk/test/java/security/Policy/GetInstance/GetInstance.policyURL b/jdk/test/java/security/Policy/GetInstance/GetInstance.policyURL
index d73cec1f4a7475dcd430f52d6f7a662e80e03de0..766819b042ad9ca880b56154949c524610f8ba9a 100644
--- a/jdk/test/java/security/Policy/GetInstance/GetInstance.policyURL
+++ b/jdk/test/java/security/Policy/GetInstance/GetInstance.policyURL
@@ -1,7 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-        permission java.security.AllPermission;
-};
-
 grant {
     permission java.security.SecurityPermission "GetInstanceTest";
 };
diff --git a/jdk/test/java/security/Policy/GetInstance/GetInstanceSecurity.policy b/jdk/test/java/security/Policy/GetInstance/GetInstanceSecurity.policy
index a1a460497cdaf097d1f5241774a22a81b195bb6f..c5dc0eab23f5bd74ac1cab631840ede99c49ed79 100644
--- a/jdk/test/java/security/Policy/GetInstance/GetInstanceSecurity.policy
+++ b/jdk/test/java/security/Policy/GetInstance/GetInstanceSecurity.policy
@@ -1,7 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-	permission java.security.AllPermission;
-};
-
 grant {
     // do not grant this:
     //
diff --git a/jdk/test/java/security/Security/AddProvider.policy.1 b/jdk/test/java/security/Security/AddProvider.policy.1
index 17a49b47b77fb86734aa079a9ae856b9aea039b4..64b43d7a1ef516745e8bc105a120899048895d3c 100644
--- a/jdk/test/java/security/Security/AddProvider.policy.1
+++ b/jdk/test/java/security/Security/AddProvider.policy.1
@@ -1,7 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-	permission java.security.AllPermission;
-};
-
 grant {
     permission java.security.SecurityPermission "insertProvider";
 };
diff --git a/jdk/test/java/security/Security/AddProvider.policy.2 b/jdk/test/java/security/Security/AddProvider.policy.2
index d5a7ca9444249dac681252de97cde9f1e6d3e114..f976821953d92ccb5dee295fb5883ec04d03ee48 100644
--- a/jdk/test/java/security/Security/AddProvider.policy.2
+++ b/jdk/test/java/security/Security/AddProvider.policy.2
@@ -1,6 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-	permission java.security.AllPermission;
-};
 
 grant {
     permission java.security.SecurityPermission "insertProvider.Test1";
diff --git a/jdk/test/java/security/Security/AddProvider.policy.3 b/jdk/test/java/security/Security/AddProvider.policy.3
index 930b443d7f683ab28d0111913be85806815bb91e..b35cd3042800774765837639c18fecc420c78083 100644
--- a/jdk/test/java/security/Security/AddProvider.policy.3
+++ b/jdk/test/java/security/Security/AddProvider.policy.3
@@ -1,6 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-	permission java.security.AllPermission;
-};
 
 grant {
     permission java.security.SecurityPermission "insertProvider.*";
diff --git a/jdk/test/java/security/Security/removing/RemoveStaticProvider.policy b/jdk/test/java/security/Security/removing/RemoveStaticProvider.policy
index 3b186afa3cd9caac8af0320a15323b68f3394f16..061e60a141371c50e91e7f1d971543e89fff640f 100644
--- a/jdk/test/java/security/Security/removing/RemoveStaticProvider.policy
+++ b/jdk/test/java/security/Security/removing/RemoveStaticProvider.policy
@@ -1,10 +1,15 @@
+
+grant codeBase "file:${java.home}/lib/ext/sunjce_provider.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+        permission java.security.SecurityPermission "clearProviderProperties.SunJCE";
+        permission java.security.SecurityPermission "removeProviderProperty.SunJCE";
+};
+
 grant {
     permission java.security.SecurityPermission "removeProvider.SunJCE";
     permission java.security.SecurityPermission "insertProvider.SunJCE";
 };
 
-// Standard extensions get all permissions
-grant codeBase "file:${java.home}/lib/ext/*" {
-        permission java.security.AllPermission;
-};
-
diff --git a/jdk/test/java/text/Bidi/Bug7051769.java b/jdk/test/java/text/Bidi/Bug7051769.java
index 1a96870b14fdcd2f60625da9f9c73082b90e7366..9b1326021b53d993f5903717d5cdf4ed66651801 100644
--- a/jdk/test/java/text/Bidi/Bug7051769.java
+++ b/jdk/test/java/text/Bidi/Bug7051769.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, 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
@@ -23,8 +23,11 @@
 
 /*
  * @test
- * @bug 7051769
+ * @bug 7051769 8038092
  * @summary verify that Bidi.toString() returns the corect result.
+ *     The second run is intended to test lazy SharedSectets init for 8038092
+ * @run main Bug7051769
+ * @run main/othervm -DpreloadBidi=true Bug7051769
  */
 import java.awt.font.*;
 import java.text.*;
@@ -32,6 +35,18 @@ import java.util.*;
 
 public class Bug7051769 {
 
+    static {
+        if (System.getProperty("preloadBidi", "").equals("true")) {
+            // Make sure the SharedSecret is lazily initialized correctly
+            try {
+                Class.forName("sun.text.bidi.BidiBase");
+                System.out.println("BidiBase class has been pre-loaded.");
+            } catch (ClassNotFoundException e) {
+                System.out.println("BidiBase class could not be pre-loaded.");
+            }
+        }
+    }
+
     private static boolean err = false;
 
     public static void main(String[] args) {
diff --git a/jdk/test/java/util/IdentityHashMap/Capacity.java b/jdk/test/java/util/IdentityHashMap/Capacity.java
new file mode 100644
index 0000000000000000000000000000000000000000..3114e6c16de86fa5c5e83a9141cab9a73b05d29a
--- /dev/null
+++ b/jdk/test/java/util/IdentityHashMap/Capacity.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Random;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.*;
+
+/*
+ * @test
+ * @bug 6904367
+ * @summary IdentityHashMap reallocates storage when inserting expected
+ *          number of elements
+ * @run testng Capacity
+ */
+
+@Test
+public class Capacity {
+    static final Field tableField;
+    static final Random random = new Random();
+    static final Object[][] sizesData;
+
+    @DataProvider(name="sizes", parallel = true)
+    public Object[][] sizesToTest() { return sizesData; }
+
+    static {
+        try {
+            tableField = IdentityHashMap.class.getDeclaredField("table");
+            tableField.setAccessible(true);
+        } catch (NoSuchFieldException e) {
+            throw new LinkageError("table", e);
+        }
+
+        ArrayList<Object[]> sizes = new ArrayList<>();
+        for (int size = 0; size < 200; size++)
+            sizes.add(new Object[] { size });
+
+        // some numbers known to demonstrate bug 6904367
+        for (int size : new int[] {682, 683, 1365, 2730, 2731, 5461})
+            sizes.add(new Object[] { size });
+
+        // a few more random sizes to try
+        for (int i = 0; i != 128; i++)
+            sizes.add(new Object[] { random.nextInt(5000) });
+
+        sizesData = sizes.toArray(new Object[0][]);
+    }
+
+    static int capacity(IdentityHashMap<?,?> map) {
+        try {
+            return ((Object[]) tableField.get(map)).length / 2;
+        } catch (Throwable t) {
+            throw new LinkageError("table", t);
+        }
+    }
+
+    static void assertCapacity(IdentityHashMap<?,?> map,
+                               int expectedCapacity) {
+        assertEquals(capacity(map), expectedCapacity);
+    }
+
+    static void growUsingPut(IdentityHashMap<Object,Object> map,
+                             int elementsToAdd) {
+        for (int i = 0; i < elementsToAdd; i++)
+            map.put(new Object(), new Object());
+    }
+
+    static void growUsingPutAll(IdentityHashMap<Object,Object> map,
+                                int elementsToAdd) {
+        IdentityHashMap<Object,Object> other = new IdentityHashMap<>();
+        growUsingPut(other, elementsToAdd);
+        map.putAll(other);
+    }
+
+    static void growUsingRepeatedPutAll(IdentityHashMap<Object,Object> map,
+                                        int elementsToAdd) {
+        for (int i = 0; i < elementsToAdd; i++)
+            map.putAll(Collections.singletonMap(new Object(),
+                                                new Object()));
+    }
+
+    /**
+     * Checks that expected number of items can be inserted into
+     * the map without resizing of the internal storage
+     */
+    @Test(dataProvider = "sizes")
+    public void canInsertExpectedItemsWithoutResizing(int size)
+        throws Throwable {
+        // First try growing using put()
+        IdentityHashMap<Object,Object> m = new IdentityHashMap<>(size);
+        int initialCapacity = capacity(m);
+        growUsingPut(m, size);
+        assertCapacity(m, initialCapacity);
+
+        // Doubling from the expected size will cause exactly one
+        // resize, except near minimum capacity.
+        if (size > 1) {
+            growUsingPut(m, size);
+            assertCapacity(m, 2 * initialCapacity);
+        }
+
+        // Try again, growing with putAll()
+        m = new IdentityHashMap<>(size);
+        initialCapacity = capacity(m);
+        growUsingPutAll(m, size);
+        assertCapacity(m, initialCapacity);
+
+        // Doubling from the expected size will cause exactly one
+        // resize, except near minimum capacity.
+        if (size > 1) {
+            growUsingPutAll(m, size);
+            assertCapacity(m, 2 * initialCapacity);
+        }
+    }
+
+    /**
+     * Given the expected size, computes such a number N of items that
+     * inserting (N+1) items will trigger resizing of the internal storage
+     */
+    static int threshold(int size) throws Throwable {
+        IdentityHashMap<Object,Object> m = new IdentityHashMap<>(size);
+        int initialCapacity = capacity(m);
+        while (capacity(m) == initialCapacity)
+            growUsingPut(m, 1);
+        return m.size() - 1;
+    }
+
+    /**
+     * Checks that inserting (threshold+1) item causes resizing
+     * of the internal storage
+     */
+    @Test(dataProvider = "sizes")
+    public void passingThresholdCausesResize(int size) throws Throwable {
+        final int threshold = threshold(size);
+        IdentityHashMap<Object,Object> m = new IdentityHashMap<>(threshold);
+        int initialCapacity = capacity(m);
+
+        growUsingPut(m, threshold);
+        assertCapacity(m, initialCapacity);
+
+        growUsingPut(m, 1);
+        assertCapacity(m, 2 * initialCapacity);
+    }
+
+    /**
+     * Checks that 4 methods of requiring capacity lead to the same
+     * internal capacity, unless sized below default capacity.
+     */
+    @Test(dataProvider = "sizes")
+    public void differentGrowthPatternsResultInSameCapacity(int size)
+        throws Throwable {
+        if (size < 21)          // 21 is default maxExpectedSize
+            return;
+
+        IdentityHashMap<Object,Object> m;
+        m = new IdentityHashMap<Object,Object>(size);
+        int capacity1 = capacity(m);
+
+        m = new IdentityHashMap<>();
+        growUsingPut(m, size);
+        int capacity2 = capacity(m);
+
+        m = new IdentityHashMap<>();
+        growUsingPutAll(m, size);
+        int capacity3 = capacity(m);
+
+        m = new IdentityHashMap<>();
+        growUsingRepeatedPutAll(m, size);
+        int capacity4 = capacity(m);
+
+        if (capacity1 != capacity2 ||
+            capacity2 != capacity3 ||
+            capacity3 != capacity4)
+            throw new AssertionError("Capacities not equal: "
+                                     + capacity1 + " "
+                                     + capacity2 + " "
+                                     + capacity3 + " "
+                                     + capacity4);
+    }
+
+    public void defaultExpectedMaxSizeIs21() {
+        assertCapacity(new IdentityHashMap<Long,Long>(), 32);
+        assertCapacity(new IdentityHashMap<Long,Long>(21), 32);
+    }
+
+    public void minimumCapacityIs4() {
+        assertCapacity(new IdentityHashMap<Long,Long>(0), 4);
+        assertCapacity(new IdentityHashMap<Long,Long>(1), 4);
+        assertCapacity(new IdentityHashMap<Long,Long>(2), 4);
+        assertCapacity(new IdentityHashMap<Long,Long>(3), 8);
+    }
+
+    @Test(enabled = false)
+    /** needs too much memory to run normally */
+    public void maximumCapacityIs2ToThe29() {
+        assertCapacity(new IdentityHashMap<Long,Long>(Integer.MAX_VALUE),
+                       1 << 29);
+    }
+}
diff --git a/jdk/test/java/util/logging/CheckZombieLockTest.java b/jdk/test/java/util/logging/CheckZombieLockTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..f0b0a930c68f65b6b1daa71c8e1463c729f78c0d
--- /dev/null
+++ b/jdk/test/java/util/logging/CheckZombieLockTest.java
@@ -0,0 +1,369 @@
+/*
+ * Copyright (c) 2014, 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     8048020
+ * @author  Daniel Fuchs
+ * @summary Regression on java.util.logging.FileHandler.
+ *     The fix is to avoid filling up the file system with zombie lock files.
+ *
+ * @run  main/othervm CheckZombieLockTest WRITABLE CLOSE CLEANUP
+ * @run  main/othervm CheckZombieLockTest CLEANUP
+ * @run  main/othervm CheckZombieLockTest WRITABLE
+ * @run  main/othervm CheckZombieLockTest CREATE_FIRST
+ * @run  main/othervm CheckZombieLockTest CREATE_NEXT
+ * @run  main/othervm CheckZombieLockTest CREATE_NEXT
+ * @run  main/othervm CheckZombieLockTest CLEANUP
+ * @run  main/othervm CheckZombieLockTest REUSE
+ * @run  main/othervm CheckZombieLockTest CLEANUP
+ */
+import java.io.File;
+import java.io.IOException;
+import java.nio.channels.FileChannel;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.logging.FileHandler;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+public class CheckZombieLockTest {
+
+    private static final String WRITABLE_DIR = "writable-dir";
+    private static volatile boolean supportsLocking = true;
+
+    static enum TestCase {
+        WRITABLE,  // just verifies that we can create a file in our 'writable-dir'
+        CLOSE, // checks that closing a FileHandler removes its lock file
+        CREATE_FIRST, // verifies that 'writable-dir' contains no lock, then creates a first FileHandler.
+        CREATE_NEXT, // verifies that 'writable-dir' contains a single lock, then creates the next FileHandler
+        REUSE, // verifies that zombie lock files can be reused
+        CLEANUP // removes "writable-dir"
+    };
+
+    public static void main(String... args) throws IOException {
+        // we'll base all file creation attempts on the system temp directory,
+        // %t
+        File writableDir = setup();
+        System.out.println("Writable dir is: "+writableDir.getAbsolutePath());
+        // we now have one writable directory to work with:
+        //    writableDir
+        if (args == null || args.length == 0) {
+            args = new String[] { "WRITABLE", "CLOSE", "CLEANUP" };
+        }
+        try {
+            runTests(writableDir, args);
+        } catch (RuntimeException | IOException | Error x) {
+            // some error occured: cleanup
+            delete(writableDir);
+            throw x;
+        }
+    }
+
+    /**
+     * @param writableDir in which log and lock file are created
+     * @throws SecurityException
+     * @throws RuntimeException
+     * @throws IOException
+     */
+    private static void runTests(File writableDir, String... args) throws SecurityException,
+            RuntimeException, IOException {
+        for (String arg : args) {
+            switch(TestCase.valueOf(arg)) {
+                // Test 1: makes sure we can create FileHandler in writable directory
+                case WRITABLE: checkWritable(writableDir); break;
+                // Test 2: verifies that FileHandler.close() cleans up its lock file
+                case CLOSE: testFileHandlerClose(writableDir); break;
+                // Test 3: creates the first file handler
+                case CREATE_FIRST: testFileHandlerCreate(writableDir, true); break;
+                // Test 4, 5, ... creates the next file handler
+                case CREATE_NEXT: testFileHandlerCreate(writableDir, false); break;
+                // Checks that zombie lock files are reused appropriatly
+                case REUSE: testFileHandlerReuse(writableDir); break;
+                // Removes the writableDir
+                case CLEANUP: delete(writableDir); break;
+                default: throw new RuntimeException("No such test case: "+arg);
+            }
+        }
+    }
+
+    /**
+     * @param writableDir in which log and lock file are created
+     * @throws SecurityException
+     * @throws RuntimeException
+     * @throws IOException
+     */
+    private static void checkWritable(File writableDir) throws SecurityException,
+            RuntimeException, IOException {
+        // Test 1: make sure we can create/delete files in the writable dir.
+        final File file = new File(writableDir, "test.txt");
+        if (!createFile(file, false)) {
+            throw new IOException("Can't create "+file+"\n\tUnable to run test");
+        } else {
+            delete(file);
+        }
+    }
+
+
+    private static FileHandler createFileHandler(File writableDir) throws SecurityException,
+            RuntimeException, IOException {
+        // Test 1: make sure we can create FileHandler in writable directory
+        try {
+            FileHandler handler = new FileHandler("%t/" + WRITABLE_DIR + "/log.log");
+            handler.publish(new LogRecord(Level.INFO, handler.toString()));
+            handler.flush();
+            return handler;
+        } catch (IOException ex) {
+            throw new RuntimeException("Test failed: should have been able"
+                    + " to create FileHandler for " + "%t/" + WRITABLE_DIR
+                    + "/log.log in writable directory.", ex);
+        }
+    }
+
+    private static List<File> listLocks(File writableDir, boolean print)
+            throws IOException {
+        List<File> locks = new ArrayList<>();
+        for (File f : writableDir.listFiles()) {
+            if (print) {
+                System.out.println("Found file: " + f.getName());
+            }
+            if (f.getName().endsWith(".lck")) {
+                locks.add(f);
+            }
+        }
+        return locks;
+    }
+
+    private static void testFileHandlerClose(File writableDir) throws IOException {
+        File fakeLock = new File(writableDir, "log.log.lck");
+        if (!createFile(fakeLock, false)) {
+            throw new IOException("Can't create fake lock file: "+fakeLock);
+        }
+        try {
+            List<File> before = listLocks(writableDir, true);
+            System.out.println("before: " +before.size() + " locks found");
+            FileHandler handler = createFileHandler(writableDir);
+            System.out.println("handler created: "+handler);
+            List<File> after = listLocks(writableDir, true);
+            System.out.println("after creating handler: " + after.size() + " locks found");
+            handler.close();
+            System.out.println("handler closed: "+handler);
+            List<File> afterClose = listLocks(writableDir, true);
+            System.out.println("after closing handler: " + afterClose.size() + " locks found");
+            afterClose.removeAll(before);
+            if (!afterClose.isEmpty()) {
+                throw new RuntimeException("Zombie lock file detected: "+ afterClose);
+            }
+        } finally {
+            if (fakeLock.canRead()) delete(fakeLock);
+        }
+        List<File> finalLocks = listLocks(writableDir, false);
+        System.out.println("After cleanup: " + finalLocks.size() + " locks found");
+    }
+
+
+    private static void testFileHandlerReuse(File writableDir) throws IOException {
+        List<File> before = listLocks(writableDir, true);
+        System.out.println("before: " +before.size() + " locks found");
+        try {
+            if (!before.isEmpty()) {
+                throw new RuntimeException("Expected no lock file! Found: "+before);
+            }
+        } finally {
+            before.stream().forEach(CheckZombieLockTest::delete);
+        }
+
+        FileHandler handler1 = createFileHandler(writableDir);
+        System.out.println("handler created: "+handler1);
+        List<File> after = listLocks(writableDir, true);
+        System.out.println("after creating handler: " + after.size() + " locks found");
+        if (after.size() != 1) {
+            throw new RuntimeException("Unexpected number of lock files found for "+handler1+": "+after);
+        }
+        final File lock = after.get(0);
+        after.clear();
+        handler1.close();
+        after = listLocks(writableDir, true);
+        System.out.println("after closing handler: " + after.size() + " locks found");
+        if (!after.isEmpty()) {
+            throw new RuntimeException("Unexpected number of lock files found for "+handler1+": "+after);
+        }
+        if (!createFile(lock, false)) {
+            throw new IOException("Can't create fake lock file: "+lock);
+        }
+        try {
+            before = listLocks(writableDir, true);
+            System.out.println("before: " +before.size() + " locks found");
+            if (before.size() != 1) {
+                throw new RuntimeException("Unexpected number of lock files found: "+before+" expected ["
+                        +lock+"].");
+            }
+            FileHandler handler2 = createFileHandler(writableDir);
+            System.out.println("handler created: "+handler2);
+            after = listLocks(writableDir, true);
+            System.out.println("after creating handler: " + after.size() + " locks found");
+            after.removeAll(before);
+            if (!after.isEmpty()) {
+                throw new RuntimeException("Unexpected lock file found: "+after
+                        + "\n\t" + lock + " should have been reused");
+            }
+            handler2.close();
+            System.out.println("handler closed: "+handler2);
+            List<File> afterClose = listLocks(writableDir, true);
+            System.out.println("after closing handler: " + afterClose.size() + " locks found");
+            if (!afterClose.isEmpty()) {
+                throw new RuntimeException("Zombie lock file detected: "+ afterClose);
+            }
+
+            if (supportsLocking) {
+                FileChannel fc = FileChannel.open(Paths.get(lock.getAbsolutePath()),
+                    StandardOpenOption.CREATE_NEW, StandardOpenOption.APPEND,
+                    StandardOpenOption.WRITE);
+                try {
+                    if (fc.tryLock() != null) {
+                        System.out.println("locked: "+lock);
+                        handler2 = createFileHandler(writableDir);
+                        System.out.println("handler created: "+handler2);
+                        after = listLocks(writableDir, true);
+                        System.out.println("after creating handler: " + after.size() + " locks found");
+                        after.removeAll(before);
+                        if (after.size() != 1) {
+                            throw new RuntimeException("Unexpected lock files found: "+after
+                                + "\n\t" + lock + " should not have been reused");
+                        }
+                    } else {
+                        throw new RuntimeException("Failed to lock: "+lock);
+                    }
+                } finally {
+                    delete(lock);
+                }
+            }
+        } finally {
+            List<File> finalLocks = listLocks(writableDir, false);
+            System.out.println("end: " + finalLocks.size() + " locks found");
+            delete(writableDir);
+        }
+    }
+
+
+    private static void testFileHandlerCreate(File writableDir, boolean first)
+            throws IOException {
+        List<File> before = listLocks(writableDir, true);
+        System.out.println("before: " +before.size() + " locks found");
+        try {
+            if (first && !before.isEmpty()) {
+                throw new RuntimeException("Expected no lock file! Found: "+before);
+            } else if (!first && before.size() != 1) {
+                throw new RuntimeException("Expected a single lock file! Found: "+before);
+            }
+        } finally {
+            before.stream().forEach(CheckZombieLockTest::delete);
+        }
+        FileHandler handler = createFileHandler(writableDir);
+        System.out.println("handler created: "+handler);
+        List<File> after = listLocks(writableDir, true);
+        System.out.println("after creating handler: " + after.size() + " locks found");
+        if (after.size() != 1) {
+            throw new RuntimeException("Unexpected number of lock files found for "+handler+": "+after);
+        }
+    }
+
+
+    /**
+     * Setup all the files and directories needed for the tests
+     *
+     * @return writable directory created that needs to be deleted when done
+     * @throws RuntimeException
+     */
+    private static File setup() throws RuntimeException {
+        // First do some setup in the temporary directory (using same logic as
+        // FileHandler for %t pattern)
+        String tmpDir = System.getProperty("java.io.tmpdir"); // i.e. %t
+        if (tmpDir == null) {
+            tmpDir = System.getProperty("user.home");
+        }
+        File tmpOrHomeDir = new File(tmpDir);
+        // Create a writable directory here (%t/writable-dir)
+        File writableDir = new File(tmpOrHomeDir, WRITABLE_DIR);
+        if (!createFile(writableDir, true)) {
+            throw new RuntimeException("Test setup failed: unable to create"
+                    + " writable working directory "
+                    + writableDir.getAbsolutePath() );
+        }
+
+        // try to determine whether file locking is supported
+        try {
+            FileChannel fc = FileChannel.open(Paths.get(writableDir.getAbsolutePath(),
+                    UUID.randomUUID().toString()+".lck"),
+                    StandardOpenOption.CREATE_NEW, StandardOpenOption.APPEND,
+                    StandardOpenOption.DELETE_ON_CLOSE);
+            try {
+                fc.tryLock();
+            } catch(IOException x) {
+                supportsLocking = false;
+            } finally {
+                fc.close();
+            }
+        } catch(Throwable t) {
+            // should not happen
+            t.printStackTrace();
+        }
+        return writableDir;
+    }
+
+    /**
+     * @param newFile
+     * @return true if file already exists or creation succeeded
+     */
+    private static boolean createFile(File newFile, boolean makeDirectory) {
+        if (newFile.exists()) {
+            return true;
+        }
+        if (makeDirectory) {
+            return newFile.mkdir();
+        } else {
+            try {
+                return newFile.createNewFile();
+            } catch (IOException ioex) {
+                ioex.printStackTrace();
+                return false;
+            }
+        }
+    }
+
+    /*
+     * Recursively delete all files starting at specified file
+     */
+    private static void delete(File f) {
+        if (f != null && f.isDirectory()) {
+            for (File c : f.listFiles())
+                delete(c);
+        }
+        if (!f.delete())
+            System.err.println(
+                    "WARNING: unable to delete/cleanup writable test directory: "
+                    + f );
+        }
+}
diff --git a/jdk/test/java/util/logging/LoggingDeadlock2.java b/jdk/test/java/util/logging/LoggingDeadlock2.java
index de328e7681a2f0b21354d698118cd8a61af256d4..c5b4e8937383f777d717ac856b438d7c25dc17c6 100644
--- a/jdk/test/java/util/logging/LoggingDeadlock2.java
+++ b/jdk/test/java/util/logging/LoggingDeadlock2.java
@@ -28,7 +28,7 @@
  * @author  Serguei Spitsyn / Hitachi / Martin Buchholz
  *
  * @build    LoggingDeadlock2
- * @run  main/timeout=15 LoggingDeadlock2
+ * @run  main LoggingDeadlock2
  *
  * There is a clear deadlock between LogManager.<clinit> and
  * Cleaner.run() methods.
diff --git a/jdk/test/javax/security/auth/login/Configuration/GetInstanceSecurity.grantedPolicy b/jdk/test/javax/security/auth/login/Configuration/GetInstanceSecurity.grantedPolicy
index 816b7ffc03b28f9fe563d7bb7016b2f1fbb48d64..bcb47b245a741f59c6c485fe5894eb5f59973e8e 100644
--- a/jdk/test/javax/security/auth/login/Configuration/GetInstanceSecurity.grantedPolicy
+++ b/jdk/test/javax/security/auth/login/Configuration/GetInstanceSecurity.grantedPolicy
@@ -1,7 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-	permission java.security.AllPermission;
-};
-
 grant {
     permission java.util.PropertyPermission "test.src", "read";
     permission java.io.FilePermission "${test.src}${/}*", "read";
diff --git a/jdk/test/javax/security/auth/login/Configuration/GetInstanceSecurity.policy b/jdk/test/javax/security/auth/login/Configuration/GetInstanceSecurity.policy
index 8a51318d3313b3d475addcf1e944c53fa0e524a6..4c0f7acfc888cffc36caccc621d09411301d95b1 100644
--- a/jdk/test/javax/security/auth/login/Configuration/GetInstanceSecurity.policy
+++ b/jdk/test/javax/security/auth/login/Configuration/GetInstanceSecurity.policy
@@ -1,6 +1,3 @@
-grant codeBase "file:${{java.ext.dirs}}/*" {
-	permission java.security.AllPermission;
-};
 
 grant {
 
diff --git a/jdk/test/jdk/nio/zipfs/test.policy b/jdk/test/jdk/nio/zipfs/test.policy
index 81261720ad79052a57bb3a9600e6dd2b9fb4eb5f..8e6ae4b6c7357c84da0d6d56802dd5aebc448cc1 100644
--- a/jdk/test/jdk/nio/zipfs/test.policy
+++ b/jdk/test/jdk/nio/zipfs/test.policy
@@ -4,10 +4,6 @@ grant codeBase "file:${java.home}/lib/ext/zipfs.jar" {
     permission java.util.PropertyPermission "*", "read";
 };
 
-grant codeBase "file:${java.home}/lib/ext/sunpkcs11.jar" {
-    permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
-};
-
 grant {
     permission java.io.FilePermission "<<ALL FILES>>","read,write,delete";
     permission java.util.PropertyPermission "test.jdk","read";
diff --git a/jdk/test/lib/security/CheckBlacklistedCerts.java b/jdk/test/lib/security/CheckBlacklistedCerts.java
index 1f162b3e4991ba3e209b119d2776cba7f77d9d05..10c2915b602edceff5b2e5dd88bfbc3b911ea9e1 100644
--- a/jdk/test/lib/security/CheckBlacklistedCerts.java
+++ b/jdk/test/lib/security/CheckBlacklistedCerts.java
@@ -62,9 +62,9 @@ public class CheckBlacklistedCerts {
         // a -testonly JPRT job.
         File[] blacklists = {
             new File(System.getProperty("test.src"),
-                "../../../src/share/lib/security/blacklisted.certs.pem"),
+                "../../../make/data/blacklistedcertsconverter/blacklisted.certs.pem"),
             new File(System.getProperty("test.src"),
-                "../../../src/closed/share/lib/security/blacklisted.certs.pem")
+                "../../../make/closed/data/blacklistedcertsconverter/blacklisted.certs.pem")
         };
 
         // Is this an OPENJDK build?
diff --git a/jdk/test/sun/net/www/http/HttpClient/IsKeepingAlive.policy b/jdk/test/sun/net/www/http/HttpClient/IsKeepingAlive.policy
index 504055e0eeed893f28f55c4b770cbdb0b352cf72..bb487b4931a379de0cf9656b38ae45eee778c73e 100644
--- a/jdk/test/sun/net/www/http/HttpClient/IsKeepingAlive.policy
+++ b/jdk/test/sun/net/www/http/HttpClient/IsKeepingAlive.policy
@@ -5,13 +5,6 @@ grant {
 	permission java.lang.RuntimePermission "accessClassInPackage.sun.net.www.http";
 };
 
-// From system java.policy
-// Standard extensions get all permissions by default
-
-grant codeBase "file:${java.home}/lib/ext/*" {
-	permission java.security.AllPermission;
-};
-
 // default permissions granted to all domains
 
 grant { 
diff --git a/jdk/test/sun/net/www/http/HttpClient/OpenServer.policy b/jdk/test/sun/net/www/http/HttpClient/OpenServer.policy
index 504055e0eeed893f28f55c4b770cbdb0b352cf72..bb487b4931a379de0cf9656b38ae45eee778c73e 100644
--- a/jdk/test/sun/net/www/http/HttpClient/OpenServer.policy
+++ b/jdk/test/sun/net/www/http/HttpClient/OpenServer.policy
@@ -5,13 +5,6 @@ grant {
 	permission java.lang.RuntimePermission "accessClassInPackage.sun.net.www.http";
 };
 
-// From system java.policy
-// Standard extensions get all permissions by default
-
-grant codeBase "file:${java.home}/lib/ext/*" {
-	permission java.security.AllPermission;
-};
-
 // default permissions granted to all domains
 
 grant { 
diff --git a/jdk/test/sun/rmi/rmic/minimizeWrapperInstances/run.sh b/jdk/test/sun/rmi/rmic/minimizeWrapperInstances/run.sh
index 7a86ae4746f4f8e781d4a1382a5a51a36713bb51..b64d9e2bf304f8d8b80e677b9969644da3de0072 100644
--- a/jdk/test/sun/rmi/rmic/minimizeWrapperInstances/run.sh
+++ b/jdk/test/sun/rmi/rmic/minimizeWrapperInstances/run.sh
@@ -45,9 +45,3 @@ ${TESTJAVA}/bin/java ${TESTVMOPTS} -classpath ${TESTCLASSES:-.} Test
 
 ${TESTJAVA}/bin/rmic -classpath ${TESTCLASSES:-.} -d ${TESTCLASSES:-.} -vcompat PImpl
 ${TESTJAVA}/bin/java ${TESTVMOPTS} -classpath ${TESTCLASSES:-.} Test
-
-${TESTJAVA}/bin/rmic -Xnew -classpath ${TESTCLASSES:-.} -d ${TESTCLASSES:-.} PImpl
-${TESTJAVA}/bin/java ${TESTVMOPTS} -classpath ${TESTCLASSES:-.} Test
-
-${TESTJAVA}/bin/rmic -Xnew -classpath ${TESTCLASSES:-.} -d ${TESTCLASSES:-.} -vcompat PImpl
-${TESTJAVA}/bin/java ${TESTVMOPTS} -classpath ${TESTCLASSES:-.} Test
diff --git a/jdk/test/sun/rmi/server/MarshalOutputStream/marshalForeignStub/security.policy b/jdk/test/sun/rmi/server/MarshalOutputStream/marshalForeignStub/security.policy
index 288a49c9b92923d48f69b4a3c5f6c641ef898ffd..8bfb6ade3af2cc350f49e864a80fea96ad352e73 100644
--- a/jdk/test/sun/rmi/server/MarshalOutputStream/marshalForeignStub/security.policy
+++ b/jdk/test/sun/rmi/server/MarshalOutputStream/marshalForeignStub/security.policy
@@ -2,10 +2,6 @@
  * security policy used by MarshalForeignStub test
  */
 
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
-};
-
 grant {
 
     // used by TestLibrary to determine test environment
diff --git a/jdk/test/sun/security/krb5/auto/SaslBasic.java b/jdk/test/sun/security/krb5/auto/SaslBasic.java
index ef38ab3185f4884fb4d1188006532b70119d1899..3fdd3534ed4e49aa07b6e09ca743581167fbb37d 100644
--- a/jdk/test/sun/security/krb5/auto/SaslBasic.java
+++ b/jdk/test/sun/security/krb5/auto/SaslBasic.java
@@ -29,6 +29,8 @@
  * @run main/othervm SaslBasic bound
  * @run main/othervm SaslBasic unbound
  */
+import com.sun.security.jgss.InquireType;
+
 import java.io.IOException;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -82,11 +84,17 @@ public class SaslBasic {
             }
         }
         if (!bound) {
-            String boundName = (String)ss.getNegotiatedProperty(Sasl.BOUND_SERVER_NAME);
+            String boundName = (String)ss.getNegotiatedProperty(
+                    Sasl.BOUND_SERVER_NAME);
             if (!boundName.equals(name)) {
                 throw new Exception("Wrong bound server name");
             }
         }
+        Object key = ss.getNegotiatedProperty(
+                "com.sun.security.jgss.inquiretype.krb5_get_session_key");
+        if (key == null) {
+            throw new Exception("Extended negotiated property not read");
+        }
         byte[] hello = "hello".getBytes();
         token = sc.wrap(hello, 0, hello.length);
         token = ss.unwrap(token, 0, token.length);
diff --git a/jdk/test/sun/security/pkcs11/KeyStore/Basic.policy b/jdk/test/sun/security/pkcs11/KeyStore/Basic.policy
index a76f3994caf110707aff3d87b1fef78931e8e2d6..97bb797f0c05c4d9e80f46d0d353d089c3efc983 100644
--- a/jdk/test/sun/security/pkcs11/KeyStore/Basic.policy
+++ b/jdk/test/sun/security/pkcs11/KeyStore/Basic.policy
@@ -1,5 +1,15 @@
-grant codeBase "file:${java.home}/lib/ext/*" {
-    permission java.security.AllPermission;
+grant codeBase "file:${java.home}/lib/ext/sunpkcs11.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2pkcs11";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.*";
+        permission java.security.SecurityPermission "clearProviderProperties.*";
+        permission java.security.SecurityPermission "removeProviderProperty.*";
+        permission java.security.SecurityPermission "getProperty.auth.login.defaultCallbackHandler";
+        permission java.security.SecurityPermission "authProvider.*";
+        // Needed for reading PKCS11 config file and NSS library check
+        permission java.io.FilePermission "<<ALL FILES>>", "read";
 };
 
 grant codebase "file:${user.dir}${/}loader.jar" {
diff --git a/jdk/test/sun/security/pkcs11/Provider/Login.policy b/jdk/test/sun/security/pkcs11/Provider/Login.policy
index 90d3a7e15239f70d7e9ec19cb0482578bcf6020c..424c87431e667d22fa5d5c58cade13ff7274e3b6 100644
--- a/jdk/test/sun/security/pkcs11/Provider/Login.policy
+++ b/jdk/test/sun/security/pkcs11/Provider/Login.policy
@@ -1,5 +1,16 @@
-grant codeBase "file:${java.home}/lib/ext/*" {
-        permission java.security.AllPermission;
+grant codeBase "file:${java.home}/lib/ext/sunpkcs11.jar" {
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
+        permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
+        permission java.lang.RuntimePermission "loadLibrary.j2pkcs11";
+        permission java.util.PropertyPermission "*", "read";
+        permission java.security.SecurityPermission "putProviderProperty.*";
+        permission java.security.SecurityPermission "clearProviderProperties.*";
+        permission java.security.SecurityPermission "removeProviderProperty.*";
+        permission java.security.SecurityPermission "getProperty.auth.login.defaultCallbackHandler";
+
+        permission java.security.SecurityPermission "authProvider.*";
+        // Needed for reading PKCS11 config file and NSS library check
+        permission java.io.FilePermission "<<ALL FILES>>", "read";
 };
 
 grant {
diff --git a/jdk/test/sun/security/provider/PolicyFile/Alias.policy b/jdk/test/sun/security/provider/PolicyFile/Alias.policy
index dbb8e05e4767e9023aa47c2a7226501eb900c5e8..003c890e24c616f68d5bce21b4293b1985747adc 100644
--- a/jdk/test/sun/security/provider/PolicyFile/Alias.policy
+++ b/jdk/test/sun/security/provider/PolicyFile/Alias.policy
@@ -10,9 +10,3 @@ grant	codebase "http://alias",
 	principal com.sun.security.auth.UnixPrincipal "unix" {
     permission java.security.SecurityPermission "ALIAS";
 };
-
-// Standard extensions get all permissions
-grant codeBase "file:${java.home}/lib/ext/*" {
-        permission java.security.AllPermission;
-};
-
diff --git a/jdk/test/sun/security/provider/PolicyFile/AliasExpansion.policy b/jdk/test/sun/security/provider/PolicyFile/AliasExpansion.policy
index 94c88590982727848a49241251fb839ea0d73e12..23cf8fd19e375ef9536c5fd67cb9d0d24e29e8c7 100644
--- a/jdk/test/sun/security/provider/PolicyFile/AliasExpansion.policy
+++ b/jdk/test/sun/security/provider/PolicyFile/AliasExpansion.policy
@@ -20,9 +20,3 @@ grant {
     permission java.security.SecurityPermission
 	"${{alias}}";
 };
-
-// Standard extensions get all permissions
-grant codeBase "file:${java.home}/lib/ext/*" {
-        permission java.security.AllPermission;
-};
-
diff --git a/jdk/test/sun/security/provider/PolicyFile/TrustedCert.policy b/jdk/test/sun/security/provider/PolicyFile/TrustedCert.policy
index 73e18cdcbbcfc032074c2612aa62ccb37c89dd65..6ebd1abedf6273d51be47d8687ddf6eaac6a30f5 100644
--- a/jdk/test/sun/security/provider/PolicyFile/TrustedCert.policy
+++ b/jdk/test/sun/security/provider/PolicyFile/TrustedCert.policy
@@ -9,8 +9,3 @@ grant principal "Tim" {
     permission java.util.PropertyPermission "foo", "read";
 };
 
-// Standard extensions get all permissions
-grant codeBase "file:${java.home}/lib/ext/*" {
-        permission java.security.AllPermission;
-};
-
diff --git a/jdk/test/tools/pack200/PackageVersionTest.java b/jdk/test/tools/pack200/PackageVersionTest.java
index dc109b8a39188d508715a89847cb4446fd812216..20a602bfad9fc2252c1be90688776c039abac55a 100644
--- a/jdk/test/tools/pack200/PackageVersionTest.java
+++ b/jdk/test/tools/pack200/PackageVersionTest.java
@@ -59,13 +59,10 @@ public class PackageVersionTest {
         }
 
         File out = new File("test.pack");
-        createClassFile("Test5");
         createClassFile("Test6");
         createClassFile("Test7");
 
         verify6991164();
-        verifyPack("Test5.class", JAVA5_PACKAGE_MAJOR_VERSION,
-                JAVA5_PACKAGE_MINOR_VERSION);
 
         verifyPack("Test6.class", JAVA6_PACKAGE_MAJOR_VERSION,
                 JAVA6_PACKAGE_MINOR_VERSION);
@@ -98,7 +95,7 @@ public class PackageVersionTest {
         String target = name.substring(name.length() - 1);
         String javacCmds[] = {
             "-source",
-            "5",
+            "6",
             "-target",
             name.substring(name.length() - 1),
             name + ".java"
diff --git a/make/jprt.properties b/make/jprt.properties
index 3a10135c56e13fd13d432cc1435f793143672fc0..a5ca05cb8c9a0e6de5d9afb8667a7254d9b58652 100644
--- a/make/jprt.properties
+++ b/make/jprt.properties
@@ -193,9 +193,7 @@ my.make.rule.test.targets.all=						\
     ${my.make.rule.test.targets.core},					\
     ${my.make.rule.test.targets.svc},					\
     ${my.test.target.set:TESTNAME=jdk_awt},				\
-    ${my.test.target.set:TESTNAME=jdk_beans1},				\
-    ${my.test.target.set:TESTNAME=jdk_beans2},				\
-    ${my.test.target.set:TESTNAME=jdk_beans3},				\
+    ${my.test.target.set:TESTNAME=jdk_beans},				\
     ${my.test.target.set:TESTNAME=jdk_sound},				\
     ${my.test.target.set:TESTNAME=jdk_swing}
 
diff --git a/nashorn/.hgtags b/nashorn/.hgtags
index 370fcc1ba8ce874034d47d271ebda8a9dfeb9f4d..b3483075230132aa64c179fc607a963e76636d51 100644
--- a/nashorn/.hgtags
+++ b/nashorn/.hgtags
@@ -255,3 +255,4 @@ fed8c83dfba4dce94d2ae1cb82f026634ff2a3e4 jdk9-b16
 46e36a92e37c06dea50f8c829549d9d0bfed4e3c jdk9-b19
 d703c59c556f9fcd9604272806ef7acf55c92363 jdk9-b20
 174cf53bce4e93a3d5d880ed7915ce8d0f08bc5e jdk9-b21
+a9d39bcfeb1bb3f7de929c56a2ecbea10a554ca1 jdk9-b22
diff --git a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
index c48bf4b26aa480bf05cd90978f7fa708f82ea2b7..098f850822d50a2843f5c50f21baff915fec5144 100644
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
@@ -53,9 +53,6 @@ public abstract class NashornException extends RuntimeException {
     // underlying ECMA error object - lazily initialized
     private Object ecmaError;
 
-    /** script source name used for "engine.js" */
-    public static final String ENGINE_SCRIPT_SOURCE_NAME = "nashorn:engine/resources/engine.js";
-
     /**
      * Constructor
      *
diff --git a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java
index 514c6ab1bc17871b74c8218a5b06578214f9f392..f19857386e6a75bbbd8dd06880ecd58d9528d018 100644
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java
@@ -25,8 +25,6 @@
 
 package jdk.nashorn.api.scripting;
 
-import static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
-import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
 import static jdk.nashorn.internal.runtime.Source.sourceFor;
 
 import java.io.IOException;
@@ -34,13 +32,10 @@ import java.io.Reader;
 import java.lang.invoke.MethodHandles;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
-import java.net.URL;
 import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.Permissions;
 import java.security.PrivilegedAction;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
 import java.security.ProtectionDomain;
 import java.text.MessageFormat;
 import java.util.Locale;
@@ -58,7 +53,6 @@ import javax.script.SimpleBindings;
 import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ErrorManager;
-import jdk.nashorn.internal.runtime.Property;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
@@ -98,9 +92,6 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
     // This is the initial default Nashorn global object.
     // This is used as "shared" global if above option is true.
     private final Global              global;
-    // initialized bit late to be made 'final'.
-    // Property object for "context" property of global object.
-    private volatile Property         contextProperty;
 
     // default options passed to Nashorn Options object
     private static final String[] DEFAULT_OPTIONS = new String[] { "-doe" };
@@ -122,30 +113,6 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
         }
     }
 
-    // load engine.js
-    private static Source loadEngineJSSource() {
-        final String script = "resources/engine.js";
-        try {
-            return AccessController.doPrivileged(
-                    new PrivilegedExceptionAction<Source>() {
-                        @Override
-                        public Source run() throws IOException {
-                            final URL url = NashornScriptEngine.class.getResource(script);
-                            return sourceFor(NashornException.ENGINE_SCRIPT_SOURCE_NAME, url);
-                        }
-                    }
-            );
-        } catch (final PrivilegedActionException e) {
-            if (Context.DEBUG) {
-                e.printStackTrace();
-            }
-            throw new RuntimeException(e);
-        }
-    }
-
-    // Source object for engine.js
-    private static final Source ENGINE_SCRIPT_SRC = loadEngineJSSource();
-
     NashornScriptEngine(final NashornScriptEngineFactory factory, final ClassLoader appLoader) {
         this(factory, DEFAULT_OPTIONS, appLoader);
     }
@@ -248,33 +215,6 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
         return getInterfaceInner(thiz, clazz);
     }
 
-    // These are called from the "engine.js" script
-
-    /**
-     * This hook is used to search js global variables exposed from Java code.
-     *
-     * @param self 'this' passed from the script
-     * @param ctxt current ScriptContext in which name is searched
-     * @param name name of the variable searched
-     * @return the value of the named variable
-     */
-    public Object __noSuchProperty__(final Object self, final ScriptContext ctxt, final String name) {
-        if (ctxt != null) {
-            final int scope = ctxt.getAttributesScope(name);
-            final Global ctxtGlobal = getNashornGlobalFrom(ctxt);
-            if (scope != -1) {
-                return ScriptObjectMirror.unwrap(ctxt.getAttribute(name, scope), ctxtGlobal);
-            }
-
-            if (self == UNDEFINED) {
-                // scope access and so throw ReferenceError
-                throw referenceError(ctxtGlobal, "not.defined", name);
-            }
-        }
-
-        return UNDEFINED;
-    }
-
     // Implementation only below this point
 
     private static Source makeSource(final Reader reader, final ScriptContext ctxt) throws ScriptException {
@@ -426,45 +366,10 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
             }
         }, CREATE_GLOBAL_ACC_CTXT);
 
-        nashornContext.initGlobal(newGlobal);
-
-        final int NON_ENUMERABLE_CONSTANT = Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE;
-        // current ScriptContext exposed as "context"
-        // "context" is non-writable from script - but script engine still
-        // needs to set it and so save the context Property object
-        contextProperty = newGlobal.addOwnProperty("context", NON_ENUMERABLE_CONSTANT, ctxt);
-        // current ScriptEngine instance exposed as "engine". We added @SuppressWarnings("LeakingThisInConstructor") as
-        // NetBeans identifies this assignment as such a leak - this is a false positive as we're setting this property
-        // in the Global of a Context we just created - both the Context and the Global were just created and can not be
-        // seen from another thread outside of this constructor.
-        newGlobal.addOwnProperty("engine", NON_ENUMERABLE_CONSTANT, this);
-        // global script arguments with undefined value
-        newGlobal.addOwnProperty("arguments", Property.NOT_ENUMERABLE, UNDEFINED);
-        // file name default is null
-        newGlobal.addOwnProperty(ScriptEngine.FILENAME, Property.NOT_ENUMERABLE, null);
-        // evaluate engine.js initialization script this new global object
-        try {
-            evalImpl(compileImpl(ENGINE_SCRIPT_SRC, newGlobal), ctxt, newGlobal);
-        } catch (final ScriptException exp) {
-            throw new RuntimeException(exp);
-        }
-        return newGlobal;
-    }
+        nashornContext.initGlobal(newGlobal, this);
+        newGlobal.setScriptContext(ctxt);
 
-    // scripts should see "context" and "engine" as variables in the given global object
-    private void setContextVariables(final Global ctxtGlobal, final ScriptContext ctxt) {
-        // set "context" global variable via contextProperty - because this
-        // property is non-writable
-        contextProperty.setValue(ctxtGlobal, ctxtGlobal, ctxt, false);
-        Object args = ScriptObjectMirror.unwrap(ctxt.getAttribute("arguments"), ctxtGlobal);
-        if (args == null || args == UNDEFINED) {
-            args = ScriptRuntime.EMPTY_ARRAY;
-        }
-        // if no arguments passed, expose it
-        if (! (args instanceof ScriptObject)) {
-            args = ctxtGlobal.wrapAsObject(args);
-            ctxtGlobal.set("arguments", args, false);
-        }
+        return newGlobal;
     }
 
     private Object invokeImpl(final Object selfObject, final String name, final Object... args) throws ScriptException, NoSuchMethodException {
@@ -533,11 +438,7 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
             }
 
             final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
-
-            // set ScriptContext variables if ctxt is non-null
-            if (ctxt != null) {
-                setContextVariables(ctxtGlobal, ctxt);
-            }
+            ctxtGlobal.setScriptContext(ctxt);
             return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
         } catch (final Exception e) {
             throwAsScriptException(e, ctxtGlobal);
@@ -560,10 +461,7 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
                 Context.setGlobal(ctxtGlobal);
             }
 
-            // set ScriptContext variables if ctxt is non-null
-            if (ctxt != null) {
-                setContextVariables(ctxtGlobal, ctxt);
-            }
+            ctxtGlobal.setScriptContext(ctxt);
             return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
         } catch (final Exception e) {
             throwAsScriptException(e, ctxtGlobal);
diff --git a/nashorn/src/jdk/nashorn/api/scripting/ScriptUtils.java b/nashorn/src/jdk/nashorn/api/scripting/ScriptUtils.java
index da5b9bdb663a4bedf8b21ba0ffd2861ba63a466b..4de2cbf5516643093caeda74ecc438e1f51aea67 100644
--- a/nashorn/src/jdk/nashorn/api/scripting/ScriptUtils.java
+++ b/nashorn/src/jdk/nashorn/api/scripting/ScriptUtils.java
@@ -25,6 +25,8 @@
 
 package jdk.nashorn.api.scripting;
 
+import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
+
 import java.lang.invoke.MethodHandle;
 import jdk.internal.dynalink.beans.StaticClass;
 import jdk.internal.dynalink.linker.LinkerServices;
@@ -69,12 +71,15 @@ public final class ScriptUtils {
      * Create a wrapper function that calls {@code func} synchronized on {@code sync} or, if that is undefined,
      * {@code self}. Used to implement "sync" function in resources/mozilla_compat.js.
      *
-     * @param func the function to invoke
+     * @param func the function to wrap
      * @param sync the object to synchronize on
      * @return a synchronizing wrapper function
      */
-    public static Object makeSynchronizedFunction(final ScriptFunction func, final Object sync) {
-        return func.makeSynchronizedFunction(sync);
+    public static Object makeSynchronizedFunction(final Object func, final Object sync) {
+        if (func instanceof ScriptFunction) {
+           return ((ScriptFunction)func).makeSynchronizedFunction(sync);
+        }
+        throw typeError("not.a.function", ScriptRuntime.safeToString(func));
     }
 
     /**
diff --git a/nashorn/src/jdk/nashorn/api/scripting/resources/engine.js b/nashorn/src/jdk/nashorn/api/scripting/resources/engine.js
deleted file mode 100644
index b9034292ac2342857f9b804f6aa7973f7c8c01ca..0000000000000000000000000000000000000000
--- a/nashorn/src/jdk/nashorn/api/scripting/resources/engine.js
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (c) 2010, 2013, 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.
- */
-
-/**
- * This script file is executed by script engine at the construction
- * of the every new Global object. The functions here assume global variables
- * "context" of type javax.script.ScriptContext and "engine" of the type
- * jdk.nashorn.api.scripting.NashornScriptEngine.
- **/
-
-Object.defineProperty(this, "__noSuchProperty__", {
-    configurable: true,
-    enumerable: false,
-    writable: true,
-    value: function (name) {
-        'use strict';
-        return engine.__noSuchProperty__(this, context, name);
-    }
-});
-
-function print() {
-    var writer = context != null? context.writer : engine.context.writer;
-    if (! (writer instanceof java.io.PrintWriter)) {
-        writer = new java.io.PrintWriter(writer);
-    }
-    
-    var buf = new java.lang.StringBuilder();
-    for (var i = 0; i < arguments.length; i++) {
-        if (i != 0) {
-            buf.append(' ');
-        }
-        buf.append(String(arguments[i]));
-    }
-    writer.println(buf.toString());
-}
-
-/**
- * This is C-like printf
- *
- * @param format string to format the rest of the print items
- * @param args variadic argument list
- */
-Object.defineProperty(this, "printf", {
-    configurable: true,
-    enumerable: false,
-    writable: true,
-    value: function (format, args/*, more args*/) {
-        print(sprintf.apply(this, arguments));
-    }
-});
-
-/**
- * This is C-like sprintf
- *
- * @param format string to format the rest of the print items
- * @param args variadic argument list
- */
-Object.defineProperty(this, "sprintf", {
-    configurable: true,
-    enumerable: false,
-    writable: true,
-    value: function (format, args/*, more args*/) {
-        var len = arguments.length - 1;
-        var array = [];
-
-        if (len < 0) {
-            return "";
-        }
-
-        for (var i = 0; i < len; i++) {
-            if (arguments[i+1] instanceof Date) {
-                array[i] = arguments[i+1].getTime();
-            } else {
-                array[i] = arguments[i+1];
-            }
-        }
-
-        array = Java.to(array);
-        return Packages.jdk.nashorn.api.scripting.ScriptUtils.format(format, array);
-    }
-});
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
index c890208879c14f7f52f1f82601dfcbe3969b12dd..46a6b86bfd37b862f8c0c1c6a943ca5238996477 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
@@ -1317,20 +1317,14 @@ final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContex
 
                         // Load up self (scope).
                         method.loadCompilerConstant(SCOPE);
-                        final CallNode.EvalArgs evalArgs = callNode.getEvalArgs();
+                        final List<Expression> evalArgs = callNode.getEvalArgs().getArgs();
                         // load evaluated code
-                        loadExpressionAsObject(evalArgs.getCode());
+                        loadExpressionAsObject(evalArgs.get(0));
                         // load second and subsequent args for side-effect
-                        final List<Expression> callArgs = callNode.getArgs();
-                        final int numArgs = callArgs.size();
+                        final int numArgs = evalArgs.size();
                         for (int i = 1; i < numArgs; i++) {
-                            loadExpressionUnbounded(callArgs.get(i)).pop();
+                            loadAndDiscard(evalArgs.get(i));
                         }
-                        // special/extra 'eval' arguments
-                        loadExpressionUnbounded(evalArgs.getThis());
-                        method.load(evalArgs.getLocation());
-                        method.load(evalArgs.getStrictMode());
-                        method.convert(Type.OBJECT);
                         method._goto(invoke_direct_eval);
 
                         method.label(is_not_eval);
@@ -1339,7 +1333,7 @@ final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContex
                         // This is some scope 'eval' or global eval replaced by user
                         // but not the built-in ECMAScript 'eval' function call
                         method.loadNull();
-                        argsCount = loadArgs(callArgs);
+                        argsCount = loadArgs(callNode.getArgs());
                     }
 
                     @Override
@@ -1349,6 +1343,11 @@ final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContex
                         method._goto(eval_done);
 
                         method.label(invoke_direct_eval);
+                        // Special/extra 'eval' arguments. These can be loaded late (in consumeStack) as we know none of
+                        // them can ever be optimistic.
+                        method.loadCompilerConstant(THIS);
+                        method.load(callNode.getEvalArgs().getLocation());
+                        method.load(CodeGenerator.this.lc.getCurrentFunction().isStrict());
                         // direct call to Global.directEval
                         globalDirectEval();
                         convertOptimisticReturnValue();
@@ -4438,7 +4437,7 @@ final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContex
 
     private MethodEmitter globalDirectEval() {
         return method.invokestatic(GLOBAL_OBJECT, "directEval",
-                methodDescriptor(Object.class, Object.class, Object.class, Object.class, Object.class, Object.class));
+                methodDescriptor(Object.class, Object.class, Object.class, Object.class, Object.class, boolean.class));
     }
 
     private abstract class OptimisticOperation {
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Lower.java b/nashorn/src/jdk/nashorn/internal/codegen/Lower.java
index 352270d05dd5697ae32d37ee41bb83b56aef7fe1..9f713e04dde6c9f81804087b78f532283f1c6c77 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/Lower.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/Lower.java
@@ -27,7 +27,6 @@ package jdk.nashorn.internal.codegen;
 
 import static jdk.nashorn.internal.codegen.CompilerConstants.EVAL;
 import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN;
-import static jdk.nashorn.internal.codegen.CompilerConstants.THIS;
 import static jdk.nashorn.internal.ir.Expression.isAlwaysTrue;
 
 import java.util.ArrayList;
@@ -603,13 +602,11 @@ final class Lower extends NodeOperatorVisitor<BlockLexicalContext> implements Lo
 
             // 'eval' call with at least one argument
             if (args.size() >= 1 && EVAL.symbolName().equals(callee.getName())) {
-                final FunctionNode currentFunction = lc.getCurrentFunction();
-                return callNode.setEvalArgs(
-                    new CallNode.EvalArgs(
-                        (Expression)ensureUniqueNamesIn(args.get(0)).accept(this),
-                        compilerConstant(THIS),
-                        evalLocation(callee),
-                        currentFunction.isStrict()));
+                final List<Expression> evalArgs = new ArrayList<>(args.size());
+                for(final Expression arg: args) {
+                    evalArgs.add((Expression)ensureUniqueNamesIn(arg).accept(this));
+                }
+                return callNode.setEvalArgs(new CallNode.EvalArgs(evalArgs, evalLocation(callee)));
             }
         }
 
diff --git a/nashorn/src/jdk/nashorn/internal/ir/CallNode.java b/nashorn/src/jdk/nashorn/internal/ir/CallNode.java
index d8bfd47adf3b4db7985424bf5754993e6fca03a5..0751ce4087d63d885a5324cd1ba5475fbf58103e 100644
--- a/nashorn/src/jdk/nashorn/internal/ir/CallNode.java
+++ b/nashorn/src/jdk/nashorn/internal/ir/CallNode.java
@@ -65,61 +65,35 @@ public final class CallNode extends LexicalContextExpression implements Optimist
      * Arguments to be passed to builtin {@code eval} function
      */
     public static class EvalArgs {
-        /** evaluated code */
-        private final Expression code;
-
-        /** 'this' passed to evaluated code */
-        private final IdentNode evalThis;
+        private final List<Expression> args;
 
         /** location string for the eval call */
         private final String location;
 
-        /** is this call from a strict context? */
-        private final boolean strictMode;
-
         /**
          * Constructor
          *
-         * @param code       code to evaluate
-         * @param evalThis   this node
-         * @param location   location for the eval call
-         * @param strictMode is this a call from a strict context?
+         * @param args     arguments to eval
+         * @param location location for the eval call
          */
-        public EvalArgs(final Expression code, final IdentNode evalThis, final String location, final boolean strictMode) {
-            this.code = code;
-            this.evalThis = evalThis;
+        public EvalArgs(final List<Expression> args, final String location) {
+            this.args = args;
             this.location = location;
-            this.strictMode = strictMode;
         }
 
         /**
          * Return the code that is to be eval:ed by this eval function
          * @return code as an AST node
          */
-        public Expression getCode() {
-            return code;
-        }
-
-        private EvalArgs setCode(final Expression code) {
-            if (this.code == code) {
-                return this;
-            }
-            return new EvalArgs(code, evalThis, location, strictMode);
-        }
-
-        /**
-         * Get the {@code this} symbol used to invoke this eval call
-         * @return the {@code this} symbol
-         */
-        public IdentNode getThis() {
-            return this.evalThis;
+        public List<Expression> getArgs() {
+            return Collections.unmodifiableList(args);
         }
 
-        private EvalArgs setThis(final IdentNode evalThis) {
-            if (this.evalThis == evalThis) {
+        private EvalArgs setArgs(final List<Expression> args) {
+            if (this.args == args) {
                 return this;
             }
-            return new EvalArgs(code, evalThis, location, strictMode);
+            return new EvalArgs(args, location);
         }
 
         /**
@@ -129,14 +103,6 @@ public final class CallNode extends LexicalContextExpression implements Optimist
         public String getLocation() {
             return this.location;
         }
-
-        /**
-         * Check whether this eval call is executed in strict mode
-         * @return true if executed in strict mode, false otherwise
-         */
-        public boolean getStrictMode() {
-            return this.strictMode;
-        }
     }
 
     /** arguments for 'eval' call. Non-null only if this call node is 'eval' */
@@ -212,8 +178,7 @@ public final class CallNode extends LexicalContextExpression implements Optimist
                     setArgs(Node.accept(visitor, Expression.class, args)).
                     setEvalArgs(evalArgs == null ?
                             null :
-                            evalArgs.setCode((Expression)evalArgs.getCode().accept(visitor)).
-                                setThis((IdentNode)evalArgs.getThis().accept(visitor))));
+                            evalArgs.setArgs(Node.accept(visitor, Expression.class, evalArgs.getArgs()))));
             // Theoretically, we'd need to instead pass lc to every setter and do a replacement on each. In practice,
             // setType from TypeOverride can't accept a lc, and we don't necessarily want to go there now.
             if (this != newCallNode) {
diff --git a/nashorn/src/jdk/nashorn/internal/objects/Global.java b/nashorn/src/jdk/nashorn/internal/objects/Global.java
index 4e2ba68a603a8a6b8dbe0068b166969369cb8fbb..5d28c1efd74bdd1296e8ff1a825a794767c85815 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/Global.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/Global.java
@@ -27,6 +27,7 @@ package jdk.nashorn.internal.objects;
 
 import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall;
 import static jdk.nashorn.internal.lookup.Lookup.MH;
+import static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
 
@@ -45,8 +46,11 @@ import java.util.Map;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicReference;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
 import jdk.internal.dynalink.linker.GuardedInvocation;
 import jdk.internal.dynalink.linker.LinkRequest;
+import jdk.nashorn.api.scripting.ScriptObjectMirror;
 import jdk.nashorn.internal.codegen.ApplySpecialization;
 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
 import jdk.nashorn.internal.lookup.Lookup;
@@ -107,6 +111,10 @@ public final class Global extends ScriptObject implements Scope {
     /** Name invalidator for things like call/apply */
     public static final Call BOOTSTRAP = staticCall(MethodHandles.lookup(), Global.class, "invalidateNameBootstrap", CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class);
 
+    /** Nashorn extension: arguments array */
+    @Property(attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_CONFIGURABLE)
+    public Object arguments;
+
     /** ECMA 15.1.2.2 parseInt (string , radix) */
     @Property(attributes = Attribute.NOT_ENUMERABLE)
     public Object parseInt;
@@ -411,12 +419,13 @@ public final class Global extends ScriptObject implements Scope {
     // Used to store the last RegExp result to support deprecated RegExp constructor properties
     private RegExpResult lastRegExpResult;
 
-    private static final MethodHandle EVAL              = findOwnMH_S("eval",              Object.class, Object.class, Object.class);
-    private static final MethodHandle PRINT             = findOwnMH_S("print",             Object.class, Object.class, Object[].class);
-    private static final MethodHandle PRINTLN           = findOwnMH_S("println",           Object.class, Object.class, Object[].class);
-    private static final MethodHandle LOAD              = findOwnMH_S("load",              Object.class, Object.class, Object.class);
-    private static final MethodHandle LOADWITHNEWGLOBAL = findOwnMH_S("loadWithNewGlobal", Object.class, Object.class, Object[].class);
-    private static final MethodHandle EXIT              = findOwnMH_S("exit",              Object.class, Object.class, Object.class);
+    private static final MethodHandle EVAL              = findOwnMH_S("eval",                Object.class, Object.class, Object.class);
+    private static final MethodHandle NO_SUCH_PROPERTY  = findOwnMH_S(NO_SUCH_PROPERTY_NAME, Object.class, Object.class, Object.class);
+    private static final MethodHandle PRINT             = findOwnMH_S("print",               Object.class, Object.class, Object[].class);
+    private static final MethodHandle PRINTLN           = findOwnMH_S("println",             Object.class, Object.class, Object[].class);
+    private static final MethodHandle LOAD              = findOwnMH_S("load",                Object.class, Object.class, Object.class);
+    private static final MethodHandle LOADWITHNEWGLOBAL = findOwnMH_S("loadWithNewGlobal",   Object.class, Object.class, Object[].class);
+    private static final MethodHandle EXIT              = findOwnMH_S("exit",                Object.class, Object.class, Object.class);
 
     /** Invalidate a reserved name, such as "apply" or "call" if assigned */
     public MethodHandle INVALIDATE_RESERVED_NAME = MH.bindTo(findOwnMH_V("invalidateReservedName", void.class, String.class), this);
@@ -427,6 +436,20 @@ public final class Global extends ScriptObject implements Scope {
     // context to which this global belongs to
     private final Context context;
 
+    // current ScriptContext to use - can be null.
+    private ScriptContext scontext;
+    // associated Property object for "context" property.
+    private jdk.nashorn.internal.runtime.Property scontextProperty;
+
+    /**
+     * Set the current script context
+     * @param scontext script context
+     */
+    public void setScriptContext(final ScriptContext scontext) {
+        this.scontext = scontext;
+        scontextProperty.setValue(this, this, scontext, false);
+    }
+
     // global constants for this global - they can be replaced with MethodHandle.constant until invalidated
     private static AtomicReference<GlobalConstants> gcsInstance = new AtomicReference<>();
 
@@ -447,12 +470,7 @@ public final class Global extends ScriptObject implements Scope {
         // null check on context
         context.getClass();
 
-        /*
-         * Duplicate global's map and use it. This way the initial Map filled
-         * by nasgen (referenced from static field in this class) is retained
-         * 'as is' (as that one is process wide singleton.
-         */
-        return $nasgenmap$.duplicate();
+        return $nasgenmap$;
     }
 
     /**
@@ -483,6 +501,10 @@ public final class Global extends ScriptObject implements Scope {
         return global;
     }
 
+    private static Global instanceFrom(final Object self) {
+        return self instanceof Global? (Global)self : instance();
+    }
+
     /**
      * Return the global constants map for fields that
      * can be accessed as MethodHandle.constant
@@ -542,13 +564,13 @@ public final class Global extends ScriptObject implements Scope {
      * as well as our extension builtin objects like "Java", "JSAdapter" as properties
      * of the global scope object.
      */
-    public void initBuiltinObjects() {
+    public void initBuiltinObjects(final ScriptEngine engine) {
         if (this.builtinObject != null) {
             // already initialized, just return
             return;
         }
 
-        init();
+        init(engine);
     }
 
     /**
@@ -848,6 +870,32 @@ public final class Global extends ScriptObject implements Scope {
         return getLazilyCreatedValue(key, creator, dynamicInvokers);
     }
 
+    /**
+     * Hook to search missing variables in ScriptContext if available
+     * @param self used to detect if scope call or not (this function is 'strict')
+     * @param name name of the variable missing
+     * @return value of the missing variable or undefined (or TypeError for scope search)
+     */
+    public static Object __noSuchProperty__(final Object self, final Object name) {
+        final Global global = Global.instance();
+        final ScriptContext sctxt = global.scontext;
+        final String nameStr = name.toString();
+
+        if (sctxt != null) {
+            final int scope = sctxt.getAttributesScope(nameStr);
+            if (scope != -1) {
+                return ScriptObjectMirror.unwrap(sctxt.getAttribute(nameStr, scope), global);
+            }
+        }
+
+        if (self == UNDEFINED) {
+            // scope access and so throw ReferenceError
+            throw referenceError(global, "not.defined", nameStr);
+        }
+
+        return UNDEFINED;
+    }
+
     /**
      * This is the eval used when 'indirect' eval call is made.
      *
@@ -860,7 +908,7 @@ public final class Global extends ScriptObject implements Scope {
      * @return the result of eval
      */
     public static Object eval(final Object self, final Object str) {
-        return directEval(self, str, UNDEFINED, UNDEFINED, UNDEFINED);
+        return directEval(self, str, UNDEFINED, UNDEFINED, false);
     }
 
     /**
@@ -876,14 +924,14 @@ public final class Global extends ScriptObject implements Scope {
      *
      * This is directly invoked from generated when eval(code) is called in user code
      */
-    public static Object directEval(final Object self, final Object str, final Object callThis, final Object location, final Object strict) {
+    public static Object directEval(final Object self, final Object str, final Object callThis, final Object location, final boolean strict) {
         if (!(str instanceof String || str instanceof ConsString)) {
             return str;
         }
-        final Global global = Global.instance();
+        final Global global = Global.instanceFrom(self);
         final ScriptObject scope = self instanceof ScriptObject ? (ScriptObject)self : global;
 
-        return global.getContext().eval(scope, str.toString(), callThis, location, Boolean.TRUE.equals(strict), true);
+        return global.getContext().eval(scope, str.toString(), callThis, location, strict, true);
     }
 
     /**
@@ -895,7 +943,7 @@ public final class Global extends ScriptObject implements Scope {
      * @return result of print (undefined)
      */
     public static Object print(final Object self, final Object... objects) {
-        return printImpl(false, objects);
+        return Global.instanceFrom(self).printImpl(false, objects);
     }
 
     /**
@@ -907,7 +955,7 @@ public final class Global extends ScriptObject implements Scope {
      * @return result of println (undefined)
      */
     public static Object println(final Object self, final Object... objects) {
-        return printImpl(true, objects);
+        return Global.instanceFrom(self).printImpl(true, objects);
     }
 
     /**
@@ -921,7 +969,7 @@ public final class Global extends ScriptObject implements Scope {
      * @throws IOException if source could not be read
      */
     public static Object load(final Object self, final Object source) throws IOException {
-        final Global global = Global.instance();
+        final Global global = Global.instanceFrom(self);
         final ScriptObject scope = self instanceof ScriptObject ? (ScriptObject)self : global;
         return global.getContext().load(scope, source);
     }
@@ -937,7 +985,7 @@ public final class Global extends ScriptObject implements Scope {
      * @throws IOException if source could not be read
      */
     public static Object loadWithNewGlobal(final Object self, final Object...args) throws IOException {
-        final Global global = Global.instance();
+        final Global global = Global.instanceFrom(self);
         final int length = args.length;
         final boolean hasArgs = 0 < length;
         final Object from = hasArgs ? args[0] : UNDEFINED;
@@ -1604,7 +1652,7 @@ public final class Global extends ScriptObject implements Scope {
         splitState = state;
     }
 
-    private void init() {
+    private void init(final ScriptEngine engine) {
         assert Context.getGlobal() == this : "this global is not set as current";
 
         final ScriptEnvironment env = getContext().getEnv();
@@ -1705,12 +1753,19 @@ public final class Global extends ScriptObject implements Scope {
         copyBuiltins();
 
         // expose script (command line) arguments as "arguments" property of global
-        final Object argumentsObject = wrapAsObject(env.getArguments().toArray());
-        final int    argumentsFlags  = Attribute.NOT_ENUMERABLE;
-        addOwnProperty("arguments", argumentsFlags, argumentsObject);
+        arguments = wrapAsObject(env.getArguments().toArray());
         if (env._scripting) {
             // synonym for "arguments" in scripting mode
-            addOwnProperty("$ARG", argumentsFlags, argumentsObject);
+            addOwnProperty("$ARG", Attribute.NOT_ENUMERABLE, arguments);
+        }
+
+        if (engine != null) {
+            final int NOT_ENUMERABLE_NOT_CONFIG = Attribute.NOT_ENUMERABLE | Attribute.NOT_CONFIGURABLE;
+            scontextProperty = addOwnProperty("context", NOT_ENUMERABLE_NOT_CONFIG, null);
+            addOwnProperty("engine", NOT_ENUMERABLE_NOT_CONFIG, engine);
+            // __noSuchProperty__ hook for ScriptContext search of missing variables
+            final ScriptFunction noSuchProp = ScriptFunctionImpl.makeStrictFunction(NO_SUCH_PROPERTY_NAME, NO_SUCH_PROPERTY);
+            addOwnProperty(NO_SUCH_PROPERTY_NAME, Attribute.NOT_ENUMERABLE, noSuchProp);
         }
     }
 
@@ -1878,8 +1933,8 @@ public final class Global extends ScriptObject implements Scope {
         this.addOwnProperty("Debug", Attribute.NOT_ENUMERABLE, initConstructor("Debug"));
     }
 
-    private static Object printImpl(final boolean newLine, final Object... objects) {
-        final PrintWriter out = Global.getEnv().getOut();
+    private Object printImpl(final boolean newLine, final Object... objects) {
+        final PrintWriter out = scontext != null? new PrintWriter(scontext.getWriter()) : getContext().getEnv().getOut();
         final StringBuilder sb = new StringBuilder();
 
         for (final Object object : objects) {
@@ -2023,12 +2078,11 @@ public final class Global extends ScriptObject implements Scope {
 
         for (final jdk.nashorn.internal.runtime.Property property : properties) {
             final Object key   = property.getKey();
-            final Object value = ObjectPrototype.get(key);
-
             if (key.equals("constructor")) {
                 continue;
             }
 
+            final Object value = ObjectPrototype.get(key);
             if (value instanceof ScriptFunction) {
                 final ScriptFunction func = (ScriptFunction)value;
                 final ScriptObject prototype = ScriptFunction.getPrototype(func);
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java b/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java
index 329750f7196534448be00be4a34e568277e42d8c..dc6ba044606d880de81d74ab9bee04303655c6e1 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDebug.java
@@ -222,7 +222,6 @@ public final class NativeDebug extends ScriptObject {
         out.println("ScriptFunction allocations " + ScriptFunction.getAllocations());
         out.println("PropertyMap count " + PropertyMap.getCount());
         out.println("PropertyMap cloned " + PropertyMap.getClonedCount());
-        out.println("PropertyMap duplicated " + PropertyMap.getDuplicatedCount());
         out.println("PropertyMap history hit " + PropertyMap.getHistoryHit());
         out.println("PropertyMap proto invalidations " + PropertyMap.getProtoInvalidations());
         out.println("PropertyMap proto history hit " + PropertyMap.getProtoHistoryHit());
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
index be0349afdab5decfb4c6ada0cca10c66ffa0fb4e..95de1bd8aa6ec7c46be72ab8eccdcb64f2a89118 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJava.java
@@ -36,6 +36,7 @@ import java.util.List;
 import jdk.internal.dynalink.beans.StaticClass;
 import jdk.internal.dynalink.support.TypeUtilities;
 import jdk.nashorn.api.scripting.JSObject;
+import jdk.nashorn.api.scripting.ScriptUtils;
 import jdk.nashorn.internal.objects.annotations.Attribute;
 import jdk.nashorn.internal.objects.annotations.Function;
 import jdk.nashorn.internal.objects.annotations.ScriptClass;
@@ -45,6 +46,7 @@ import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.ListAdapter;
 import jdk.nashorn.internal.runtime.PropertyMap;
 import jdk.nashorn.internal.runtime.ScriptObject;
+import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
 import jdk.nashorn.internal.runtime.linker.JavaAdapterFactory;
@@ -79,6 +81,73 @@ public final class NativeJava {
         return type instanceof StaticClass;
     }
 
+    /**
+     * Returns synchronized wrapper version of the given ECMAScript function.
+     * @param self not used
+     * @param func the ECMAScript function whose synchronized version is returned.
+     * @param obj the object (i.e, lock) on which the function synchronizes.
+     * @return synchronized wrapper version of the given ECMAScript function.
+     */
+    @Function(name="synchronized", attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
+    public static Object synchronizedFunc(final Object self, final Object func, final Object obj) {
+        return ScriptUtils.makeSynchronizedFunction(func, obj);
+    }
+
+    /**
+     * Returns true if the specified object is a Java method.
+     * @param self not used
+     * @param obj the object that is checked if it is a Java method object or not
+     * @return tells whether given object is a Java method object or not.
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
+    public static boolean isJavaMethod(final Object self, final Object obj) {
+        return Bootstrap.isDynamicMethod(obj);
+    }
+
+    /**
+     * Returns true if the specified object is a java function (but not script function)
+     * @param self not used
+     * @param obj the object that is checked if it is a Java function or not
+     * @return tells whether given object is a Java function or not
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
+    public static boolean isJavaFunction(final Object self, final Object obj) {
+        return Bootstrap.isCallable(obj) && !(obj instanceof ScriptFunction);
+    }
+
+    /**
+     * Returns true if the specified object is a Java object but not a script object
+     * @param self not used
+     * @param obj the object that is checked
+     * @return tells whether given object is a Java object but not a script object
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
+    public static boolean isJavaObject(final Object self, final Object obj) {
+        return obj != null && !(obj instanceof ScriptObject);
+    }
+
+    /**
+     * Returns true if the specified object is a ECMAScript object, that is an instance of {@link ScriptObject}.
+     * @param self not used
+     * @param obj the object that is checked if it is a ECMAScript object or not
+     * @return tells whether given object is a ECMAScript object or not.
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
+    public static boolean isScriptObject(final Object self, final Object obj) {
+        return obj instanceof ScriptObject;
+    }
+
+    /**
+     * Returns true if the specified object is a ECMAScript function, that is an instance of {@link ScriptFunction}.
+     * @param self not used
+     * @param obj the object that is checked if it is a ECMAScript function or not
+     * @return tells whether given object is a ECMAScript function or not.
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
+    public static boolean isScriptFunction(final Object self, final Object obj) {
+        return obj instanceof ScriptFunction;
+    }
+
     /**
      * <p>
      * Given a name of a Java type, returns an object representing that type in Nashorn. The Java class of the objects
diff --git a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
index c399a95589ab32b7f2f0b7207952000fac804a4e..a52051ca9676baa636b587b920477d981e0308c7 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
@@ -184,6 +184,15 @@ public class ScriptFunctionImpl extends ScriptFunction {
         return new AnonymousFunction();
     }
 
+    private static ScriptFunction makeFunction(final String name, final MethodHandle methodHandle, final MethodHandle[] specs, final int flags) {
+        final ScriptFunctionImpl func = new ScriptFunctionImpl(name, methodHandle, null, specs, flags);
+        func.setPrototype(UNDEFINED);
+        // Non-constructor built-in functions do not have "prototype" property
+        func.deleteOwnProperty(func.getMap().findProperty("prototype"));
+
+        return func;
+    }
+
     /**
      * Factory method for non-constructor built-in functions
      *
@@ -193,12 +202,18 @@ public class ScriptFunctionImpl extends ScriptFunction {
      * @return new ScriptFunction
      */
     static ScriptFunction makeFunction(final String name, final MethodHandle methodHandle, final MethodHandle[] specs) {
-        final ScriptFunctionImpl func = new ScriptFunctionImpl(name, methodHandle, null, specs, ScriptFunctionData.IS_BUILTIN);
-        func.setPrototype(UNDEFINED);
-        // Non-constructor built-in functions do not have "prototype" property
-        func.deleteOwnProperty(func.getMap().findProperty("prototype"));
+        return makeFunction(name, methodHandle, specs, ScriptFunctionData.IS_BUILTIN);
+    }
 
-        return func;
+    /**
+     * Factory method for non-constructor built-in, strict functions
+     *
+     * @param name   function name
+     * @param methodHandle handle for invocation
+     * @return new ScriptFunction
+     */
+    static ScriptFunction makeStrictFunction(final String name, final MethodHandle methodHandle) {
+        return makeFunction(name, methodHandle, null, ScriptFunctionData.IS_BUILTIN | ScriptFunctionData.IS_STRICT );
     }
 
     /**
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java
index a70f80d43d9294563a98426b5b2f6f45442e030b..0b98603d92ee643337b9db33870cdb4facdb330c 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java
@@ -62,6 +62,7 @@ import java.util.concurrent.atomic.AtomicLong;
 import java.util.function.Consumer;
 import java.util.function.Supplier;
 import java.util.logging.Level;
+import javax.script.ScriptEngine;
 import jdk.internal.org.objectweb.asm.ClassReader;
 import jdk.internal.org.objectweb.asm.util.CheckClassAdapter;
 import jdk.nashorn.api.scripting.ScriptObjectMirror;
@@ -954,16 +955,17 @@ public final class Context {
      * Initialize given global scope object.
      *
      * @param global the global
+     * @param engine the associated ScriptEngine instance, can be null
      * @return the initialized global scope object.
      */
-    public Global initGlobal(final Global global) {
+    public Global initGlobal(final Global global, final ScriptEngine engine) {
         // Need only minimal global object, if we are just compiling.
         if (!env._compile_only) {
             final Global oldGlobal = Context.getGlobal();
             try {
                 Context.setGlobal(global);
                 // initialize global scope with builtin global objects
-                global.initBuiltinObjects();
+                global.initBuiltinObjects(engine);
             } finally {
                 Context.setGlobal(oldGlobal);
             }
@@ -972,6 +974,16 @@ public final class Context {
         return global;
     }
 
+    /**
+     * Initialize given global scope object.
+     *
+     * @param global the global
+     * @return the initialized global scope object.
+     */
+    public Global initGlobal(final Global global) {
+        return initGlobal(global, null);
+    }
+
     /**
      * Return the current global's context
      * @return current global's context
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ECMAErrors.java b/nashorn/src/jdk/nashorn/internal/runtime/ECMAErrors.java
index 4160a356c003b50afb12eee0caca02492595e668..462028e886bf5af354cbba3ec83760bdceac5073 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/ECMAErrors.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ECMAErrors.java
@@ -405,12 +405,8 @@ public final class ECMAErrors {
         // Look for script package in class name (into which compiler puts generated code)
         if (className.startsWith(scriptPackage) && !CompilerConstants.isInternalMethodName(frame.getMethodName())) {
             final String source = frame.getFileName();
-            /*
-             * Make sure that it is not some Java code that Nashorn has in that package!
-             * also, we don't want to report JavaScript code that lives in script engine implementation
-             * We want to report only user's own scripts and not any of our own scripts like "engine.js"
-             */
-            return source != null && !source.endsWith(".java") && !source.contains(NashornException.ENGINE_SCRIPT_SOURCE_NAME);
+            // Make sure that it is not some Java code that Nashorn has in that package!
+            return source != null && !source.endsWith(".java");
         }
         return false;
     }
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java
index 9641f5222725b513e73eb984fbcdcb7e81fc2931..620ffa7dba71f1724c42bb95000ee03f6a53c3d8 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java
@@ -145,21 +145,6 @@ public final class PropertyMap implements Iterable<Object>, Serializable {
         this(propertyMap, propertyMap.properties);
     }
 
-    /**
-     * Duplicates this PropertyMap instance. This is used to duplicate 'shared'
-     * maps {@link PropertyMap} used as process wide singletons. Shared maps are
-     * duplicated for every global scope object. That way listeners, proto and property
-     * histories are scoped within a global scope.
-     *
-     * @return Duplicated {@link PropertyMap}.
-     */
-    public PropertyMap duplicate() {
-        if (Context.DEBUG) {
-            duplicatedCount++;
-        }
-        return new PropertyMap(this.properties, this.className, 0, 0, 0, containsArrayKeys());
-    }
-
     private void writeObject(final ObjectOutputStream out) throws IOException {
         out.defaultWriteObject();
         out.writeObject(properties.getProperties());
@@ -968,7 +953,6 @@ public final class PropertyMap implements Iterable<Object>, Serializable {
     // counters updated only in debug mode
     private static int count;
     private static int clonedCount;
-    private static int duplicatedCount;
     private static int historyHit;
     private static int protoInvalidations;
     private static int protoHistoryHit;
@@ -988,13 +972,6 @@ public final class PropertyMap implements Iterable<Object>, Serializable {
         return clonedCount;
     }
 
-    /**
-     * @return The number of maps that are duplicated.
-     */
-    public static int getDuplicatedCount() {
-        return duplicatedCount;
-    }
-
     /**
      * @return The number of times history was successfully used.
      */
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java
index 1987d31710083e6262078ad6e70ac093bff68776..4f36eb55e38b42d1206a079d907a52fc4d1fddbe 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java
@@ -103,10 +103,10 @@ public abstract class ScriptObject implements PropertyAccess {
     public static final String PROTO_PROPERTY_NAME   = "__proto__";
 
     /** Search fall back routine name for "no such method" */
-    static final String NO_SUCH_METHOD_NAME   = "__noSuchMethod__";
+    public static final String NO_SUCH_METHOD_NAME   = "__noSuchMethod__";
 
     /** Search fall back routine name for "no such property" */
-    static final String NO_SUCH_PROPERTY_NAME = "__noSuchProperty__";
+    public static final String NO_SUCH_PROPERTY_NAME = "__noSuchProperty__";
 
     /** Per ScriptObject flag - is this a scope object? */
     public static final int IS_SCOPE       = 1 << 0;
@@ -160,7 +160,8 @@ public abstract class ScriptObject implements PropertyAccess {
     static final MethodHandle GLOBALFILTER       = findOwnMH_S("globalFilter", Object.class, Object.class);
 
     private static final MethodHandle TRUNCATINGFILTER   = findOwnMH_S("truncatingFilter", Object[].class, int.class, Object[].class);
-    private static final MethodHandle KNOWNFUNCPROPGUARD = findOwnMH_S("knownFunctionPropertyGuard", boolean.class, Object.class, PropertyMap.class, MethodHandle.class, Object.class, ScriptFunction.class);
+    private static final MethodHandle KNOWNFUNCPROPGUARDSELF = findOwnMH_S("knownFunctionPropertyGuardSelf", boolean.class, Object.class, PropertyMap.class, MethodHandle.class, ScriptFunction.class);
+    private static final MethodHandle KNOWNFUNCPROPGUARDPROTO = findOwnMH_S("knownFunctionPropertyGuardProto", boolean.class, Object.class, PropertyMap.class, MethodHandle.class, int.class, ScriptFunction.class);
 
     private static final ArrayList<MethodHandle> PROTO_FILTERS = new ArrayList<>();
 
@@ -2271,13 +2272,20 @@ public abstract class ScriptObject implements PropertyAccess {
                 if (scopeAccess && func.isStrict()) {
                     mh = bindTo(mh, UNDEFINED);
                 }
+
                 return new GuardedInvocation(
                         mh,
-                        //TODO this always does a scriptobject check
-                        getKnownFunctionPropertyGuard(
+                        find.isSelf()?
+                            getKnownFunctionPropertyGuardSelf(
+                                getMap(),
+                                find.getGetter(Object.class, INVALID_PROGRAM_POINT),
+                                func)
+                            :
+                            //TODO this always does a scriptobject check
+                            getKnownFunctionPropertyGuardProto(
                                 getMap(),
                                 find.getGetter(Object.class, INVALID_PROGRAM_POINT),
-                                find.getOwner(),
+                                find.getProtoChainLength(),
                                 func),
                         getProtoSwitchPoint(NO_SUCH_PROPERTY_NAME, find.getOwner()),
                         //TODO this doesn't need a ClassCastException as guard always checks script object
@@ -3595,15 +3603,51 @@ public abstract class ScriptObject implements PropertyAccess {
         return MH.findStatic(MethodHandles.lookup(), ScriptObject.class, name, MH.type(rtype, types));
     }
 
-    private static MethodHandle getKnownFunctionPropertyGuard(final PropertyMap map, final MethodHandle getter, final Object where, final ScriptFunction func) {
-        return MH.insertArguments(KNOWNFUNCPROPGUARD, 1, map, getter, where, func);
+    private static MethodHandle getKnownFunctionPropertyGuardSelf(final PropertyMap map, final MethodHandle getter, final ScriptFunction func) {
+        return MH.insertArguments(KNOWNFUNCPROPGUARDSELF, 1, map, getter, func);
     }
 
     @SuppressWarnings("unused")
-    private static boolean knownFunctionPropertyGuard(final Object self, final PropertyMap map, final MethodHandle getter, final Object where, final ScriptFunction func) {
+    private static boolean knownFunctionPropertyGuardSelf(final Object self, final PropertyMap map, final MethodHandle getter, final ScriptFunction func) {
         if (self instanceof ScriptObject && ((ScriptObject)self).getMap() == map) {
             try {
-                return getter.invokeExact(where) == func;
+                return getter.invokeExact(self) == func;
+            } catch (final RuntimeException | Error e) {
+                throw e;
+            } catch (final Throwable t) {
+                throw new RuntimeException(t);
+            }
+        }
+
+        return false;
+    }
+
+    private static MethodHandle getKnownFunctionPropertyGuardProto(final PropertyMap map, final MethodHandle getter, final int depth, final ScriptFunction func) {
+        return MH.insertArguments(KNOWNFUNCPROPGUARDPROTO, 1, map, getter, depth, func);
+    }
+
+    @SuppressWarnings("unused")
+    private static ScriptObject getProto(final ScriptObject self, final int depth) {
+        ScriptObject proto = self;
+        for (int d = 0; d < depth; d++) {
+            proto = proto.getProto();
+            if (proto == null) {
+                return null;
+            }
+        }
+
+        return proto;
+    }
+
+    @SuppressWarnings("unused")
+    private static boolean knownFunctionPropertyGuardProto(final Object self, final PropertyMap map, final MethodHandle getter, final int depth, final ScriptFunction func) {
+        if (self instanceof ScriptObject && ((ScriptObject)self).getMap() == map) {
+            final ScriptObject proto = getProto((ScriptObject)self, depth);
+            if (proto == null) {
+                return false;
+            }
+            try {
+                return getter.invokeExact((Object)proto) == func;
             } catch (final RuntimeException | Error e) {
                 throw e;
             } catch (final Throwable t) {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/BoundDynamicMethod.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/BoundDynamicMethod.java
index f2089d5a2ba7ca412ec552765df051841476752c..9008547fa885b03bf156742ef98b769053aa1fd3 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/BoundDynamicMethod.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/BoundDynamicMethod.java
@@ -25,6 +25,7 @@
 
 package jdk.nashorn.internal.runtime.linker;
 
+import java.util.Objects;
 import jdk.internal.dynalink.beans.BeansLinker;
 
 /**
@@ -48,4 +49,9 @@ final class BoundDynamicMethod {
     Object getBoundThis() {
         return boundThis;
     }
+
+    @Override
+    public String toString() {
+        return dynamicMethod.toString() + " on " + Objects.toString(boundThis);
+    }
 }
diff --git a/nashorn/test/script/basic/JDK-8047057.js b/nashorn/test/script/basic/JDK-8047057.js
index f13e36e49412790ac58c49c2ff8bb6fe7a4f1e22..bd38ee901e3bcadc67e9309b8e25e1052bdce50f 100644
--- a/nashorn/test/script/basic/JDK-8047057.js
+++ b/nashorn/test/script/basic/JDK-8047057.js
@@ -49,7 +49,7 @@ makeFuncAndCall("switch(0) { default: {break;} return }");
 makeFuncAndCall("L: { { break L; } return; }");
 makeFuncAndCall("L: { while(0) break L; return; }");
 makeFuncExpectError("L: {while(0) break L; return [](); }", TypeError);
-// makeFuncAndCall("do with({}) break ; while(0);");
+makeFuncAndCall("do with({}) break ; while(0);");
 makeFuncAndCall("while(0) with({}) continue ;");
 makeFuncAndCall("eval([]);");
 makeFuncAndCall("try{} finally{[]}");
@@ -59,10 +59,10 @@ makeFuncAndCall("Error() * (false)[-0]--");
 makeFuncAndCall("try { var x = 1, x = null; } finally { }");
 makeFuncAndCall("try { var x = {}, x = []; } catch(x3) { }");
 makeFuncAndCall("[delete this]");
-// makeFuncAndCall("if(eval('', eval('', function() {}))) { }");
-// makeFuncAndCall("if(eval('', eval('', function() {}))) { }");
-// makeFuncAndCall("eval(\"[,,];\", [11,12,13,14].some)");
-// makeFuncAndCall("eval(\"1.2e3\", ({})[ /x/ ])");
+makeFuncAndCall("if(eval('', eval('', function() {}))) { }");
+makeFuncAndCall("if(eval('', eval('', function() {}))) { }");
+makeFuncAndCall("eval(\"[,,];\", [11,12,13,14].some)");
+makeFuncAndCall("eval(\"1.2e3\", ({})[ /x/ ])");
 makeFuncExpectError("eval(\"x4\", x3);", ReferenceError);
 makeFuncAndCall("with({5.0000000000000000000000: String()}){(false); }");
 makeFuncAndCall("try { var x = undefined, x = 5.0000000000000000000000; } catch(x) { x = undefined; }");
@@ -72,4 +72,4 @@ makeFuncAndCall("(false % !this) && 0");
 makeFuncAndCall("with({8: 'fafafa'.replace()}){ }");
 makeFuncAndCall("(function (x) '' )(true)");
 makeFuncExpectError("new eval(function(){})", TypeError);
-//** makeFuncAndCall('eval("23", ({})[/x/])');
+makeFuncAndCall('eval("23", ({})[/x/])');
diff --git a/hotspot/src/cpu/ppc/vm/bytecodes_ppc.hpp b/nashorn/test/script/basic/JDK-8047067.js
similarity index 66%
rename from hotspot/src/cpu/ppc/vm/bytecodes_ppc.hpp
rename to nashorn/test/script/basic/JDK-8047067.js
index 35fc51147a74213be58f5400b1ef09b878b47422..2b68611290c0536b9a3af364ca3b96ad35ca758b 100644
--- a/hotspot/src/cpu/ppc/vm/bytecodes_ppc.hpp
+++ b/nashorn/test/script/basic/JDK-8047067.js
@@ -1,31 +1,36 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright (c) 2010, 2014, 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 CPU_PPC_VM_BYTECODES_PPC_HPP
-#define CPU_PPC_VM_BYTECODES_PPC_HPP
-
-// No ppc64 specific bytecodes
+/**
+ * JDK-8047067: all eval arguments need to be copied in Lower
+ *
+ * @test
+ * @run
+ */
 
-#endif // CPU_PPC_VM_BYTECODES_PPC_HPP
+// The second expression triggers optimistic deoptimization, and if not
+// all eval arguments were copied in Lower, we'd end up with duplicate
+// program points that'd cause incorrect continuation program point in
+// the rest-of, and therefore a bad stack, and therefore an AIOOBE in
+// the continuation setup code.
+eval("23", ({})[/x/]) 
diff --git a/nashorn/test/script/basic/JDK-8049086.js b/nashorn/test/script/basic/JDK-8049086.js
new file mode 100644
index 0000000000000000000000000000000000000000..2fae31b5324c94a48194bdbc84a6c7acb86837f8
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8049086.js
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+/**
+ * JDK-8049086: Minor API convenience functions on "Java" object
+ *
+ * @test
+ * @run
+ */
+
+var System = Java.type("java.lang.System");
+var out = System.out;
+var println = out.println;
+var getProperty = System.getProperty;
+var File = Java.type("java.io.File")["(String)"];
+
+print("println is java method? " + Java.isJavaMethod(println));
+print("println is script function? " + Java.isScriptFunction(println));
+print("getProperty is java method? " + Java.isJavaMethod(getProperty));
+print("getProperty is script function? " + Java.isScriptFunction(getProperty));
+print("File is java method? " + Java.isJavaMethod(File));
+print("File is script function? " + Java.isScriptFunction(File));
+
+print("eval is script function? " + Java.isScriptFunction(eval));
+print("eval is java method? " + Java.isJavaMethod(eval));
+function hello() {}
+print("hello is script function? " + Java.isScriptFunction(hello));
+print("hello is java method? " + Java.isJavaMethod(hello));
+
+print("out is script object? " + Java.isScriptObject(out));
+print("System is script object? " + Java.isScriptObject(System));
+print("Object is script object? " + Java.isScriptObject(Object));
+print("{} is script object? " + Java.isScriptObject({}));
+print("/foo/ is script object? " + Java.isScriptObject(/foo/));
+
+// Java function is anything whose 'typeof' is 'function' but it is not
+// a script function! This includes:
+// (a) Java methods (b) Java classes (as these respond to new)
+// (c) FunctionalInterface objects (d) JSObjects that are 'functions'
+
+print("java.awt.Color is java function? " + Java.isJavaFunction(java.awt.Color));
+print("java.lang.Runnable instance is java function? " 
+    + Java.isJavaFunction(new java.lang.Runnable(function() {})));
+print("eval is java function? " + Java.isJavaFunction(eval));
+print("println is java function? " + Java.isJavaFunction(println));
+print("getProperty is java function? " + Java.isJavaFunction(getProperty));
+
+var JSObject = Java.type("jdk.nashorn.api.scripting.JSObject");
+print("callable JSObject is function? " +
+    Java.isJavaFunction(new JSObject() {
+        isFunction: function() true,
+        call: function() {}
+    })
+);
+
+print("Non callable JSObject is function? " +
+    Java.isJavaFunction(new JSObject() {
+        isFunction: function() false,
+    })
+);
+
+// synchronized function
+var lock = new java.lang.Object();
+
+print("lock is java object? " + Java.isJavaObject(lock));
+print("eval is java object? " + Java.isJavaObject(eval));
+print("{} is java object? " + Java.isJavaObject({}));
+print("/foo/ is java object? " + Java.isJavaObject(/foo/));
+print("[] is java object? " + Java.isJavaObject([]));
+print("java.io.File is java object? " + Java.isJavaObject(java.io.File));
+
+// synchornized function checks
+Java.synchronized(function() {
+    var th = new java.lang.Thread(Java.synchronized(function() {
+        print("new thread");
+        print("notifying..");
+        lock.notifyAll();
+    }, lock));
+    th.start();
+    print("about to wait..");
+    lock.wait();
+    th.join();
+    print("done waiting!");
+}, lock)();
+
+// try Mozilla "sync" as well
+load("nashorn:mozilla_compat.js");
+sync(function() {
+    var th = new java.lang.Thread(sync(function() {
+        print("new thread");
+        print("notifying..");
+        lock.notifyAll();
+    }, lock));
+    th.start();
+    print("about to wait..");
+    lock.wait();
+    th.join();
+    print("done waiting!");
+}, lock)();
+
+function expectTypeError(func) {
+    try {
+        func();
+        throw new Error("should have thrown TypeError");
+    } catch (e) {
+        if (! (e instanceof TypeError)) {
+            fail("Expected TypeError, got " +e);
+        }
+        print(e);
+    }
+}
+
+expectTypeError(function() Java.synchronized(232));
+expectTypeError(function() sync(232));
+expectTypeError(function() Java.synchronized({}));
+expectTypeError(function() sync({}));
+expectTypeError(function() Java.synchronized([]));
+expectTypeError(function() sync([]));
+expectTypeError(function() Java.synchronized("hello"));
+expectTypeError(function() sync("hello"));
+expectTypeError(function() Java.synchronized(null));
+expectTypeError(function() sync(null));
+expectTypeError(function() Java.synchronized(undefined));
+expectTypeError(function() sync(undefined));
diff --git a/nashorn/test/script/basic/JDK-8049086.js.EXPECTED b/nashorn/test/script/basic/JDK-8049086.js.EXPECTED
new file mode 100644
index 0000000000000000000000000000000000000000..d67db5da2663c2314ffef8e81477ccd8a8755eaa
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8049086.js.EXPECTED
@@ -0,0 +1,48 @@
+println is java method? true
+println is script function? false
+getProperty is java method? true
+getProperty is script function? false
+File is java method? true
+File is script function? false
+eval is script function? true
+eval is java method? false
+hello is script function? true
+hello is java method? false
+out is script object? false
+System is script object? false
+Object is script object? true
+{} is script object? true
+/foo/ is script object? true
+java.awt.Color is java function? true
+java.lang.Runnable instance is java function? true
+eval is java function? false
+println is java function? true
+getProperty is java function? true
+callable JSObject is function? true
+Non callable JSObject is function? false
+lock is java object? true
+eval is java object? false
+{} is java object? false
+/foo/ is java object? false
+[] is java object? false
+java.io.File is java object? true
+about to wait..
+new thread
+notifying..
+done waiting!
+about to wait..
+new thread
+notifying..
+done waiting!
+TypeError: 232 is not a function
+TypeError: 232 is not a function
+TypeError: [object Object] is not a function
+TypeError: [object Object] is not a function
+TypeError: [object Array] is not a function
+TypeError: [object Array] is not a function
+TypeError: hello is not a function
+TypeError: hello is not a function
+TypeError: null is not a function
+TypeError: null is not a function
+TypeError: undefined is not a function
+TypeError: undefined is not a function
diff --git a/nashorn/test/src/jdk/nashorn/internal/runtime/CodeStoreAndPathTest.java b/nashorn/test/src/jdk/nashorn/internal/runtime/CodeStoreAndPathTest.java
index b7999dfc4dee6fcf20c9b170bf05f5edfefabbec..b4463a090050b22daec3f390c2cb5bbb4a2d9f3e 100644
--- a/nashorn/test/src/jdk/nashorn/internal/runtime/CodeStoreAndPathTest.java
+++ b/nashorn/test/src/jdk/nashorn/internal/runtime/CodeStoreAndPathTest.java
@@ -136,8 +136,7 @@ public class CodeStoreAndPathTest {
             // Check that a new compiled script is stored in existing code cache
             e.eval(code1);
             final DirectoryStream<Path> stream = Files.newDirectoryStream(codeCachePath);
-            // Already one compiled script has been stored in the cache during initialization
-            checkCompiledScripts(stream, 2);
+            checkCompiledScripts(stream, 1);
             // Setting to default current working dir
         } finally {
             System.setProperty("user.dir", oldUserDir);
@@ -154,9 +153,8 @@ public class CodeStoreAndPathTest {
         e.eval(code1);
         e.eval(code2);
         e.eval(code3);// less than minimum size for storing
-        // Already one compiled script has been stored in the cache during initialization
         // adding code1 and code2.
         final DirectoryStream<Path> stream = Files.newDirectoryStream(codeCachePath);
-        checkCompiledScripts(stream, 3);
+        checkCompiledScripts(stream, 2);
     }
 }