Merge
diff --git a/.hgtags b/.hgtags
index d71db3f..3d3aca8 100644
--- a/.hgtags
+++ b/.hgtags
@@ -1,3 +1,73 @@
+da5736e2722fee1336dfb69a0f03de060bde0ee1 jdk8u151-b08
+f942aac3c779302dc1f30ef74d57758e075df800 jdk8u151-b07
+f155de194467531ebe3ebf173418174d406fcfc6 jdk8u151-b06
+2401707998d06bf826658178b5df3c2d82f73cf3 jdk8u151-b05
+21bddd52ddb11639963c179e070253266b94e8c6 jdk8u151-b04
+3b7c730afe0f134ebcc781d86adda9cd655fdc00 jdk8u161-b00
+60cf90ade4856f9d35473321b55439bb204acdcf jdk8u151-b01
+54c3b3e54098761308caa28818391163768f55b8 jdk8u151-b02
+d871b591be14810d5bcbc8d27581c217c7eaa84b jdk8u151-b03
+1721377b270960d73f0cccce4b412db17b36b8e0 jdk8u141-b00
+a1ad1dbffd0b01b9900e48405a491e70b5e58d38 jdk8u131-b01
+98f347a6ac28d2b288319d7c72d7b5bca2e38439 jdk8u131-b02
+c71548e1ccff0813404d6f864a961d078c895c6e jdk8u131-b03
+5cf5a05e3c7c11db7568b65259e783e7e75986d1 jdk8u131-b04
+6f290d3b4a50d535f6758697c782cd2b9bebf802 jdk8u131-b05
+91b4735c1e7c4e6cd69422233b07b4ba91476625 jdk8u131-b06
+d84dd60eb37bba22201a7d2c3ef6245e80210875 jdk8u131-b07
+db7050bfc6f1e32c58322eb974575868dda9fa9b jdk8u131-b08
+086295963c6795cf1f87b0a1ae5132d2df1f9925 jdk8u131-b09
+27348d4f07a9fd2ee700054dc37bb352ea7ee967 jdk8u131-b10
+5429c38d9b62b745370bb4012be8edb99dca1284 jdk8u131-b11
+cfa59dbee3fd01ea829114074bcba800417850bd jdk8u112-b31
+cfdead3b29eec58ca0e0f3a41256ce08b6d30f82 jdk8u102-b34
+647493df603512a5c15864503acce3df36e0e9f1 jdk8u102-b35
+7df80f389babf722197a61844c0865df3e6ecf0b jdk8u102-b32
+981a32f2b638773a933a1bcf85ffb1dbec8817bc jdk8u102-b33
+ac3b63962fa1047596f51baf19bc6dcd71ba4dca jdk8u121-b01
+2d0862dd8ac7f7a595cbb82256a309bdaca3f50f jdk8u121-b02
+107bc0d8b594135b825229d1f6c86082deab22aa jdk8u121-b03
+a4f2db1641316cd709a04549e2027c480927275a jdk8u121-b04
+6ed6629394c23407cfb179a87dca9e21eea5d552 jdk8u131-b00
+03a4ea65733fd8a88e94d0ebb6e326077d865304 jdk8u121-b05
+b05ec2c59cb37a481dcbda316d41047e7a117658 jdk8u121-b06
+5516f058d5d36b671a032deb900ac84fe2437bf2 jdk8u121-b07
+f45c8969e38ce9f1d7fd80643a9574c584cbf169 jdk8u121-b08
+5710638769b15e2cfafa8e34d12a51207f2d7146 jdk8u121-b09
+160d0cc5f1fc14709ca225ddae01043fbbb5ed27 jdk8u121-b10
+ce33aacefa79e299ea28848b89a78973c2cfe6e5 jdk8u121-b11
+f05b4900af0e98d43ca21fb8145ab3189a10ccaa jdk8u121-b12
+aaa961d4510bb91c7797359aa6a3af59d311e57f jdk8u121-b13
+9883502d14ab9ac2b146be9409a0f268e18c54f5 jdk8u111-b14
+b792fddb75637e5e6afbd95faa28954c4cbc1800 jdk8u111-b12
+2400d4bac056f0a50c9c2c25b29471b12a507a3c jdk8u111-b13
+60779b2f8705ad721d641075c77d026910514ecc jdk8u111-b10
+b8452186ce8dd7571c5bf022ca72e2575eee9289 jdk8u111-b11
+8b20e51a0b4709c96e901c26ecf19054a5736d87 jdk8u111-b09
+4c22c1e9154583e7c696ef73b049ffcfdfe7ca4d jdk8u111-b08
+ddbba33294a0ba2cfa6d7344858324c7e80f6d1e jdk8u111-b07
+a7f55c3506ec8927f498d427c4cff476e34d8bcd jdk8u92-b32
+0b14732c52bfdbb220b97969a9889a7575eaee1b jdk8u92-b33
+f130ddae68457255a580d6ce54649f7caeefd0d8 jdk8u92-b34
+4742913d7cbeef450a65c688c60842446b82223d jdk8u102-b31
+21cd5d898356e2d937dd5be38a01e585ca26bba6 jdk8u111-b01
+c20e91e8f3d8c13a5e50af3f6bf7a16064066857 jdk8u111-b02
+dc44c4152a25fba2dab8fb665a0cf3eecdb180f7 jdk8u111-b03
+31d6aa39e19c5dd61a11cea9601fce8c3d151ea4 jdk8u111-b04
+68f5780c42b786792b9e1da77b70b7b057dd561f jdk8u121-b00
+1262587f060d47a1b7a3b614be7740e5516e6bc6 jdk8u111-b05
+6596927f21616acac574e353164a9930320e4ee7 jdk8u111-b06
+698a72044b8358e518d8f93f7fefba7f63689c46 jdk8u112-b06
+792a64b9ef3e473181843cdc8b565958a8c8b50a jdk8u112-b07
+71f39f9abe748b7434ab7a772afc19483d0043de jdk8u112-b08
+b8b28e0fa2a04865be7fb3cbe839af5a746d1cf2 jdk8u112-b09
+8b6622c212cbbe9afcf8a2bc96565f8aa88973aa jdk8u112-b10
+7384404de375ec8fbaca712671e977685fb83ea9 jdk8u112-b11
+48477bbf5da57e64f1558bbda44928b5daae5bbe jdk8u112-b12
+3e1d45c06a9dfaa165ac2c30e9c55ebb3cfa0f17 jdk8u112-b13
+b096d13f8c6ef35d109f8e2efe6424e6b31eb001 jdk8u112-b14
+3b46f90599fea8bad5e7c9e5f5fdbb634388c402 jdk8u112-b15
+1a3ecd8435fc30eebd2503eb16730e067cfa51fe jdk8u112-b16
 d06710c4acec884855c6bea19cb1ce80888c5a84 jdk8u102-b14
 0fce54d8ba98e3d64fb808a67c335da7bddde726 jdk8u102-b04
 97cdf82a2b16ba8ee77f5f40ab9d9ae90cd98a9e jdk8u112-b00
@@ -611,4 +681,19 @@
 bc2b59e8aabe5be743241e0f970f32935db7e258 jdk8u102-b13
 9f52dcc16dac8ab6347ad2ff9ec37dcd8ba98bdc jdk8u112-b03
 8becc9de1b6c0e027bc585607f333a64182c9740 jdk8u112-b04
-da5736e2722fee1336dfb69a0f03de060bde0ee1 jdk8u151-b08
+0e2f80bf92dcdcd9450c3677acd7ba81d7b27ddc jdk8u122-b00
+f09ce43caf23aa16f04566ce00fb794859cfd9dc jdk8u122-b01
+3a093f082be2c269b5d1d6e6da6c1f14b3909985 jdk8u122-b02
+402fb87e82ed2ea0ebd523471158a66e21686abe jdk8u122-b03
+88a6196b3f1a19f108b730059bd4ff3591aa1eca jdk8u122-b04
+80645cd4632a1f8a0a0dbb2d519a1f8bbff43b64 jdk8u132-b00
+23b1fd4a0fd4bb91092f4495365fc168e50be77b jdk8u152-b00
+adff1b83f0e41ce4d1d7275d747679ec61bd031d jdk8u152-b01
+5947bd7783e9c3b8986409ca3de05a5003525bff jdk8u152-b02
+c83e434ff56c94d0cc59ff97d6fccbcfe296fd85 jdk8u152-b03
+5d31a1e85b9a57b0cb32247f4ba4216a94107d8b jdk8u152-b04
+304500c3ea78b9aec8fac50c9eb15cf9e45fa1d1 jdk8u152-b06
+6cef99435f23c36ba392ed8e8989b8dbd726cce2 jdk8u152-b07
+713ab0ac5d8285dd0a8c7bc35823630557668125 jdk8u152-b08
+bcaa988dc25c9fdc94c472988adee25b6df81b48 jdk8u152-b09
+81c509532cb5fc3044b4c01d5a705c9fc96ec098 jdk8u152-b10
diff --git a/.hgtags-top-repo b/.hgtags-top-repo
index d716157..c59c38b 100644
--- a/.hgtags-top-repo
+++ b/.hgtags-top-repo
@@ -718,3 +718,25 @@
 6d4ab2046f26035e500924bffb49934d66aa64e3 jdk8u151-b05
 2edf82f6996ed27adb82dec2e3ce880134a98cc6 jdk8u151-b06
 9f271942852d8bc7de6c282307ffec3c92518f7d jdk8u151-b07
+1be5e74bfdf0c42ef5746b63b39a8ac139a063f7 jdk8u151-b08
+b94f31b809debc683b996146ac20acbb269381f9 jdk8u122-b00
+73494e6ff8e5a5a66cb87445d6c5a0a8acab3409 jdk8u122-b01
+89062b8ff53bfc62689c52373f5564369cd61609 jdk8u122-b02
+4cf57a6813323a1c3336bef63ca7c16d52146637 jdk8u122-b03
+4cf57a6813323a1c3336bef63ca7c16d52146637 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+b6e27dc2775764b59755eb054c66fbec9b2684b7 jdk8u122-b03
+6dd80b19838ded52371aa280cb8a68ad80aed22d jdk8u122-b04
+1e501e6d58a962a1ef5dd933dc4cce56a5358a98 jdk8u132-b00
+d15b51f1149bd1b7e87f4ec6a1bc5678c15275ef jdk8u152-b00
+b6446826930c8577c7a90009dd472b7eb813e495 jdk8u152-b01
+d7045c4d4eab5eb23ed9e43a351ff1a497ba7a7e jdk8u152-b02
+0414b34a471e1c3d277a5b0e583c6bfd9708305c jdk8u152-b03
+ea8d7d26cccae878ffed38eaa3f3c49d74c891fd jdk8u152-b04
+c23b7c1c24bf06ffa1bd52f19d541a56cdb1b350 jdk8u152-b05
+ff59566476c79e8143bf18eefb79196cc3a12994 jdk8u152-b06
+c0a2f84796bc8a55bb686069114de60a7cc2c875 jdk8u152-b07
+8f1aee9f3d074e074b74fdd4c63d21c554295443 jdk8u152-b08
+88df79df1243571bbce3a8d4935ff7f25b9ade78 jdk8u152-b09
+336862c1e889840a37fe3b07eae2cd328382782d jdk8u152-b10
diff --git a/ASSEMBLY_EXCEPTION b/ASSEMBLY_EXCEPTION
index 8b7ac1d..065b8d9 100644
--- a/ASSEMBLY_EXCEPTION
+++ b/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Sun at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Sun gives you permission to link this
-    OpenJDK Code with certain code licensed by Sun as indicated at
+    As a special exception, Oracle gives you permission to link this
+    OpenJDK Code with certain code licensed by Oracle as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Sun.
+    governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Sun
-could not provide under GPL2 (or that Sun has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh
index f6e9aec..280b92c 100644
--- a/common/autoconf/generated-configure.sh
+++ b/common/autoconf/generated-configure.sh
@@ -679,6 +679,9 @@
 CFLAGS_JDKLIB
 MACOSX_VERSION_MIN
 PACKAGE_PATH
+NO_LIFETIME_DSE_CFLAG
+NO_DELETE_NULL_POINTER_CHECKS_CFLAG
+CXXSTD_CXXFLAG
 LEGACY_EXTRA_LDFLAGS
 LEGACY_EXTRA_CXXFLAGS
 LEGACY_EXTRA_CFLAGS
@@ -743,6 +746,8 @@
 ac_ct_OBJC
 OBJCFLAGS
 OBJC
+CXX_VERSION
+CC_VERSION
 ac_ct_CXX
 CXXFLAGS
 CXX
@@ -3795,6 +3800,19 @@
 # questions.
 #
 
+# Prepare the system so that TOOLCHAIN_CHECK_COMPILER_VERSION can be called.
+# Must have CC_VERSION_NUMBER and CXX_VERSION_NUMBER.
+
+
+# Check if the configured compiler (C and C++) is of a specific version or
+# newer. TOOLCHAIN_PREPARE_FOR_VERSION_COMPARISONS must have been called before.
+#
+# Arguments:
+#   $1:   The version string to check against the found version
+#   $2:   block to run if the compiler is at least this version (>=)
+#   $3:   block to run if the compiler is older than this version (<)
+
+
 # $1 = compiler to test (CC or CXX)
 # $2 = human readable name of compiler (C or C++)
 
@@ -3818,10 +3836,22 @@
 
 
 
-# TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
-#                                   [RUN-IF-FALSE])
+# TOOLCHAIN_C_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
+#                                      [RUN-IF-FALSE])
 # ------------------------------------------------------------
-# Check that the c and c++ compilers support an argument
+# Check that the C compiler supports an argument
+
+
+# TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
+#                                        [RUN-IF-FALSE])
+# ------------------------------------------------------------
+# Check that the C++ compiler supports an argument
+
+
+# TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
+#                                    [RUN-IF-FALSE])
+# ------------------------------------------------------------
+# Check that the C and C++ compilers support an argument
 
 
 
@@ -3829,6 +3859,8 @@
 # Setup the JTREG paths
 
 
+
+
 #
 # Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -3880,7 +3912,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1500922661
+DATE_WHEN_GENERATED=1500960571
 
 ###############################################################################
 #
@@ -20368,7 +20400,8 @@
 
     # First line typically looks something like:
     # gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
-    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^.* \([1-9][0-9.]*\)/\1/p"`
+    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | \
+        $SED -e 's/^.* \([1-9]\.[0-9.]*\)[^0-9.].*$/\1/'`
     COMPILER_VENDOR=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^\(.*\) [1-9][0-9.]*/\1/p"`
   fi
   # This sets CC_VERSION or CXX_VERSION. (This comment is a grep marker)
@@ -21969,7 +22002,8 @@
 
     # First line typically looks something like:
     # gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
-    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^.* \([1-9][0-9.]*\)/\1/p"`
+    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | \
+        $SED -e 's/^.* \([1-9]\.[0-9.]*\)[^0-9.].*$/\1/'`
     COMPILER_VENDOR=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^\(.*\) [1-9][0-9.]*/\1/p"`
   fi
   # This sets CC_VERSION or CXX_VERSION. (This comment is a grep marker)
@@ -22240,6 +22274,32 @@
 ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
 
 
+  # This is the compiler version number on the form X.Y[.Z]
+
+
+
+
+  if test "x$CC_VERSION" != "x$CXX_VERSION"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: C and C++ compiler has different version numbers, $CC_VERSION vs $CXX_VERSION." >&5
+$as_echo "$as_me: WARNING: C and C++ compiler has different version numbers, $CC_VERSION vs $CXX_VERSION." >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: This typically indicates a broken setup, and is not supported" >&5
+$as_echo "$as_me: WARNING: This typically indicates a broken setup, and is not supported" >&2;}
+  fi
+
+  # We only check CC_VERSION since we assume CXX_VERSION is equal.
+  if  [[ "$CC_VERSION" =~ (.*\.){3} ]] ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: C compiler version number has more than three parts (X.Y.Z): $CC_VERSION. Comparisons might be wrong." >&5
+$as_echo "$as_me: WARNING: C compiler version number has more than three parts (X.Y.Z): $CC_VERSION. Comparisons might be wrong." >&2;}
+  fi
+
+  if  [[  "$CC_VERSION" =~ [0-9]{6} ]] ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: C compiler version number has a part larger than 99999: $CC_VERSION. Comparisons might be wrong." >&5
+$as_echo "$as_me: WARNING: C compiler version number has a part larger than 99999: $CC_VERSION. Comparisons might be wrong." >&2;}
+  fi
+
+  COMPARABLE_ACTUAL_VERSION=`$AWK -F. '{ printf("%05d%05d%05d\n", $1, $2, $3) }' <<< "$CC_VERSION"`
+
+
   ### Locate other tools
 
   if test "x$OPENJDK_TARGET_OS" = xmacosx; then
@@ -24831,7 +24891,8 @@
 
 
       COMPILER_TYPE=CL
-      CCXXFLAGS="$CCXXFLAGS -nologo"
+      # silence copyright notice and other headers.
+      COMMON_CCXXFLAGS="$COMMON_CCXXFLAGS -nologo"
 
 fi
 
@@ -29664,12 +29725,57 @@
   #
   # Now setup the CFLAGS and LDFLAGS for the JDK build.
   # Later we will also have CFLAGS and LDFLAGS for the hotspot subrepo build.
+  #    CFLAGS_JDK    - C Compiler flags
+  #    CXXFLAGS_JDK  - C++ Compiler flags
+  #    COMMON_CCXXFLAGS_JDK - common to C and C++
   #
   case $COMPILER_NAME in
     gcc )
-      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -W -Wall -Wno-unused -Wno-parentheses \
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -W -Wall -Wno-unused -Wno-parentheses \
       -pipe \
       -D_GNU_SOURCE -D_REENTRANT -D_LARGEFILE64_SOURCE"
+      CXXSTD_CXXFLAG="-std=gnu++98"
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"$CXXSTD_CXXFLAG $CFLAGS_WARNINGS_ARE_ERRORS\"" >&5
+$as_echo_n "checking if the C++ compiler supports \"$CXXSTD_CXXFLAG $CFLAGS_WARNINGS_ARE_ERRORS\"... " >&6; }
+  supports=yes
+
+  saved_cxxflags="$CXXFLAGS"
+  CXXFLAGS="$CXXFLAG $CXXSTD_CXXFLAG $CFLAGS_WARNINGS_ARE_ERRORS"
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int i;
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+
+else
+  supports=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+  CXXFLAGS="$saved_cxxflags"
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    :
+  else
+    CXXSTD_CXXFLAG=""
+  fi
+
+      CXXFLAGS_JDK="${CXXFLAGS_JDK} ${CXXSTD_CXXFLAG}"
+
       case $OPENJDK_TARGET_CPU_ARCH in
         arm )
           # on arm we don't prevent gcc to omit frame pointer but do prevent strict aliasing
@@ -29679,16 +29785,234 @@
           # on ppc we don't prevent gcc to omit frame pointer nor strict-aliasing
           ;;
         * )
-          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -fno-omit-frame-pointer"
+          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -fno-omit-frame-pointer"
           CFLAGS_JDK="${CFLAGS_JDK} -fno-strict-aliasing"
           ;;
       esac
+
+  REFERENCE_VERSION=6
+
+  if  [[ "$REFERENCE_VERSION" =~ (.*\.){3} ]] ; then
+    as_fn_error $? "Internal error: Cannot compare to $REFERENCE_VERSION, only three parts (X.Y.Z) is supported" "$LINENO" 5
+  fi
+
+  if  [[ "$REFERENCE_VERSION" =~ [0-9]{6} ]] ; then
+    as_fn_error $? "Internal error: Cannot compare to $REFERENCE_VERSION, only parts < 99999 is supported" "$LINENO" 5
+  fi
+
+  # Version comparison method inspired by http://stackoverflow.com/a/24067243
+  COMPARABLE_REFERENCE_VERSION=`$AWK -F. '{ printf("%05d%05d%05d\n", $1, $2, $3) }' <<< "$REFERENCE_VERSION"`
+
+  if test $COMPARABLE_ACTUAL_VERSION -ge $COMPARABLE_REFERENCE_VERSION ; then
+
+  # These flags are required for GCC 6 builds as undefined behaviour in OpenJDK code
+  # runs afoul of the more aggressive versions of these optimisations.
+  # Notably, value range propagation now assumes that the this pointer of C++
+  # member functions is non-null.
+  NO_DELETE_NULL_POINTER_CHECKS_CFLAG="-fno-delete-null-pointer-checks"
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C compiler supports \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"" >&5
+$as_echo_n "checking if the C compiler supports \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"... " >&6; }
+  supports=yes
+
+  saved_cflags="$CFLAGS"
+  CFLAGS="$CFLAGS $NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror"
+  ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int i;
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  supports=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+  CFLAGS="$saved_cflags"
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    C_COMP_SUPPORTS="yes"
+  else
+    C_COMP_SUPPORTS="no"
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"" >&5
+$as_echo_n "checking if the C++ compiler supports \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"... " >&6; }
+  supports=yes
+
+  saved_cxxflags="$CXXFLAGS"
+  CXXFLAGS="$CXXFLAG $NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror"
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int i;
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+
+else
+  supports=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+  CXXFLAGS="$saved_cxxflags"
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    CXX_COMP_SUPPORTS="yes"
+  else
+    CXX_COMP_SUPPORTS="no"
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if both compilers support \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"" >&5
+$as_echo_n "checking if both compilers support \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"... " >&6; }
+  supports=no
+  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    :
+  else
+    NO_DELETE_NULL_POINTER_CHECKS_CFLAG=""
+  fi
+
+
+  NO_LIFETIME_DSE_CFLAG="-fno-lifetime-dse"
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C compiler supports \"$NO_LIFETIME_DSE_CFLAG -Werror\"" >&5
+$as_echo_n "checking if the C compiler supports \"$NO_LIFETIME_DSE_CFLAG -Werror\"... " >&6; }
+  supports=yes
+
+  saved_cflags="$CFLAGS"
+  CFLAGS="$CFLAGS $NO_LIFETIME_DSE_CFLAG -Werror"
+  ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int i;
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  supports=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+  CFLAGS="$saved_cflags"
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    C_COMP_SUPPORTS="yes"
+  else
+    C_COMP_SUPPORTS="no"
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"$NO_LIFETIME_DSE_CFLAG -Werror\"" >&5
+$as_echo_n "checking if the C++ compiler supports \"$NO_LIFETIME_DSE_CFLAG -Werror\"... " >&6; }
+  supports=yes
+
+  saved_cxxflags="$CXXFLAGS"
+  CXXFLAGS="$CXXFLAG $NO_LIFETIME_DSE_CFLAG -Werror"
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int i;
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+
+else
+  supports=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+  CXXFLAGS="$saved_cxxflags"
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    CXX_COMP_SUPPORTS="yes"
+  else
+    CXX_COMP_SUPPORTS="no"
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if both compilers support \"$NO_LIFETIME_DSE_CFLAG -Werror\"" >&5
+$as_echo_n "checking if both compilers support \"$NO_LIFETIME_DSE_CFLAG -Werror\"... " >&6; }
+  supports=no
+  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    :
+  else
+    NO_LIFETIME_DSE_CFLAG=""
+  fi
+
+  CFLAGS_JDK="${CFLAGS_JDK} ${NO_DELETE_NULL_POINTER_CHECKS_CFLAG} ${NO_LIFETIME_DSE_CFLAG}"
+
+
+
+  else
+    :
+  fi
+
       ;;
     ossc )
-      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -DTRACING -DMACRO_MEMSYS_OPS -DBREAKPTS"
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -DTRACING -DMACRO_MEMSYS_OPS -DBREAKPTS"
       case $OPENJDK_TARGET_CPU_ARCH in
         x86 )
-          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DcpuIntel -Di586 -D$OPENJDK_TARGET_CPU_LEGACY_LIB"
+          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DcpuIntel -Di586 -D$OPENJDK_TARGET_CPU_LEGACY_LIB"
           CFLAGS_JDK="$CFLAGS_JDK -erroff=E_BAD_PRAGMA_PACK_VALUE"
           ;;
       esac
@@ -29707,16 +30031,16 @@
       LDFLAGS_CXX_JDK="$LDFLAGS_CXX_JDK"
       ;;
     cl )
-      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -Zi -MD -Zc:wchar_t- -W3 -wd4800 \
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -Zi -MD -Zc:wchar_t- -W3 -wd4800 \
       -D_STATIC_CPPLIB -D_DISABLE_DEPRECATE_STATIC_CPPLIB -DWIN32_LEAN_AND_MEAN \
       -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE \
       -DWIN32 -DIAL"
       case $OPENJDK_TARGET_CPU in
         x86 )
-          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_X86_ -Dx86"
+          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_X86_ -Dx86"
           ;;
         x86_64 )
-          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_AMD64_ -Damd64"
+          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_AMD64_ -Damd64"
           ;;
       esac
       ;;
@@ -29746,7 +30070,7 @@
       ;;
   esac
 
-  CCXXFLAGS_JDK="$CCXXFLAGS_JDK $ADD_LP64"
+  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK $ADD_LP64"
 
   # The package path is used only on macosx?
   PACKAGE_PATH=/opt/local
@@ -29759,27 +30083,27 @@
     #   Note: -Dmacro         is the same as    #define macro 1
     #         -Dmacro=        is the same as    #define macro
     if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-      CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_LITTLE_ENDIAN="
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_LITTLE_ENDIAN="
     else
-      CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_LITTLE_ENDIAN"
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_LITTLE_ENDIAN"
     fi
   else
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_BIG_ENDIAN"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_BIG_ENDIAN"
   fi
   if test "x$OPENJDK_TARGET_OS" = xlinux; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DLINUX"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DLINUX"
   fi
   if test "x$OPENJDK_TARGET_OS" = xwindows; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DWINDOWS"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DWINDOWS"
   fi
   if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DSOLARIS"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DSOLARIS"
   fi
   if test "x$OPENJDK_TARGET_OS" = xaix; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DAIX -DPPC64"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DAIX -DPPC64"
   fi
   if test "x$OPENJDK_TARGET_OS" = xmacosx; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DMACOSX -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMACOSX -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT"
     # Setting these parameters makes it an error to link to macosx APIs that are
     # newer than the given OS version and makes the linked binaries compatible even
     # if built on a newer version of the OS.
@@ -29789,25 +30113,25 @@
     # The macro takes the version with no dots, ex: 1070
     # Let the flags variables get resolved in make for easier override on make
     # command line.
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
     LDFLAGS_JDK="$LDFLAGS_JDK -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
   fi
   if test "x$OPENJDK_TARGET_OS" = xbsd; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DBSD -D_ALLBSD_SOURCE"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DBSD -D_ALLBSD_SOURCE"
   fi
   if test "x$DEBUG_LEVEL" = xrelease; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DNDEBUG"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DNDEBUG"
   if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DTRIMMED"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DTRIMMED"
   fi
   else
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DDEBUG"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DDEBUG"
   fi
 
-  CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DARCH='\"$OPENJDK_TARGET_CPU_LEGACY\"' -D$OPENJDK_TARGET_CPU_LEGACY"
-  CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DRELEASE='\"\$(RELEASE)\"'"
+  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DARCH='\"$OPENJDK_TARGET_CPU_LEGACY\"' -D$OPENJDK_TARGET_CPU_LEGACY"
+  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DRELEASE='\"\$(RELEASE)\"'"
 
-  CCXXFLAGS_JDK="$CCXXFLAGS_JDK \
+  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK \
       -I${JDK_OUTPUTDIR}/include \
       -I${JDK_OUTPUTDIR}/include/$OPENJDK_TARGET_OS \
       -I${JDK_TOPDIR}/src/share/javavm/export \
@@ -29816,12 +30140,12 @@
       -I${JDK_TOPDIR}/src/$OPENJDK_TARGET_OS_API_DIR/native/common"
 
   # The shared libraries are compiled using the picflag.
-  CFLAGS_JDKLIB="$CCXXFLAGS_JDK $CFLAGS_JDK $PICFLAG $CFLAGS_JDKLIB_EXTRA"
-  CXXFLAGS_JDKLIB="$CCXXFLAGS_JDK $CXXFLAGS_JDK $PICFLAG $CXXFLAGS_JDKLIB_EXTRA "
+  CFLAGS_JDKLIB="$COMMON_CCXXFLAGS_JDK $CFLAGS_JDK $PICFLAG $CFLAGS_JDKLIB_EXTRA"
+  CXXFLAGS_JDKLIB="$COMMON_CCXXFLAGS_JDK $CXXFLAGS_JDK $PICFLAG $CXXFLAGS_JDKLIB_EXTRA "
 
   # Executable flags
-  CFLAGS_JDKEXE="$CCXXFLAGS_JDK $CFLAGS_JDK"
-  CXXFLAGS_JDKEXE="$CCXXFLAGS_JDK $CXXFLAGS_JDK"
+  CFLAGS_JDKEXE="$COMMON_CCXXFLAGS_JDK $CFLAGS_JDK"
+  CXXFLAGS_JDKEXE="$COMMON_CCXXFLAGS_JDK $CXXFLAGS_JDK"
 
   # Now this is odd. The JDK native libraries have to link against libjvm.so
   # On 32-bit machines there is normally two distinct libjvm.so:s, client and server.
@@ -29905,7 +30229,6 @@
 
 
 
-
   # Some Zero and Shark settings.
   # ZERO_ARCHFLAG tells the compiler which mode to build for
   case "${OPENJDK_TARGET_CPU}" in
@@ -29916,8 +30239,9 @@
       ZERO_ARCHFLAG="${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}"
   esac
 
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler supports \"$ZERO_ARCHFLAG\"" >&5
-$as_echo_n "checking if compiler supports \"$ZERO_ARCHFLAG\"... " >&6; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C compiler supports \"$ZERO_ARCHFLAG\"" >&5
+$as_echo_n "checking if the C compiler supports \"$ZERO_ARCHFLAG\"... " >&6; }
   supports=yes
 
   saved_cflags="$CFLAGS"
@@ -29946,6 +30270,19 @@
 
   CFLAGS="$saved_cflags"
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    C_COMP_SUPPORTS="yes"
+  else
+    C_COMP_SUPPORTS="no"
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"$ZERO_ARCHFLAG\"" >&5
+$as_echo_n "checking if the C++ compiler supports \"$ZERO_ARCHFLAG\"... " >&6; }
+  supports=yes
+
   saved_cxxflags="$CXXFLAGS"
   CXXFLAGS="$CXXFLAG $ZERO_ARCHFLAG"
   ac_ext=cpp
@@ -29975,6 +30312,20 @@
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
 $as_echo "$supports" >&6; }
   if test "x$supports" = "xyes" ; then
+    CXX_COMP_SUPPORTS="yes"
+  else
+    CXX_COMP_SUPPORTS="no"
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if both compilers support \"$ZERO_ARCHFLAG\"" >&5
+$as_echo_n "checking if both compilers support \"$ZERO_ARCHFLAG\"... " >&6; }
+  supports=no
+  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
     :
   else
     ZERO_ARCHFLAG=""
@@ -29985,8 +30336,9 @@
   # Check that the compiler supports -mX (or -qX on AIX) flags
   # Set COMPILER_SUPPORTS_TARGET_BITS_FLAG to 'true' if it does
 
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"" >&5
-$as_echo_n "checking if compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"... " >&6; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"" >&5
+$as_echo_n "checking if the C compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"... " >&6; }
   supports=yes
 
   saved_cflags="$CFLAGS"
@@ -30015,6 +30367,19 @@
 
   CFLAGS="$saved_cflags"
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
+    C_COMP_SUPPORTS="yes"
+  else
+    C_COMP_SUPPORTS="no"
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"" >&5
+$as_echo_n "checking if the C++ compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"... " >&6; }
+  supports=yes
+
   saved_cxxflags="$CXXFLAGS"
   CXXFLAGS="$CXXFLAG ${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}"
   ac_ext=cpp
@@ -30044,6 +30409,20 @@
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
 $as_echo "$supports" >&6; }
   if test "x$supports" = "xyes" ; then
+    CXX_COMP_SUPPORTS="yes"
+  else
+    CXX_COMP_SUPPORTS="no"
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if both compilers support \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"" >&5
+$as_echo_n "checking if both compilers support \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"... " >&6; }
+  supports=no
+  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
+$as_echo "$supports" >&6; }
+  if test "x$supports" = "xyes" ; then
     COMPILER_SUPPORTS_TARGET_BITS_FLAG=true
   else
     COMPILER_SUPPORTS_TARGET_BITS_FLAG=false
diff --git a/common/autoconf/hotspot-spec.gmk.in b/common/autoconf/hotspot-spec.gmk.in
index 65d14dc..8146fe5 100644
--- a/common/autoconf/hotspot-spec.gmk.in
+++ b/common/autoconf/hotspot-spec.gmk.in
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -109,7 +109,8 @@
 MT:=@HOTSPOT_MT@
 RC:=@HOTSPOT_RC@
 
-EXTRA_CFLAGS=@LEGACY_EXTRA_CFLAGS@
+EXTRA_CFLAGS=@LEGACY_EXTRA_CFLAGS@ $(NO_DELETE_NULL_POINTER_CHECKS_CFLAG) \
+				   $(NO_LIFETIME_DSE_CFLAG) $(CXXSTD_CXXFLAG)
 EXTRA_CXXFLAGS=@LEGACY_EXTRA_CXXFLAGS@
 EXTRA_LDFLAGS=@LEGACY_EXTRA_LDFLAGS@
 
diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in
index ed3ef8b..1c418f2 100644
--- a/common/autoconf/spec.gmk.in
+++ b/common/autoconf/spec.gmk.in
@@ -331,6 +331,10 @@
 CFLAGS_JDKEXE:=@CFLAGS_JDKEXE@
 CXXFLAGS_JDKEXE:=@CXXFLAGS_JDKEXE@
 
+NO_DELETE_NULL_POINTER_CHECKS_CFLAG=@NO_DELETE_NULL_POINTER_CHECKS_CFLAG@
+NO_LIFETIME_DSE_CFLAG=@NO_LIFETIME_DSE_CFLAG@
+CXXSTD_CXXFLAG=@CXXSTD_CXXFLAG@
+
 CXX:=@FIXPATH@ @CCACHE@ @CXX@
 #CXXFLAGS:=@CXXFLAGS@
 
diff --git a/common/autoconf/toolchain.m4 b/common/autoconf/toolchain.m4
index 44ceadf..1af8fa3 100644
--- a/common/autoconf/toolchain.m4
+++ b/common/autoconf/toolchain.m4
@@ -23,9 +23,59 @@
 # questions.
 #
 
+# Prepare the system so that TOOLCHAIN_CHECK_COMPILER_VERSION can be called.
+# Must have CC_VERSION_NUMBER and CXX_VERSION_NUMBER.
+AC_DEFUN([TOOLCHAIN_PREPARE_FOR_VERSION_COMPARISONS],
+[
+  if test "x$CC_VERSION" != "x$CXX_VERSION"; then
+    AC_MSG_WARN([C and C++ compiler has different version numbers, $CC_VERSION vs $CXX_VERSION.])
+    AC_MSG_WARN([This typically indicates a broken setup, and is not supported])
+  fi
+
+  # We only check CC_VERSION since we assume CXX_VERSION is equal.
+  if [ [[ "$CC_VERSION" =~ (.*\.){3} ]] ]; then
+    AC_MSG_WARN([C compiler version number has more than three parts (X.Y.Z): $CC_VERSION. Comparisons might be wrong.])
+  fi
+
+  if [ [[  "$CC_VERSION" =~ [0-9]{6} ]] ]; then
+    AC_MSG_WARN([C compiler version number has a part larger than 99999: $CC_VERSION. Comparisons might be wrong.])
+  fi
+
+  COMPARABLE_ACTUAL_VERSION=`$AWK -F. '{ printf("%05d%05d%05d\n", [$]1, [$]2, [$]3) }' <<< "$CC_VERSION"`
+])
+
+# Check if the configured compiler (C and C++) is of a specific version or
+# newer. TOOLCHAIN_PREPARE_FOR_VERSION_COMPARISONS must have been called before.
+#
+# Arguments:
+#   $1:   The version string to check against the found version
+#   $2:   block to run if the compiler is at least this version (>=)
+#   $3:   block to run if the compiler is older than this version (<)
+AC_DEFUN([TOOLCHAIN_CHECK_COMPILER_VERSION],
+[
+  REFERENCE_VERSION=$1
+
+  if [ [[ "$REFERENCE_VERSION" =~ (.*\.){3} ]] ]; then
+    AC_MSG_ERROR([Internal error: Cannot compare to $REFERENCE_VERSION, only three parts (X.Y.Z) is supported])
+  fi
+
+  if [ [[ "$REFERENCE_VERSION" =~ [0-9]{6} ]] ]; then
+    AC_MSG_ERROR([Internal error: Cannot compare to $REFERENCE_VERSION, only parts < 99999 is supported])
+  fi
+
+  # Version comparison method inspired by http://stackoverflow.com/a/24067243
+  COMPARABLE_REFERENCE_VERSION=`$AWK -F. '{ printf("%05d%05d%05d\n", [$]1, [$]2, [$]3) }' <<< "$REFERENCE_VERSION"`
+
+  if test $COMPARABLE_ACTUAL_VERSION -ge $COMPARABLE_REFERENCE_VERSION ; then
+    m4_ifval([$2], [$2], [:])
+  else
+    m4_ifval([$3], [$3], [:])
+  fi
+])
+
 # $1 = compiler to test (CC or CXX)
 # $2 = human readable name of compiler (C or C++)
-AC_DEFUN([TOOLCHAIN_CHECK_COMPILER_VERSION],
+AC_DEFUN([TOOLCHAIN_EXTRACT_COMPILER_VERSION],
 [
   COMPILER=[$]$1
   COMPILER_NAME=$2
@@ -81,7 +131,8 @@
 
     # First line typically looks something like:
     # gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
-    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^.* \(@<:@1-9@:>@@<:@0-9.@:>@*\)/\1/p"`
+    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | \
+        $SED -e 's/^.* \(@<:@1-9@:>@\.@<:@0-9.@:>@*\)@<:@^0-9.@:>@.*$/\1/'`
     COMPILER_VENDOR=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^\(.*\) @<:@1-9@:>@@<:@0-9.@:>@*/\1/p"`
   fi
   # This sets CC_VERSION or CXX_VERSION. (This comment is a grep marker)
@@ -181,7 +232,7 @@
     AC_MSG_RESULT([no, keeping $1])
     $1="$TEST_COMPILER"
   fi
-  TOOLCHAIN_CHECK_COMPILER_VERSION([$1], [$COMPILER_NAME])
+  TOOLCHAIN_EXTRACT_COMPILER_VERSION([$1], [$COMPILER_NAME])
 ])
 
 
@@ -385,6 +436,12 @@
   # Now that we have resolved CXX ourself, let autoconf have its go at it
   AC_PROG_CXX([$CXX])
 
+  # This is the compiler version number on the form X.Y[.Z]
+  AC_SUBST(CC_VERSION)
+  AC_SUBST(CXX_VERSION)
+
+  TOOLCHAIN_PREPARE_FOR_VERSION_COMPARISONS
+
   ### Locate other tools
 
   if test "x$OPENJDK_TARGET_OS" = xmacosx; then
@@ -507,7 +564,8 @@
       BASIC_FIXUP_EXECUTABLE(DUMPBIN)
 
       COMPILER_TYPE=CL
-      CCXXFLAGS="$CCXXFLAGS -nologo"
+      # silence copyright notice and other headers.
+      COMMON_CCXXFLAGS="$COMMON_CCXXFLAGS -nologo"
   ])
   AC_SUBST(RC_FLAGS)
   AC_SUBST(COMPILER_TYPE)
@@ -954,12 +1012,20 @@
   #
   # Now setup the CFLAGS and LDFLAGS for the JDK build.
   # Later we will also have CFLAGS and LDFLAGS for the hotspot subrepo build.
+  #    CFLAGS_JDK    - C Compiler flags
+  #    CXXFLAGS_JDK  - C++ Compiler flags
+  #    COMMON_CCXXFLAGS_JDK - common to C and C++
   #
   case $COMPILER_NAME in
     gcc )
-      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -W -Wall -Wno-unused -Wno-parentheses \
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -W -Wall -Wno-unused -Wno-parentheses \
       -pipe \
       -D_GNU_SOURCE -D_REENTRANT -D_LARGEFILE64_SOURCE"
+      CXXSTD_CXXFLAG="-std=gnu++98"
+      TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS([$CXXSTD_CXXFLAG $CFLAGS_WARNINGS_ARE_ERRORS],
+    					     [], [CXXSTD_CXXFLAG=""])
+      CXXFLAGS_JDK="${CXXFLAGS_JDK} ${CXXSTD_CXXFLAG}"
+      AC_SUBST([CXXSTD_CXXFLAG])
       case $OPENJDK_TARGET_CPU_ARCH in
         arm )
           # on arm we don't prevent gcc to omit frame pointer but do prevent strict aliasing
@@ -969,16 +1035,17 @@
           # on ppc we don't prevent gcc to omit frame pointer nor strict-aliasing
           ;;
         * )
-          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -fno-omit-frame-pointer"
+          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -fno-omit-frame-pointer"
           CFLAGS_JDK="${CFLAGS_JDK} -fno-strict-aliasing"
           ;;
       esac
+      TOOLCHAIN_CHECK_COMPILER_VERSION(6, TOOLCHAIN_SETUP_GCC6_COMPILER_FLAGS)
       ;;
     ossc )
-      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -DTRACING -DMACRO_MEMSYS_OPS -DBREAKPTS"
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -DTRACING -DMACRO_MEMSYS_OPS -DBREAKPTS"
       case $OPENJDK_TARGET_CPU_ARCH in
         x86 )
-          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DcpuIntel -Di586 -D$OPENJDK_TARGET_CPU_LEGACY_LIB"
+          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DcpuIntel -Di586 -D$OPENJDK_TARGET_CPU_LEGACY_LIB"
           CFLAGS_JDK="$CFLAGS_JDK -erroff=E_BAD_PRAGMA_PACK_VALUE"
           ;;
       esac
@@ -997,16 +1064,16 @@
       LDFLAGS_CXX_JDK="$LDFLAGS_CXX_JDK"
       ;;
     cl )
-      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -Zi -MD -Zc:wchar_t- -W3 -wd4800 \
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -Zi -MD -Zc:wchar_t- -W3 -wd4800 \
       -D_STATIC_CPPLIB -D_DISABLE_DEPRECATE_STATIC_CPPLIB -DWIN32_LEAN_AND_MEAN \
       -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE \
       -DWIN32 -DIAL"
       case $OPENJDK_TARGET_CPU in
         x86 )
-          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_X86_ -Dx86"
+          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_X86_ -Dx86"
           ;;
         x86_64 )
-          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_AMD64_ -Damd64"
+          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_AMD64_ -Damd64"
           ;;
       esac
       ;;
@@ -1036,7 +1103,7 @@
       ;;
   esac
 
-  CCXXFLAGS_JDK="$CCXXFLAGS_JDK $ADD_LP64"
+  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK $ADD_LP64"
 
   # The package path is used only on macosx?
   PACKAGE_PATH=/opt/local
@@ -1049,27 +1116,27 @@
     #   Note: -Dmacro         is the same as    #define macro 1
     #         -Dmacro=        is the same as    #define macro
     if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-      CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_LITTLE_ENDIAN="
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_LITTLE_ENDIAN="
     else
-      CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_LITTLE_ENDIAN"
+      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_LITTLE_ENDIAN"
     fi
   else
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_BIG_ENDIAN"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_BIG_ENDIAN"
   fi
   if test "x$OPENJDK_TARGET_OS" = xlinux; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DLINUX"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DLINUX"
   fi
   if test "x$OPENJDK_TARGET_OS" = xwindows; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DWINDOWS"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DWINDOWS"
   fi
   if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DSOLARIS"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DSOLARIS"
   fi
   if test "x$OPENJDK_TARGET_OS" = xaix; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DAIX -DPPC64"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DAIX -DPPC64"
   fi
   if test "x$OPENJDK_TARGET_OS" = xmacosx; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DMACOSX -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMACOSX -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT"
     # Setting these parameters makes it an error to link to macosx APIs that are
     # newer than the given OS version and makes the linked binaries compatible even
     # if built on a newer version of the OS.
@@ -1079,25 +1146,25 @@
     # The macro takes the version with no dots, ex: 1070
     # Let the flags variables get resolved in make for easier override on make
     # command line.
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
     LDFLAGS_JDK="$LDFLAGS_JDK -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
   fi
   if test "x$OPENJDK_TARGET_OS" = xbsd; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DBSD -D_ALLBSD_SOURCE"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DBSD -D_ALLBSD_SOURCE"
   fi
   if test "x$DEBUG_LEVEL" = xrelease; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DNDEBUG"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DNDEBUG"
   if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DTRIMMED"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DTRIMMED"
   fi
   else
-    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DDEBUG"
+    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DDEBUG"
   fi
 
-  CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DARCH='\"$OPENJDK_TARGET_CPU_LEGACY\"' -D$OPENJDK_TARGET_CPU_LEGACY"
-  CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DRELEASE='\"\$(RELEASE)\"'"
+  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DARCH='\"$OPENJDK_TARGET_CPU_LEGACY\"' -D$OPENJDK_TARGET_CPU_LEGACY"
+  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DRELEASE='\"\$(RELEASE)\"'"
 
-  CCXXFLAGS_JDK="$CCXXFLAGS_JDK \
+  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK \
       -I${JDK_OUTPUTDIR}/include \
       -I${JDK_OUTPUTDIR}/include/$OPENJDK_TARGET_OS \
       -I${JDK_TOPDIR}/src/share/javavm/export \
@@ -1106,12 +1173,12 @@
       -I${JDK_TOPDIR}/src/$OPENJDK_TARGET_OS_API_DIR/native/common"
 
   # The shared libraries are compiled using the picflag.
-  CFLAGS_JDKLIB="$CCXXFLAGS_JDK $CFLAGS_JDK $PICFLAG $CFLAGS_JDKLIB_EXTRA"
-  CXXFLAGS_JDKLIB="$CCXXFLAGS_JDK $CXXFLAGS_JDK $PICFLAG $CXXFLAGS_JDKLIB_EXTRA "
+  CFLAGS_JDKLIB="$COMMON_CCXXFLAGS_JDK $CFLAGS_JDK $PICFLAG $CFLAGS_JDKLIB_EXTRA"
+  CXXFLAGS_JDKLIB="$COMMON_CCXXFLAGS_JDK $CXXFLAGS_JDK $PICFLAG $CXXFLAGS_JDKLIB_EXTRA "
 
   # Executable flags
-  CFLAGS_JDKEXE="$CCXXFLAGS_JDK $CFLAGS_JDK"
-  CXXFLAGS_JDKEXE="$CCXXFLAGS_JDK $CXXFLAGS_JDK"
+  CFLAGS_JDKEXE="$COMMON_CCXXFLAGS_JDK $CFLAGS_JDK"
+  CXXFLAGS_JDKEXE="$COMMON_CCXXFLAGS_JDK $CXXFLAGS_JDK"
 
   # Now this is odd. The JDK native libraries have to link against libjvm.so
   # On 32-bit machines there is normally two distinct libjvm.so:s, client and server.
@@ -1196,13 +1263,13 @@
 ])
 
 
-# TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
-#                                   [RUN-IF-FALSE])
+# TOOLCHAIN_C_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
+#                                      [RUN-IF-FALSE])
 # ------------------------------------------------------------
-# Check that the c and c++ compilers support an argument
-AC_DEFUN([TOOLCHAIN_COMPILER_CHECK_ARGUMENTS],
+# Check that the C compiler supports an argument
+AC_DEFUN([TOOLCHAIN_C_COMPILER_CHECK_ARGUMENTS],
 [
-  AC_MSG_CHECKING([if compiler supports "$1"])
+  AC_MSG_CHECKING([if the C compiler supports "$1"])
   supports=yes
 
   saved_cflags="$CFLAGS"
@@ -1213,6 +1280,23 @@
   AC_LANG_POP([C])
   CFLAGS="$saved_cflags"
 
+  AC_MSG_RESULT([$supports])
+  if test "x$supports" = "xyes" ; then
+    m4_ifval([$2], [$2], [:])
+  else
+    m4_ifval([$3], [$3], [:])
+  fi
+])
+
+# TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
+#                                        [RUN-IF-FALSE])
+# ------------------------------------------------------------
+# Check that the C++ compiler supports an argument
+AC_DEFUN([TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS],
+[
+  AC_MSG_CHECKING([if the C++ compiler supports "$1"])
+  supports=yes
+
   saved_cxxflags="$CXXFLAGS"
   CXXFLAGS="$CXXFLAG $1"
   AC_LANG_PUSH([C++])
@@ -1220,7 +1304,32 @@
       [supports=no])
   AC_LANG_POP([C++])
   CXXFLAGS="$saved_cxxflags"
+  
+  AC_MSG_RESULT([$supports])
+  if test "x$supports" = "xyes" ; then
+    m4_ifval([$2], [$2], [:])
+  else
+    m4_ifval([$3], [$3], [:])
+  fi
+])
 
+# TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
+#                                    [RUN-IF-FALSE])
+# ------------------------------------------------------------
+# Check that the C and C++ compilers support an argument
+AC_DEFUN([TOOLCHAIN_COMPILER_CHECK_ARGUMENTS],
+[
+  TOOLCHAIN_C_COMPILER_CHECK_ARGUMENTS([$1],
+  				       [C_COMP_SUPPORTS="yes"],
+				       [C_COMP_SUPPORTS="no"])
+  TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS([$1],
+  					 [CXX_COMP_SUPPORTS="yes"],
+					 [CXX_COMP_SUPPORTS="no"])
+
+  AC_MSG_CHECKING([if both compilers support "$1"])
+  supports=no
+  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
+  
   AC_MSG_RESULT([$supports])
   if test "x$supports" = "xyes" ; then
     m4_ifval([$2], [$2], [:])
@@ -1311,3 +1420,20 @@
   AC_SUBST(JT_HOME)
   AC_SUBST(JTREGEXE)
 ])
+
+AC_DEFUN_ONCE([TOOLCHAIN_SETUP_GCC6_COMPILER_FLAGS],
+[
+  # These flags are required for GCC 6 builds as undefined behaviour in OpenJDK code
+  # runs afoul of the more aggressive versions of these optimisations.
+  # Notably, value range propagation now assumes that the this pointer of C++
+  # member functions is non-null.
+  NO_DELETE_NULL_POINTER_CHECKS_CFLAG="-fno-delete-null-pointer-checks"
+  TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror],
+  				     [], [NO_DELETE_NULL_POINTER_CHECKS_CFLAG=""])
+  AC_SUBST([NO_DELETE_NULL_POINTER_CHECKS_CFLAG])
+  NO_LIFETIME_DSE_CFLAG="-fno-lifetime-dse"
+  TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([$NO_LIFETIME_DSE_CFLAG -Werror],
+  				     [], [NO_LIFETIME_DSE_CFLAG=""])
+  CFLAGS_JDK="${CFLAGS_JDK} ${NO_DELETE_NULL_POINTER_CHECKS_CFLAG} ${NO_LIFETIME_DSE_CFLAG}"
+  AC_SUBST([NO_LIFETIME_DSE_CFLAG])
+])
diff --git a/corba/.hgtags b/corba/.hgtags
index 78d13be..295fe7d 100644
--- a/corba/.hgtags
+++ b/corba/.hgtags
@@ -753,3 +753,25 @@
 8977426affc02fdf74b1163865059ec86ddccb61 jdk8u151-b05
 3289ad7e88f3aa38fdaa4910e9eeed5e1e5430b1 jdk8u151-b06
 d41040488bbb511d64c6c2533d642e52675edfde jdk8u151-b07
+5d079476bf24cb8143473d2a0880e0b2e032b1eb jdk8u151-b08
+58d0ffe75dc5597310d422e214dc077476bd2338 jdk8u122-b00
+a87b06da783bb5a11f7857220789979129e39e7c jdk8u122-b01
+8684348ae5eb6f895d19e4752dea567642dbcec4 jdk8u122-b02
+117a593d021502529821afbd7e0d695c170449f8 jdk8u122-b03
+117a593d021502529821afbd7e0d695c170449f8 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+f8661a76fe475b1d7653493e407086830fde81f8 jdk8u122-b03
+7bd4195b17aa0a268eee4bc4b89f30ed3b096898 jdk8u122-b04
+f86d6064d7cfa022425c3df03d4335511ab33ecb jdk8u132-b00
+ea3d3c26102dcb82d9b140f729308395310dae7a jdk8u152-b00
+1819d008129b31df8c74b5d16e9daabc2bdcc10c jdk8u152-b01
+06f411ed0014d88050d9bd1e74c208a9fa3cfb6e jdk8u152-b02
+d36e9c6f195c5604626f7c836c17826960ca2a11 jdk8u152-b03
+4f94cc55256028ab54390abe212959c241b0670f jdk8u152-b04
+2917e61cfadab474625d19fb7775ccdec5584738 jdk8u152-b05
+bc6e4d3f7a20c34dcdccc1be17792188ccdcb917 jdk8u152-b06
+87992ac3484c6c2ae5cad4ad14701a03a9ec963c jdk8u152-b07
+1f7bbfb8b2632ac610c3a0d7d944ff0a3967469a jdk8u152-b08
+a9e83644bd11b5da49bb4424eed9c5a34003085c jdk8u152-b09
+3c302cc47b26715fb9ae863a477d6d0366feb713 jdk8u152-b10
diff --git a/corba/ASSEMBLY_EXCEPTION b/corba/ASSEMBLY_EXCEPTION
index 8b7ac1d..065b8d9 100644
--- a/corba/ASSEMBLY_EXCEPTION
+++ b/corba/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Sun at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Sun gives you permission to link this
-    OpenJDK Code with certain code licensed by Sun as indicated at
+    As a special exception, Oracle gives you permission to link this
+    OpenJDK Code with certain code licensed by Oracle as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Sun.
+    governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Sun
-could not provide under GPL2 (or that Sun has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/hotspot/.hgtags b/hotspot/.hgtags
index c7e2f07..f376b57 100644
--- a/hotspot/.hgtags
+++ b/hotspot/.hgtags
@@ -983,3 +983,25 @@
 507af6ef977a5d0306a8723dec66e34befc1ae81 jdk8u151-b05
 e1dc36cddcbc36b78e3d0558f87bbf459191e479 jdk8u151-b06
 e2a930243efa63b0a789e85a523e69574d53ac92 jdk8u151-b07
+158904fa31b28f1e027dc5b5a833ee673e89a84b jdk8u151-b08
+5aa8c4ca51f0e666d368a4f119ed734d3ac59d7c jdk8u122-b00
+2198ef7e1c1702b3506b95b5d8c886ad5a12bbe5 jdk8u122-b01
+58d961f47dd4ee1d516512b7744e0f1fc83d8f52 jdk8u122-b02
+b0f2296a0bc85e400e4389306219fcfd2076c9b5 jdk8u122-b03
+b0f2296a0bc85e400e4389306219fcfd2076c9b5 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+65601f3eae818a49a5246c73fb4872f5467a230c jdk8u122-b03
+fb8ea28efb05cd89e5416665232165ef0d2eef29 jdk8u122-b04
+92aff007ba7fd9b69adcf212c5280b9152f3d667 jdk8u132-b00
+8cc092b845ce5dae4fa450d23d8bb9abf509e1a0 jdk8u152-b00
+77d9c9da7188ef4d5fe9c409362d63911c4794e8 jdk8u152-b01
+60d621df6c586e325c0a2cf045c8fc68b7f979fe jdk8u152-b02
+d63e731a896c711b8e0c30ac9ae2d900d4e024f6 jdk8u152-b03
+0bd600d6d77b5b41780074bcbfa133032dadf657 jdk8u152-b04
+68758c5ab0c1ef01e89bea8a9b799714831a177f jdk8u152-b05
+98fb3d75fe567bda30a3667c58a9f83ad2acbdf3 jdk8u152-b06
+4af38194b12580bdc885ab3873d7efefa990f543 jdk8u152-b07
+285fcd09ae9994ac836a2759f6615520b2568432 jdk8u152-b08
+70f18ab733f55856cbd880fe8ba3034ff4d7265d jdk8u152-b09
+39967c81d3f3b8d20584d1400e6f4b2490f0c822 jdk8u152-b10
diff --git a/hotspot/ASSEMBLY_EXCEPTION b/hotspot/ASSEMBLY_EXCEPTION
index 3e78398..065b8d9 100644
--- a/hotspot/ASSEMBLY_EXCEPTION
+++ b/hotspot/ASSEMBLY_EXCEPTION
@@ -1,9 +1,9 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
@@ -19,9 +19,9 @@
     provided that the Designated Exception Modules continue to be
     governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Oracle
-could not provide under GPL2 (or that Oracle has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/hotspot/agent/src/os/linux/elfmacros.h b/hotspot/agent/src/os/linux/elfmacros.h
index 15bf640..2dc0b61 100644
--- a/hotspot/agent/src/os/linux/elfmacros.h
+++ b/hotspot/agent/src/os/linux/elfmacros.h
@@ -33,6 +33,7 @@
 #define ELF_NHDR        Elf64_Nhdr
 #define ELF_DYN         Elf64_Dyn
 #define ELF_ADDR        Elf64_Addr
+#define ELF_AUXV        Elf64_auxv_t
 
 #define ELF_ST_TYPE     ELF64_ST_TYPE
 
@@ -45,6 +46,7 @@
 #define ELF_NHDR        Elf32_Nhdr
 #define ELF_DYN         Elf32_Dyn
 #define ELF_ADDR        Elf32_Addr
+#define ELF_AUXV        Elf32_auxv_t
 
 #define ELF_ST_TYPE     ELF32_ST_TYPE
 
diff --git a/hotspot/agent/src/os/linux/ps_core.c b/hotspot/agent/src/os/linux/ps_core.c
index 268fc2a..541c857 100644
--- a/hotspot/agent/src/os/linux/ps_core.c
+++ b/hotspot/agent/src/os/linux/ps_core.c
@@ -642,6 +642,18 @@
         if (core_handle_prstatus(ph, descdata, notep->n_descsz) != true) {
           return false;
         }
+      } else if (notep->n_type == NT_AUXV) {
+        // Get first segment from entry point
+        ELF_AUXV *auxv = (ELF_AUXV *)descdata;
+        while (auxv->a_type != AT_NULL) {
+          if (auxv->a_type == AT_ENTRY) {
+            // Set entry point address to address of dynamic section.
+            // We will adjust it in read_exec_segments().
+            ph->core->dynamic_addr = auxv->a_un.a_val;
+            break;
+          }
+          auxv++;
+        }
       }
       p = descdata + ROUNDUP(notep->n_descsz, 4);
    }
@@ -826,7 +838,13 @@
 
          // from PT_DYNAMIC we want to read address of first link_map addr
          case PT_DYNAMIC: {
-            ph->core->dynamic_addr = exec_php->p_vaddr;
+            if (exec_ehdr->e_type == ET_EXEC) {
+                ph->core->dynamic_addr = exec_php->p_vaddr;
+            } else { // ET_DYN
+                // dynamic_addr has entry point of executable.
+                // Thus we should substract it.
+                ph->core->dynamic_addr += exec_php->p_vaddr - exec_ehdr->e_entry;
+            }
             print_debug("address of _DYNAMIC is 0x%lx\n", ph->core->dynamic_addr);
             break;
          }
@@ -1024,8 +1042,9 @@
     goto err;
   }
 
-  if (read_elf_header(ph->core->exec_fd, &exec_ehdr) != true || exec_ehdr.e_type != ET_EXEC) {
-    print_debug("executable file is not a valid ELF ET_EXEC file\n");
+  if (read_elf_header(ph->core->exec_fd, &exec_ehdr) != true ||
+      ((exec_ehdr.e_type != ET_EXEC) && (exec_ehdr.e_type != ET_DYN))) {
+    print_debug("executable file is not a valid ELF file\n");
     goto err;
   }
 
diff --git a/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp b/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
index 7d9aecb..a488d6d 100644
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
@@ -589,6 +589,7 @@
     VNOR_OPCODE    = (4u  << OPCODE_SHIFT | 1284u     ),
     VOR_OPCODE     = (4u  << OPCODE_SHIFT | 1156u     ),
     VXOR_OPCODE    = (4u  << OPCODE_SHIFT | 1220u     ),
+    VRLD_OPCODE    = (4u  << OPCODE_SHIFT |  196u     ),
     VRLB_OPCODE    = (4u  << OPCODE_SHIFT |    4u     ),
     VRLW_OPCODE    = (4u  << OPCODE_SHIFT |  132u     ),
     VRLH_OPCODE    = (4u  << OPCODE_SHIFT |   68u     ),
@@ -1918,6 +1919,7 @@
   inline void vnor(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vor(      VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vxor(     VectorRegister d, VectorRegister a, VectorRegister b);
+  inline void vrld(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vrlb(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vrlw(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vrlh(     VectorRegister d, VectorRegister a, VectorRegister b);
diff --git a/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp b/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
index b4a7370..0f76435 100644
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
@@ -739,6 +739,7 @@
 inline void Assembler::vnor(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VNOR_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vor(     VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VOR_OPCODE      | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vxor(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VXOR_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
+inline void Assembler::vrld(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VRLD_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vrlb(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VRLB_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vrlw(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VRLW_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vrlh(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VRLH_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
diff --git a/hotspot/src/cpu/ppc/vm/relocInfo_ppc.cpp b/hotspot/src/cpu/ppc/vm/relocInfo_ppc.cpp
index 4f365a4..b48cba0 100644
--- a/hotspot/src/cpu/ppc/vm/relocInfo_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/relocInfo_ppc.cpp
@@ -62,7 +62,7 @@
       nativeMovConstReg_at(addr())->set_narrow_oop(no, code());
     }
   } else {
-    assert((address) (nativeMovConstReg_at(addr())->data()) == x, "data must match");
+    guarantee((address) (nativeMovConstReg_at(addr())->data()) == x, "data must match");
   }
 }
 
diff --git a/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp b/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
index ed292cb..325b527 100644
--- a/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
@@ -1961,6 +1961,434 @@
     return start;
   }
 
+  // Arguments for generated stub (little endian only):
+  //   R3_ARG1   - source byte array address
+  //   R4_ARG2   - destination byte array address
+  //   R5_ARG3   - round key array
+  address generate_aescrypt_encryptBlock() {
+    assert(UseAES, "need AES instructions and misaligned SSE support");
+    StubCodeMark mark(this, "StubRoutines", "aescrypt_encryptBlock");
+
+    address start = __ function_entry();
+
+    Label L_doLast;
+
+    Register from           = R3_ARG1;  // source array address
+    Register to             = R4_ARG2;  // destination array address
+    Register key            = R5_ARG3;  // round key array
+
+    Register keylen         = R8;
+    Register temp           = R9;
+    Register keypos         = R10;
+    Register hex            = R11;
+    Register fifteen        = R12;
+
+    VectorRegister vRet     = VR0;
+
+    VectorRegister vKey1    = VR1;
+    VectorRegister vKey2    = VR2;
+    VectorRegister vKey3    = VR3;
+    VectorRegister vKey4    = VR4;
+
+    VectorRegister fromPerm = VR5;
+    VectorRegister keyPerm  = VR6;
+    VectorRegister toPerm   = VR7;
+    VectorRegister fSplt    = VR8;
+
+    VectorRegister vTmp1    = VR9;
+    VectorRegister vTmp2    = VR10;
+    VectorRegister vTmp3    = VR11;
+    VectorRegister vTmp4    = VR12;
+
+    VectorRegister vLow     = VR13;
+    VectorRegister vHigh    = VR14;
+
+    __ li              (hex, 16);
+    __ li              (fifteen, 15);
+    __ vspltisb        (fSplt, 0x0f);
+
+    // load unaligned from[0-15] to vsRet
+    __ lvx             (vRet, from);
+    __ lvx             (vTmp1, fifteen, from);
+    __ lvsl            (fromPerm, from);
+    __ vxor            (fromPerm, fromPerm, fSplt);
+    __ vperm           (vRet, vRet, vTmp1, fromPerm);
+
+    // load keylen (44 or 52 or 60)
+    __ lwz             (keylen, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT), key);
+
+    // to load keys
+    __ lvsr            (keyPerm, key);
+    __ vxor            (vTmp2, vTmp2, vTmp2);
+    __ vspltisb        (vTmp2, -16);
+    __ vrld            (keyPerm, keyPerm, vTmp2);
+    __ vrld            (keyPerm, keyPerm, vTmp2);
+    __ vsldoi          (keyPerm, keyPerm, keyPerm, -8);
+
+    // load the 1st round key to vKey1
+    __ li              (keypos, 0);
+    __ lvx             (vKey1, keypos, key);
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey1, vTmp1, vKey1, keyPerm);
+
+    // 1st round
+    __ vxor (vRet, vRet, vKey1);
+
+    // load the 2nd round key to vKey1
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
+
+    // load the 3rd round key to vKey2
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
+
+    // load the 4th round key to vKey3
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey3, vTmp2, vTmp1, keyPerm);
+
+    // load the 5th round key to vKey4
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey4, vTmp1, vTmp2, keyPerm);
+
+    // 2nd - 5th rounds
+    __ vcipher (vRet, vRet, vKey1);
+    __ vcipher (vRet, vRet, vKey2);
+    __ vcipher (vRet, vRet, vKey3);
+    __ vcipher (vRet, vRet, vKey4);
+
+    // load the 6th round key to vKey1
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
+
+    // load the 7th round key to vKey2
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
+
+    // load the 8th round key to vKey3
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey3, vTmp2, vTmp1, keyPerm);
+
+    // load the 9th round key to vKey4
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey4, vTmp1, vTmp2, keyPerm);
+
+    // 6th - 9th rounds
+    __ vcipher (vRet, vRet, vKey1);
+    __ vcipher (vRet, vRet, vKey2);
+    __ vcipher (vRet, vRet, vKey3);
+    __ vcipher (vRet, vRet, vKey4);
+
+    // load the 10th round key to vKey1
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
+
+    // load the 11th round key to vKey2
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
+
+    // if all round keys are loaded, skip next 4 rounds
+    __ cmpwi           (CCR0, keylen, 44);
+    __ beq             (CCR0, L_doLast);
+
+    // 10th - 11th rounds
+    __ vcipher (vRet, vRet, vKey1);
+    __ vcipher (vRet, vRet, vKey2);
+
+    // load the 12th round key to vKey1
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
+
+    // load the 13th round key to vKey2
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
+
+    // if all round keys are loaded, skip next 2 rounds
+    __ cmpwi           (CCR0, keylen, 52);
+    __ beq             (CCR0, L_doLast);
+
+    // 12th - 13th rounds
+    __ vcipher (vRet, vRet, vKey1);
+    __ vcipher (vRet, vRet, vKey2);
+
+    // load the 14th round key to vKey1
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
+
+    // load the 15th round key to vKey2
+    __ addi            (keypos, keypos, 16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
+
+    __ bind(L_doLast);
+
+    // last two rounds
+    __ vcipher (vRet, vRet, vKey1);
+    __ vcipherlast (vRet, vRet, vKey2);
+
+    __ neg             (temp, to);
+    __ lvsr            (toPerm, temp);
+    __ vspltisb        (vTmp2, -1);
+    __ vxor            (vTmp1, vTmp1, vTmp1);
+    __ vperm           (vTmp2, vTmp2, vTmp1, toPerm);
+    __ vxor            (toPerm, toPerm, fSplt);
+    __ lvx             (vTmp1, to);
+    __ vperm           (vRet, vRet, vRet, toPerm);
+    __ vsel            (vTmp1, vTmp1, vRet, vTmp2);
+    __ lvx             (vTmp4, fifteen, to);
+    __ stvx            (vTmp1, to);
+    __ vsel            (vRet, vRet, vTmp4, vTmp2);
+    __ stvx            (vRet, fifteen, to);
+
+    __ blr();
+     return start;
+  }
+
+  // Arguments for generated stub (little endian only):
+  //   R3_ARG1   - source byte array address
+  //   R4_ARG2   - destination byte array address
+  //   R5_ARG3   - K (key) in little endian int array
+  address generate_aescrypt_decryptBlock() {
+    assert(UseAES, "need AES instructions and misaligned SSE support");
+    StubCodeMark mark(this, "StubRoutines", "aescrypt_decryptBlock");
+
+    address start = __ function_entry();
+
+    Label L_doLast;
+    Label L_do44;
+    Label L_do52;
+    Label L_do60;
+
+    Register from           = R3_ARG1;  // source array address
+    Register to             = R4_ARG2;  // destination array address
+    Register key            = R5_ARG3;  // round key array
+
+    Register keylen         = R8;
+    Register temp           = R9;
+    Register keypos         = R10;
+    Register hex            = R11;
+    Register fifteen        = R12;
+
+    VectorRegister vRet     = VR0;
+
+    VectorRegister vKey1    = VR1;
+    VectorRegister vKey2    = VR2;
+    VectorRegister vKey3    = VR3;
+    VectorRegister vKey4    = VR4;
+    VectorRegister vKey5    = VR5;
+
+    VectorRegister fromPerm = VR6;
+    VectorRegister keyPerm  = VR7;
+    VectorRegister toPerm   = VR8;
+    VectorRegister fSplt    = VR9;
+
+    VectorRegister vTmp1    = VR10;
+    VectorRegister vTmp2    = VR11;
+    VectorRegister vTmp3    = VR12;
+    VectorRegister vTmp4    = VR13;
+
+    VectorRegister vLow     = VR14;
+    VectorRegister vHigh    = VR15;
+
+    __ li              (hex, 16);
+    __ li              (fifteen, 15);
+    __ vspltisb        (fSplt, 0x0f);
+
+    // load unaligned from[0-15] to vsRet
+    __ lvx             (vRet, from);
+    __ lvx             (vTmp1, fifteen, from);
+    __ lvsl            (fromPerm, from);
+    __ vxor            (fromPerm, fromPerm, fSplt);
+    __ vperm           (vRet, vRet, vTmp1, fromPerm); // align [and byte swap in LE]
+
+    // load keylen (44 or 52 or 60)
+    __ lwz             (keylen, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT), key);
+
+    // to load keys
+    __ lvsr            (keyPerm, key);
+    __ vxor            (vTmp2, vTmp2, vTmp2);
+    __ vspltisb        (vTmp2, -16);
+    __ vrld            (keyPerm, keyPerm, vTmp2);
+    __ vrld            (keyPerm, keyPerm, vTmp2);
+    __ vsldoi          (keyPerm, keyPerm, keyPerm, -8);
+
+    __ cmpwi           (CCR0, keylen, 44);
+    __ beq             (CCR0, L_do44);
+
+    __ cmpwi           (CCR0, keylen, 52);
+    __ beq             (CCR0, L_do52);
+
+    // load the 15th round key to vKey11
+    __ li              (keypos, 240);
+    __ lvx             (vTmp1, keypos, key);
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp1, vTmp2, keyPerm);
+
+    // load the 14th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey2, vTmp2, vTmp1, keyPerm);
+
+    // load the 13th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey3, vTmp1, vTmp2, keyPerm);
+
+    // load the 12th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey4, vTmp2, vTmp1, keyPerm);
+
+    // load the 11th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey5, vTmp1, vTmp2, keyPerm);
+
+    // 1st - 5th rounds
+    __ vxor            (vRet, vRet, vKey1);
+    __ vncipher        (vRet, vRet, vKey2);
+    __ vncipher        (vRet, vRet, vKey3);
+    __ vncipher        (vRet, vRet, vKey4);
+    __ vncipher        (vRet, vRet, vKey5);
+
+    __ b               (L_doLast);
+
+    __ bind            (L_do52);
+
+    // load the 13th round key to vKey11
+    __ li              (keypos, 208);
+    __ lvx             (vTmp1, keypos, key);
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp1, vTmp2, keyPerm);
+
+    // load the 12th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey2, vTmp2, vTmp1, keyPerm);
+
+    // load the 11th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey3, vTmp1, vTmp2, keyPerm);
+
+    // 1st - 3rd rounds
+    __ vxor            (vRet, vRet, vKey1);
+    __ vncipher        (vRet, vRet, vKey2);
+    __ vncipher        (vRet, vRet, vKey3);
+
+    __ b               (L_doLast);
+
+    __ bind            (L_do44);
+
+    // load the 11th round key to vKey11
+    __ li              (keypos, 176);
+    __ lvx             (vTmp1, keypos, key);
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp1, vTmp2, keyPerm);
+
+    // 1st round
+    __ vxor            (vRet, vRet, vKey1);
+
+    __ bind            (L_doLast);
+
+    // load the 10th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
+
+    // load the 9th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
+
+    // load the 8th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey3, vTmp2, vTmp1, keyPerm);
+
+    // load the 7th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey4, vTmp1, vTmp2, keyPerm);
+
+    // load the 6th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey5, vTmp2, vTmp1, keyPerm);
+
+    // last 10th - 6th rounds
+    __ vncipher        (vRet, vRet, vKey1);
+    __ vncipher        (vRet, vRet, vKey2);
+    __ vncipher        (vRet, vRet, vKey3);
+    __ vncipher        (vRet, vRet, vKey4);
+    __ vncipher        (vRet, vRet, vKey5);
+
+    // load the 5th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey1, vTmp1, vTmp2, keyPerm);
+
+    // load the 4th round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey2, vTmp2, vTmp1, keyPerm);
+
+    // load the 3rd round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey3, vTmp1, vTmp2, keyPerm);
+
+    // load the 2nd round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp1, keypos, key);
+    __ vperm           (vKey4, vTmp2, vTmp1, keyPerm);
+
+    // load the 1st round key to vKey10
+    __ addi            (keypos, keypos, -16);
+    __ lvx             (vTmp2, keypos, key);
+    __ vperm           (vKey5, vTmp1, vTmp2, keyPerm);
+
+    // last 5th - 1th rounds
+    __ vncipher        (vRet, vRet, vKey1);
+    __ vncipher        (vRet, vRet, vKey2);
+    __ vncipher        (vRet, vRet, vKey3);
+    __ vncipher        (vRet, vRet, vKey4);
+    __ vncipherlast    (vRet, vRet, vKey5);
+
+    __ neg             (temp, to);
+    __ lvsr            (toPerm, temp);
+    __ vspltisb        (vTmp2, -1);
+    __ vxor            (vTmp1, vTmp1, vTmp1);
+    __ vperm           (vTmp2, vTmp2, vTmp1, toPerm);
+    __ vxor            (toPerm, toPerm, fSplt);
+    __ lvx             (vTmp1, to);
+    __ vperm           (vRet, vRet, vRet, toPerm);
+    __ vsel            (vTmp1, vTmp1, vRet, vTmp2);
+    __ lvx             (vTmp4, fifteen, to);
+    __ stvx            (vTmp1, to);
+    __ vsel            (vRet, vRet, vTmp4, vTmp2);
+    __ stvx            (vRet, fifteen, to);
+
+    __ blr();
+     return start;
+  }
+
   void generate_arraycopy_stubs() {
     // Note: the disjoint stubs must be generated first, some of
     // the conjoint stubs use them.
@@ -2083,10 +2511,6 @@
     // arraycopy stubs used by compilers
     generate_arraycopy_stubs();
 
-    if (UseAESIntrinsics) {
-      guarantee(!UseAESIntrinsics, "not yet implemented.");
-    }
-
     // Safefetch stubs.
     generate_safefetch("SafeFetch32", sizeof(int),     &StubRoutines::_safefetch32_entry,
                                                        &StubRoutines::_safefetch32_fault_pc,
@@ -2094,6 +2518,12 @@
     generate_safefetch("SafeFetchN", sizeof(intptr_t), &StubRoutines::_safefetchN_entry,
                                                        &StubRoutines::_safefetchN_fault_pc,
                                                        &StubRoutines::_safefetchN_continuation_pc);
+
+    if (UseAESIntrinsics) {
+      StubRoutines::_aescrypt_encryptBlock = generate_aescrypt_encryptBlock();
+      StubRoutines::_aescrypt_decryptBlock = generate_aescrypt_decryptBlock();
+    }
+
   }
 
  public:
diff --git a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
index 1f8375f..d8214a8 100644
--- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
@@ -102,7 +102,7 @@
   // Create and print feature-string.
   char buf[(num_features+1) * 16]; // Max 16 chars per feature.
   jio_snprintf(buf, sizeof(buf),
-               "ppc64%s%s%s%s%s%s%s%s",
+               "ppc64%s%s%s%s%s%s%s%s%s",
                (has_fsqrt()   ? " fsqrt"   : ""),
                (has_isel()    ? " isel"    : ""),
                (has_lxarxeh() ? " lxarxeh" : ""),
@@ -111,7 +111,8 @@
                (has_popcntb() ? " popcntb" : ""),
                (has_popcntw() ? " popcntw" : ""),
                (has_fcfids()  ? " fcfids"  : ""),
-               (has_vand()    ? " vand"    : "")
+               (has_vand()    ? " vand"    : ""),
+               (has_vcipher() ? " aes"     : "")
                // Make sure number of %s matches num_features!
               );
   _features_str = strdup(buf);
@@ -156,6 +157,28 @@
   }
 
   // The AES intrinsic stubs require AES instruction support.
+#if defined(VM_LITTLE_ENDIAN)
+  if (has_vcipher()) {
+    if (FLAG_IS_DEFAULT(UseAES)) {
+      UseAES = true;
+    }
+  } else if (UseAES) {
+    if (!FLAG_IS_DEFAULT(UseAES))
+      warning("AES instructions are not available on this CPU");
+    FLAG_SET_DEFAULT(UseAES, false);
+  }
+
+  if (UseAES && has_vcipher()) {
+    if (FLAG_IS_DEFAULT(UseAESIntrinsics)) {
+      UseAESIntrinsics = true;
+    }
+  } else if (UseAESIntrinsics) {
+    if (!FLAG_IS_DEFAULT(UseAESIntrinsics))
+      warning("AES intrinsics are not available on this CPU");
+    FLAG_SET_DEFAULT(UseAESIntrinsics, false);
+  }
+
+#else
   if (UseAES) {
     warning("AES instructions are not available on this CPU");
     FLAG_SET_DEFAULT(UseAES, false);
@@ -165,6 +188,7 @@
       warning("AES intrinsics are not available on this CPU");
     FLAG_SET_DEFAULT(UseAESIntrinsics, false);
   }
+#endif
 
   if (UseSHA) {
     warning("SHA instructions are not available on this CPU");
@@ -452,6 +476,7 @@
   a->popcntw(R7, R5);                          // code[7] -> popcntw
   a->fcfids(F3, F4);                           // code[8] -> fcfids
   a->vand(VR0, VR0, VR0);                      // code[9] -> vand
+  a->vcipher(VR0, VR1, VR2);                   // code[10] -> vcipher
   a->blr();
 
   // Emit function to set one cache line to zero. Emit function descriptor and get pointer to it.
@@ -495,6 +520,7 @@
   if (code[feature_cntr++]) features |= popcntw_m;
   if (code[feature_cntr++]) features |= fcfids_m;
   if (code[feature_cntr++]) features |= vand_m;
+  if (code[feature_cntr++]) features |= vcipher_m;
 
   // Print the detection code.
   if (PrintAssembly) {
diff --git a/hotspot/src/cpu/ppc/vm/vm_version_ppc.hpp b/hotspot/src/cpu/ppc/vm/vm_version_ppc.hpp
index 2bbfddd..d7839b4 100644
--- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.hpp
+++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.hpp
@@ -42,6 +42,7 @@
     fcfids,
     vand,
     dcba,
+    vcipher,
     num_features // last entry to count features
   };
   enum Feature_Flag_Set {
@@ -56,6 +57,7 @@
     fcfids_m              = (1 << fcfids ),
     vand_m                = (1 << vand   ),
     dcba_m                = (1 << dcba   ),
+    vcipher_m             = (1 << vcipher),
     all_features_m        = -1
   };
   static int  _features;
@@ -83,6 +85,7 @@
   static bool has_fcfids()  { return (_features & fcfids_m) != 0; }
   static bool has_vand()    { return (_features & vand_m) != 0; }
   static bool has_dcba()    { return (_features & dcba_m) != 0; }
+  static bool has_vcipher() { return (_features & vcipher_m) != 0; }
 
   static const char* cpu_features() { return _features_str; }
 
diff --git a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp
index d7396f6..4dfc1db 100644
--- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp
@@ -4261,6 +4261,7 @@
   assert(UseBlockZeroing && VM_Version::has_block_zeroing(), "only works with BIS zeroing");
   Register end = count;
   int cache_line_size = VM_Version::prefetch_data_size();
+  assert(cache_line_size > 0, "cache line size should be known for this code");
   // Minimum count when BIS zeroing can be used since
   // it needs membar which is expensive.
   int block_zero_size  = MAX2(cache_line_size*3, (int)BlockZeroingLowLimit);
diff --git a/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp b/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp
index f5ac37c..413cfe2 100644
--- a/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp
@@ -64,7 +64,7 @@
   masm.patchable_sethi(x, destreg);
   int len = buffer - masm.pc();
   for (int i = 0; i < len; i++) {
-    assert(instaddr[i] == buffer[i], "instructions must match");
+    guarantee(instaddr[i] == buffer[i], "instructions must match");
   }
 }
 
diff --git a/hotspot/src/cpu/sparc/vm/relocInfo_sparc.cpp b/hotspot/src/cpu/sparc/vm/relocInfo_sparc.cpp
index e132c42..4900e14 100644
--- a/hotspot/src/cpu/sparc/vm/relocInfo_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/relocInfo_sparc.cpp
@@ -83,7 +83,7 @@
     inst &= ~Assembler::simm(    -1, 13);
     inst |=  Assembler::simm(simm13, 13);
     if (verify_only) {
-      assert(ip->long_at(0) == inst, "instructions must match");
+      guarantee(ip->long_at(0) == inst, "instructions must match");
     } else {
       ip->set_long_at(0, inst);
     }
@@ -101,15 +101,15 @@
       inst &= ~Assembler::hi22(-1);
       inst |=  Assembler::hi22((intptr_t)np);
       if (verify_only) {
-        assert(ip->long_at(0) == inst, "instructions must match");
+        guarantee(ip->long_at(0) == inst, "instructions must match");
       } else {
         ip->set_long_at(0, inst);
       }
       inst2 = ip->long_at( NativeInstruction::nop_instruction_size );
       guarantee(Assembler::inv_op(inst2)==Assembler::arith_op, "arith op");
       if (verify_only) {
-        assert(ip->long_at(NativeInstruction::nop_instruction_size) == NativeInstruction::set_data32_simm13( inst2, (intptr_t)np),
-               "instructions must match");
+        guarantee(ip->long_at(NativeInstruction::nop_instruction_size) == NativeInstruction::set_data32_simm13( inst2, (intptr_t)np),
+                  "instructions must match");
       } else {
         ip->set_long_at(NativeInstruction::nop_instruction_size, NativeInstruction::set_data32_simm13( inst2, (intptr_t)np));
       }
@@ -126,7 +126,7 @@
     inst |=  Assembler::hi22((intptr_t)x);
     // (ignore offset; it doesn't play into the sethi)
     if (verify_only) {
-      assert(ip->long_at(0) == inst, "instructions must match");
+      guarantee(ip->long_at(0) == inst, "instructions must match");
     } else {
       ip->set_long_at(0, inst);
     }
diff --git a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp
index 72e98c6..15e6f33 100644
--- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp
@@ -74,7 +74,7 @@
     AllocatePrefetchDistance = AllocatePrefetchStepSize;
   }
 
-  if (AllocatePrefetchStyle == 3 && !has_blk_init()) {
+  if (AllocatePrefetchStyle == 3 && (!has_blk_init() || cache_line_size <= 0)) {
     warning("BIS instructions are not available on this CPU");
     FLAG_SET_DEFAULT(AllocatePrefetchStyle, 1);
   }
@@ -138,7 +138,7 @@
       FLAG_SET_DEFAULT(InteriorEntryAlignment, 4);
     }
     if (is_niagara_plus()) {
-      if (has_blk_init() && UseTLAB &&
+      if (has_blk_init() && (cache_line_size > 0) && UseTLAB &&
           FLAG_IS_DEFAULT(AllocatePrefetchInstr)) {
         // Use BIS instruction for TLAB allocation prefetch.
         FLAG_SET_ERGO(intx, AllocatePrefetchInstr, 1);
@@ -236,7 +236,7 @@
   assert((OptoLoopAlignment % relocInfo::addr_unit()) == 0, "alignment is not a multiple of NOP size");
 
   char buf[512];
-  jio_snprintf(buf, sizeof(buf), "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
+  jio_snprintf(buf, sizeof(buf), "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
                (has_v9() ? ", v9" : (has_v8() ? ", v8" : "")),
                (has_hardware_popc() ? ", popc" : ""),
                (has_vis1() ? ", vis1" : ""),
@@ -249,6 +249,7 @@
                (has_sha256() ? ", sha256" : ""),
                (has_sha512() ? ", sha512" : ""),
                (is_ultra3() ? ", ultra3" : ""),
+               (has_sparc5_instr() ? ", sparc5" : ""),
                (is_sun4v() ? ", sun4v" : ""),
                (is_niagara_plus() ? ", niagara_plus" : (is_niagara() ? ", niagara" : "")),
                (is_sparc64() ? ", sparc64" : ""),
@@ -364,6 +365,7 @@
 
 #ifndef PRODUCT
   if (PrintMiscellaneous && Verbose) {
+    tty->print_cr("L1 data cache line size: %u", L1_data_cache_line_size());
     tty->print_cr("L2 data cache line size: %u", L2_data_cache_line_size());
     tty->print("Allocation");
     if (AllocatePrefetchStyle <= 0) {
@@ -447,9 +449,10 @@
 
 unsigned int VM_Version::calc_parallel_worker_threads() {
   unsigned int result;
-  if (is_M_series()) {
-    // for now, use same gc thread calculation for M-series as for niagara-plus
-    // in future, we may want to tweak parameters for nof_parallel_worker_thread
+  if (is_M_series() || is_S_series()) {
+    // for now, use same gc thread calculation for M-series and S-series as for
+    // niagara-plus. In future, we may want to tweak parameters for
+    // nof_parallel_worker_thread
     result = nof_parallel_worker_threads(5, 16, 8);
   } else if (is_niagara_plus()) {
     result = nof_parallel_worker_threads(5, 16, 8);
@@ -458,3 +461,37 @@
   }
   return result;
 }
+
+
+int VM_Version::parse_features(const char* implementation) {
+  int features = unknown_m;
+  // Convert to UPPER case before compare.
+  char* impl = os::strdup(implementation);
+
+  for (int i = 0; impl[i] != 0; i++)
+    impl[i] = (char)toupper((uint)impl[i]);
+
+  if (strstr(impl, "SPARC64") != NULL) {
+    features |= sparc64_family_m;
+  } else if (strstr(impl, "SPARC-M") != NULL) {
+    // M-series SPARC is based on T-series.
+    features |= (M_family_m | T_family_m);
+  } else if (strstr(impl, "SPARC-S") != NULL) {
+    // S-series SPARC is based on T-series.
+    features |= (S_family_m | T_family_m);
+  } else if (strstr(impl, "SPARC-T") != NULL) {
+    features |= T_family_m;
+    if (strstr(impl, "SPARC-T1") != NULL) {
+      features |= T1_model_m;
+    }
+  } else if (strstr(impl, "SUN4V-CPU") != NULL) {
+    // Generic or migration class LDOM
+    features |= T_family_m;
+  } else {
+#ifndef PRODUCT
+    warning("Failed to parse CPU implementation = '%s'", impl);
+#endif
+  }
+  os::free((void*)impl);
+  return features;
+}
diff --git a/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp b/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp
index c493100..bc9faef 100644
--- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp
+++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp
@@ -47,13 +47,14 @@
     cbcond_instructions  = 13,
     sparc64_family       = 14,
     M_family             = 15,
-    T_family             = 16,
-    T1_model             = 17,
-    sparc5_instructions  = 18,
-    aes_instructions     = 19,
-    sha1_instruction     = 20,
-    sha256_instruction   = 21,
-    sha512_instruction   = 22
+    S_family             = 16,
+    T_family             = 17,
+    T1_model             = 18,
+    sparc5_instructions  = 19,
+    aes_instructions     = 20,
+    sha1_instruction     = 21,
+    sha256_instruction   = 22,
+    sha512_instruction   = 23
   };
 
   enum Feature_Flag_Set {
@@ -76,6 +77,7 @@
     cbcond_instructions_m   = 1 << cbcond_instructions,
     sparc64_family_m        = 1 << sparc64_family,
     M_family_m              = 1 << M_family,
+    S_family_m              = 1 << S_family,
     T_family_m              = 1 << T_family,
     T1_model_m              = 1 << T1_model,
     sparc5_instructions_m   = 1 << sparc5_instructions,
@@ -105,6 +107,7 @@
 
   // Returns true if the platform is in the niagara line (T series)
   static bool is_M_family(int features) { return (features & M_family_m) != 0; }
+  static bool is_S_family(int features) { return (features & S_family_m) != 0; }
   static bool is_T_family(int features) { return (features & T_family_m) != 0; }
   static bool is_niagara() { return is_T_family(_features); }
 #ifdef ASSERT
@@ -119,7 +122,7 @@
   static bool is_T1_model(int features) { return is_T_family(features) && ((features & T1_model_m) != 0); }
 
   static int maximum_niagara1_processor_count() { return 32; }
-
+  static int parse_features(const char* implementation);
 public:
   // Initialization
   static void initialize();
@@ -152,6 +155,7 @@
   static bool is_niagara_plus()         { return is_T_family(_features) && !is_T1_model(_features); }
 
   static bool is_M_series()             { return is_M_family(_features); }
+  static bool is_S_series()             { return is_S_family(_features); }
   static bool is_T4()                   { return is_T_family(_features) && has_cbcond(); }
   static bool is_T7()                   { return is_T_family(_features) && has_sparc5_instr(); }
 
diff --git a/hotspot/src/cpu/x86/vm/relocInfo_x86.cpp b/hotspot/src/cpu/x86/vm/relocInfo_x86.cpp
index 14868cb..918b6f2 100644
--- a/hotspot/src/cpu/x86/vm/relocInfo_x86.cpp
+++ b/hotspot/src/cpu/x86/vm/relocInfo_x86.cpp
@@ -40,7 +40,7 @@
          which == Assembler::imm_operand, "format unpacks ok");
   if (which == Assembler::imm_operand) {
     if (verify_only) {
-      assert(*pd_address_in_code() == x, "instructions must match");
+      guarantee(*pd_address_in_code() == x, "instructions must match");
     } else {
       *pd_address_in_code() = x;
     }
@@ -49,13 +49,13 @@
     // both compressed oops and compressed classes look the same
     if (Universe::heap()->is_in_reserved((oop)x)) {
     if (verify_only) {
-      assert(*(uint32_t*) disp == oopDesc::encode_heap_oop((oop)x), "instructions must match");
+      guarantee(*(uint32_t*) disp == oopDesc::encode_heap_oop((oop)x), "instructions must match");
     } else {
       *(int32_t*) disp = oopDesc::encode_heap_oop((oop)x);
     }
   } else {
       if (verify_only) {
-        assert(*(uint32_t*) disp == Klass::encode_klass((Klass*)x), "instructions must match");
+        guarantee(*(uint32_t*) disp == Klass::encode_klass((Klass*)x), "instructions must match");
       } else {
         *(int32_t*) disp = Klass::encode_klass((Klass*)x);
       }
@@ -66,14 +66,14 @@
     address disp = Assembler::locate_operand(ip, which);
     address next_ip = Assembler::locate_next_instruction(ip);
     if (verify_only) {
-      assert(*(int32_t*) disp == (x - next_ip), "instructions must match");
+      guarantee(*(int32_t*) disp == (x - next_ip), "instructions must match");
     } else {
       *(int32_t*) disp = x - next_ip;
     }
   }
 #else
   if (verify_only) {
-    assert(*pd_address_in_code() == (x + o), "instructions must match");
+    guarantee(*pd_address_in_code() == (x + o), "instructions must match");
   } else {
     *pd_address_in_code() = x + o;
   }
diff --git a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp
index 28aa48e..fd0a68d 100644
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp
@@ -406,6 +406,8 @@
   _stepping = 0;
   _cpuFeatures = 0;
   _logical_processors_per_package = 1;
+  // i486 internal cache is both I&D and has a 16-byte line size
+  _L1_data_cache_line_size = 16;
 
   if (!Use486InstrsOnly) {
     // Get raw processor info
@@ -424,6 +426,7 @@
       // Logical processors are only available on P4s and above,
       // and only if hyperthreading is available.
       _logical_processors_per_package = logical_processor_count();
+      _L1_data_cache_line_size = L1_line_size();
     }
   }
 
@@ -704,16 +707,16 @@
     UseMultiplyToLenIntrinsic = true;
   }
   if (FLAG_IS_DEFAULT(UseSquareToLenIntrinsic)) {
-    UseSquareToLenIntrinsic = false;
+    UseSquareToLenIntrinsic = true;
   }
   if (FLAG_IS_DEFAULT(UseMulAddIntrinsic)) {
-    UseMulAddIntrinsic = false;
+    UseMulAddIntrinsic = true;
   }
   if (FLAG_IS_DEFAULT(UseMontgomeryMultiplyIntrinsic)) {
-    UseMontgomeryMultiplyIntrinsic = false;
+    UseMontgomeryMultiplyIntrinsic = true;
   }
   if (FLAG_IS_DEFAULT(UseMontgomerySquareIntrinsic)) {
-    UseMontgomerySquareIntrinsic = false;
+    UseMontgomerySquareIntrinsic = true;
   }
 #else
   if (UseMultiplyToLenIntrinsic) {
@@ -1034,6 +1037,7 @@
   if (PrintMiscellaneous && Verbose) {
     tty->print_cr("Logical CPUs per core: %u",
                   logical_processors_per_package());
+    tty->print_cr("L1 data cache line size: %u", L1_data_cache_line_size());
     tty->print("UseSSE=%d", (int) UseSSE);
     if (UseAVX > 0) {
       tty->print("  UseAVX=%d", (int) UseAVX);
diff --git a/hotspot/src/cpu/x86/vm/vm_version_x86.hpp b/hotspot/src/cpu/x86/vm/vm_version_x86.hpp
index 49c9dba..f018936 100644
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.hpp
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.hpp
@@ -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
@@ -595,7 +595,7 @@
     return (result == 0 ? 1 : result);
   }
 
-  static intx prefetch_data_size()  {
+  static intx L1_line_size()  {
     intx result = 0;
     if (is_intel()) {
       result = (_cpuid_info.dcp_cpuid4_ebx.bits.L1_line_size + 1);
@@ -607,6 +607,10 @@
     return result;
   }
 
+  static intx prefetch_data_size()  {
+    return L1_line_size();
+  }
+
   //
   // Feature identification
   //
diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp
index ff47e0c..4a4cad5 100644
--- a/hotspot/src/os/linux/vm/os_linux.cpp
+++ b/hotspot/src/os/linux/vm/os_linux.cpp
@@ -2736,8 +2736,9 @@
 bool os::numa_topology_changed()   { return false; }
 
 size_t os::numa_get_groups_num() {
-  int max_node = Linux::numa_max_node();
-  return max_node > 0 ? max_node + 1 : 1;
+  // Return just the number of nodes in which it's possible to allocate memory
+  // (in numa terminology, configured nodes).
+  return Linux::numa_num_configured_nodes();
 }
 
 int os::numa_get_group_id() {
@@ -2751,11 +2752,33 @@
   return 0;
 }
 
-size_t os::numa_get_leaf_groups(int *ids, size_t size) {
-  for (size_t i = 0; i < size; i++) {
-    ids[i] = i;
+int os::Linux::get_existing_num_nodes() {
+  size_t node;
+  size_t highest_node_number = Linux::numa_max_node();
+  int num_nodes = 0;
+
+  // Get the total number of nodes in the system including nodes without memory.
+  for (node = 0; node <= highest_node_number; node++) {
+    if (isnode_in_existing_nodes(node)) {
+      num_nodes++;
+    }
   }
-  return size;
+  return num_nodes;
+}
+
+size_t os::numa_get_leaf_groups(int *ids, size_t size) {
+  size_t highest_node_number = Linux::numa_max_node();
+  size_t i = 0;
+
+  // Map all node ids in which is possible to allocate memory. Also nodes are
+  // not always consecutively available, i.e. available from 0 to the highest
+  // node number.
+  for (size_t node = 0; node <= highest_node_number; node++) {
+    if (Linux::isnode_in_configured_nodes(node)) {
+      ids[i++] = node;
+    }
+  }
+  return i;
 }
 
 bool os::get_page_info(char *start, page_info* info) {
@@ -2825,18 +2848,28 @@
                                            libnuma_dlsym(handle, "numa_node_to_cpus")));
       set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
                                        libnuma_dlsym(handle, "numa_max_node")));
+      set_numa_num_configured_nodes(CAST_TO_FN_PTR(numa_num_configured_nodes_func_t,
+                                                   libnuma_dlsym(handle, "numa_num_configured_nodes")));
       set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
                                         libnuma_dlsym(handle, "numa_available")));
       set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
                                             libnuma_dlsym(handle, "numa_tonode_memory")));
       set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
-                                            libnuma_dlsym(handle, "numa_interleave_memory")));
+                                                libnuma_dlsym(handle, "numa_interleave_memory")));
       set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t,
-                                            libnuma_dlsym(handle, "numa_set_bind_policy")));
-
+                                              libnuma_dlsym(handle, "numa_set_bind_policy")));
+      set_numa_bitmask_isbitset(CAST_TO_FN_PTR(numa_bitmask_isbitset_func_t,
+                                               libnuma_dlsym(handle, "numa_bitmask_isbitset")));
+      set_numa_distance(CAST_TO_FN_PTR(numa_distance_func_t,
+                                       libnuma_dlsym(handle, "numa_distance")));
 
       if (numa_available() != -1) {
         set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
+        set_numa_all_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_all_nodes_ptr"));
+        set_numa_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_nodes_ptr"));
+        // Create an index -> node mapping, since nodes are not always consecutive
+        _nindex_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
+        rebuild_nindex_to_node_map();
         // Create a cpu -> node mapping
         _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
         rebuild_cpu_to_node_map();
@@ -2847,6 +2880,17 @@
   return false;
 }
 
+void os::Linux::rebuild_nindex_to_node_map() {
+  int highest_node_number = Linux::numa_max_node();
+
+  nindex_to_node()->clear();
+  for (int node = 0; node <= highest_node_number; node++) {
+    if (Linux::isnode_in_existing_nodes(node)) {
+      nindex_to_node()->append(node);
+    }
+  }
+}
+
 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
 // The table is later used in get_node_by_cpu().
 void os::Linux::rebuild_cpu_to_node_map() {
@@ -2859,23 +2903,53 @@
                               // in the library.
   const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
 
-  size_t cpu_num = os::active_processor_count();
+  size_t cpu_num = processor_count();
   size_t cpu_map_size = NCPUS / BitsPerCLong;
   size_t cpu_map_valid_size =
     MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
 
   cpu_to_node()->clear();
   cpu_to_node()->at_grow(cpu_num - 1);
-  size_t node_num = numa_get_groups_num();
 
+  size_t node_num = get_existing_num_nodes();
+
+  int distance = 0;
+  int closest_distance = INT_MAX;
+  int closest_node = 0;
   unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
   for (size_t i = 0; i < node_num; i++) {
-    if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
+    // Check if node is configured (not a memory-less node). If it is not, find
+    // the closest configured node.
+    if (!isnode_in_configured_nodes(nindex_to_node()->at(i))) {
+      closest_distance = INT_MAX;
+      // Check distance from all remaining nodes in the system. Ignore distance
+      // from itself and from another non-configured node.
+      for (size_t m = 0; m < node_num; m++) {
+        if (m != i && isnode_in_configured_nodes(nindex_to_node()->at(m))) {
+          distance = numa_distance(nindex_to_node()->at(i), nindex_to_node()->at(m));
+          // If a closest node is found, update. There is always at least one
+          // configured node in the system so there is always at least one node
+          // close.
+          if (distance != 0 && distance < closest_distance) {
+            closest_distance = distance;
+            closest_node = nindex_to_node()->at(m);
+          }
+        }
+      }
+     } else {
+       // Current node is already a configured node.
+       closest_node = nindex_to_node()->at(i);
+     }
+
+    // Get cpus from the original node and map them to the closest node. If node
+    // is a configured node (not a memory-less node), then original node and
+    // closest node are the same.
+    if (numa_node_to_cpus(nindex_to_node()->at(i), cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
       for (size_t j = 0; j < cpu_map_valid_size; j++) {
         if (cpu_map[j] != 0) {
           for (size_t k = 0; k < BitsPerCLong; k++) {
             if (cpu_map[j] & (1UL << k)) {
-              cpu_to_node()->at_put(j * BitsPerCLong + k, i);
+              cpu_to_node()->at_put(j * BitsPerCLong + k, closest_node);
             }
           }
         }
@@ -2893,14 +2967,20 @@
 }
 
 GrowableArray<int>* os::Linux::_cpu_to_node;
+GrowableArray<int>* os::Linux::_nindex_to_node;
 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
+os::Linux::numa_num_configured_nodes_func_t os::Linux::_numa_num_configured_nodes;
 os::Linux::numa_available_func_t os::Linux::_numa_available;
 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
 os::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy;
+os::Linux::numa_bitmask_isbitset_func_t os::Linux::_numa_bitmask_isbitset;
+os::Linux::numa_distance_func_t os::Linux::_numa_distance;
 unsigned long* os::Linux::_numa_all_nodes;
+struct bitmask* os::Linux::_numa_all_nodes_ptr;
+struct bitmask* os::Linux::_numa_nodes_ptr;
 
 bool os::pd_uncommit_memory(char* addr, size_t size) {
   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
diff --git a/hotspot/src/os/linux/vm/os_linux.hpp b/hotspot/src/os/linux/vm/os_linux.hpp
index e72cca1..b8c9343 100644
--- a/hotspot/src/os/linux/vm/os_linux.hpp
+++ b/hotspot/src/os/linux/vm/os_linux.hpp
@@ -67,6 +67,7 @@
   static bool _supports_fast_thread_cpu_time;
 
   static GrowableArray<int>* _cpu_to_node;
+  static GrowableArray<int>* _nindex_to_node;
 
  protected:
 
@@ -94,7 +95,9 @@
   static void set_is_floating_stack()         { _is_floating_stack = true; }
 
   static void rebuild_cpu_to_node_map();
+  static void rebuild_nindex_to_node_map();
   static GrowableArray<int>* cpu_to_node()    { return _cpu_to_node; }
+  static GrowableArray<int>* nindex_to_node()  { return _nindex_to_node; }
 
   static size_t find_large_page_size();
   static size_t setup_large_page_size();
@@ -243,28 +246,41 @@
   typedef int (*sched_getcpu_func_t)(void);
   typedef int (*numa_node_to_cpus_func_t)(int node, unsigned long *buffer, int bufferlen);
   typedef int (*numa_max_node_func_t)(void);
+  typedef int (*numa_num_configured_nodes_func_t)(void);
   typedef int (*numa_available_func_t)(void);
   typedef int (*numa_tonode_memory_func_t)(void *start, size_t size, int node);
   typedef void (*numa_interleave_memory_func_t)(void *start, size_t size, unsigned long *nodemask);
   typedef void (*numa_set_bind_policy_func_t)(int policy);
+  typedef int (*numa_bitmask_isbitset_func_t)(struct bitmask *bmp, unsigned int n);
+  typedef int (*numa_distance_func_t)(int node1, int node2);
 
   static sched_getcpu_func_t _sched_getcpu;
   static numa_node_to_cpus_func_t _numa_node_to_cpus;
   static numa_max_node_func_t _numa_max_node;
+  static numa_num_configured_nodes_func_t _numa_num_configured_nodes;
   static numa_available_func_t _numa_available;
   static numa_tonode_memory_func_t _numa_tonode_memory;
   static numa_interleave_memory_func_t _numa_interleave_memory;
   static numa_set_bind_policy_func_t _numa_set_bind_policy;
+  static numa_bitmask_isbitset_func_t _numa_bitmask_isbitset;
+  static numa_distance_func_t _numa_distance;
   static unsigned long* _numa_all_nodes;
+  static struct bitmask* _numa_all_nodes_ptr;
+  static struct bitmask* _numa_nodes_ptr;
 
   static void set_sched_getcpu(sched_getcpu_func_t func) { _sched_getcpu = func; }
   static void set_numa_node_to_cpus(numa_node_to_cpus_func_t func) { _numa_node_to_cpus = func; }
   static void set_numa_max_node(numa_max_node_func_t func) { _numa_max_node = func; }
+  static void set_numa_num_configured_nodes(numa_num_configured_nodes_func_t func) { _numa_num_configured_nodes = func; }
   static void set_numa_available(numa_available_func_t func) { _numa_available = func; }
   static void set_numa_tonode_memory(numa_tonode_memory_func_t func) { _numa_tonode_memory = func; }
   static void set_numa_interleave_memory(numa_interleave_memory_func_t func) { _numa_interleave_memory = func; }
   static void set_numa_set_bind_policy(numa_set_bind_policy_func_t func) { _numa_set_bind_policy = func; }
+  static void set_numa_bitmask_isbitset(numa_bitmask_isbitset_func_t func) { _numa_bitmask_isbitset = func; }
+  static void set_numa_distance(numa_distance_func_t func) { _numa_distance = func; }
   static void set_numa_all_nodes(unsigned long* ptr) { _numa_all_nodes = ptr; }
+  static void set_numa_all_nodes_ptr(struct bitmask **ptr) { _numa_all_nodes_ptr = *ptr; }
+  static void set_numa_nodes_ptr(struct bitmask **ptr) { _numa_nodes_ptr = *ptr; }
   static int sched_getcpu_syscall(void);
 public:
   static int sched_getcpu()  { return _sched_getcpu != NULL ? _sched_getcpu() : -1; }
@@ -272,6 +288,9 @@
     return _numa_node_to_cpus != NULL ? _numa_node_to_cpus(node, buffer, bufferlen) : -1;
   }
   static int numa_max_node() { return _numa_max_node != NULL ? _numa_max_node() : -1; }
+  static int numa_num_configured_nodes() {
+    return _numa_num_configured_nodes != NULL ? _numa_num_configured_nodes() : -1;
+  }
   static int numa_available() { return _numa_available != NULL ? _numa_available() : -1; }
   static int numa_tonode_memory(void *start, size_t size, int node) {
     return _numa_tonode_memory != NULL ? _numa_tonode_memory(start, size, node) : -1;
@@ -286,7 +305,25 @@
       _numa_set_bind_policy(policy);
     }
   }
+  static int numa_distance(int node1, int node2) {
+    return _numa_distance != NULL ? _numa_distance(node1, node2) : -1;
+  }
   static int get_node_by_cpu(int cpu_id);
+  static int get_existing_num_nodes();
+  // Check if numa node is configured (non-zero memory node).
+  static bool isnode_in_configured_nodes(unsigned int n) {
+    if (_numa_bitmask_isbitset != NULL && _numa_all_nodes_ptr != NULL) {
+      return _numa_bitmask_isbitset(_numa_all_nodes_ptr, n);
+    } else
+      return 0;
+  }
+  // Check if numa node exists in the system (including zero memory nodes).
+  static bool isnode_in_existing_nodes(unsigned int n) {
+    if (_numa_bitmask_isbitset != NULL && _numa_nodes_ptr != NULL) {
+      return _numa_bitmask_isbitset(_numa_nodes_ptr, n);
+    } else
+      return 0;
+  }
 };
 
 
diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp b/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp
index 4775be2..0e1b7b3 100644
--- a/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp
@@ -262,6 +262,7 @@
 
 // We need to keep these here as long as we have to build on Solaris
 // versions before 10.
+
 #ifndef SI_ARCHITECTURE_32
 #define SI_ARCHITECTURE_32      516     /* basic 32-bit SI_ARCHITECTURE */
 #endif
@@ -270,231 +271,233 @@
 #define SI_ARCHITECTURE_64      517     /* basic 64-bit SI_ARCHITECTURE */
 #endif
 
-static void do_sysinfo(int si, const char* string, int* features, int mask) {
-  char   tmp;
-  size_t bufsize = sysinfo(si, &tmp, 1);
+#ifndef SI_CPUBRAND
+#define SI_CPUBRAND             523     /* return cpu brand string */
+#endif
 
-  // All SI defines used below must be supported.
-  guarantee(bufsize != -1, "must be supported");
+class Sysinfo {
+  char* _string;
+public:
+  Sysinfo(int si) : _string(NULL) {
+    char   tmp;
+    size_t bufsize = sysinfo(si, &tmp, 1);
 
-  char* buf = (char*) malloc(bufsize);
+    if (bufsize != -1) {
+      char* buf = (char*) os::malloc(bufsize, mtInternal);
+      if (buf != NULL) {
+        if (sysinfo(si, buf, bufsize) == bufsize) {
+          _string = buf;
+        } else {
+          os::free(buf);
+        }
+      }
+     }
+   }
 
-  if (buf == NULL)
-    return;
-
-  if (sysinfo(si, buf, bufsize) == bufsize) {
-    // Compare the string.
-    if (strcmp(buf, string) == 0) {
-      *features |= mask;
+  ~Sysinfo() {
+    if (_string != NULL) {
+      os::free(_string);
     }
   }
 
-  free(buf);
-}
+  const char* value() const {
+    return _string;
+  }
 
-int VM_Version::platform_features(int features) {
-  // getisax(2), SI_ARCHITECTURE_32, and SI_ARCHITECTURE_64 are
-  // supported on Solaris 10 and later.
-  if (os::Solaris::supports_getisax()) {
+  bool valid() const {
+    return _string != NULL;
+  }
 
-    // Check 32-bit architecture.
-    do_sysinfo(SI_ARCHITECTURE_32, "sparc", &features, v8_instructions_m);
+  bool match(const char* s) const {
+    return valid() ? strcmp(_string, s) == 0 : false;
+  }
 
-    // Check 64-bit architecture.
-    do_sysinfo(SI_ARCHITECTURE_64, "sparcv9", &features, generic_v9_m);
+  bool match_substring(const char* s) const {
+    return valid() ? strstr(_string, s) != NULL : false;
+  }
+};
 
-    // Extract valid instruction set extensions.
-    uint_t avs[2];
-    uint_t avn = os::Solaris::getisax(avs, 2);
-    assert(avn <= 2, "should return two or less av's");
-    uint_t av = avs[0];
+class Sysconf {
+  int _value;
+public:
+  Sysconf(int sc) : _value(-1) {
+    _value = sysconf(sc);
+  }
+  bool valid() const {
+    return _value != -1;
+  }
+  int value() const {
+    return _value;
+  }
+};
 
-#ifndef PRODUCT
-    if (PrintMiscellaneous && Verbose) {
-      tty->print("getisax(2) returned: " PTR32_FORMAT, av);
-      if (avn > 1) {
-        tty->print(", " PTR32_FORMAT, avs[1]);
-      }
-      tty->cr();
-    }
+
+#ifndef _SC_DCACHE_LINESZ
+#define _SC_DCACHE_LINESZ       508     /* Data cache line size */
 #endif
 
-    if (av & AV_SPARC_MUL32)  features |= hardware_mul32_m;
-    if (av & AV_SPARC_DIV32)  features |= hardware_div32_m;
-    if (av & AV_SPARC_FSMULD) features |= hardware_fsmuld_m;
-    if (av & AV_SPARC_V8PLUS) features |= v9_instructions_m;
-    if (av & AV_SPARC_POPC)   features |= hardware_popc_m;
-    if (av & AV_SPARC_VIS)    features |= vis1_instructions_m;
-    if (av & AV_SPARC_VIS2)   features |= vis2_instructions_m;
+#ifndef _SC_L2CACHE_LINESZ
+#define _SC_L2CACHE_LINESZ      527     /* Size of L2 cache line */
+#endif
+
+
+int VM_Version::platform_features(int features) {
+  assert(os::Solaris::supports_getisax(), "getisax() must be available");
+
+  // Check 32-bit architecture.
+  if (Sysinfo(SI_ARCHITECTURE_32).match("sparc")) {
+    features |= v8_instructions_m;
+  }
+
+  // Check 64-bit architecture.
+  if (Sysinfo(SI_ARCHITECTURE_64).match("sparcv9")) {
+    features |= generic_v9_m;
+  }
+
+  // Extract valid instruction set extensions.
+  uint_t avs[2];
+  uint_t avn = os::Solaris::getisax(avs, 2);
+  assert(avn <= 2, "should return two or less av's");
+  uint_t av = avs[0];
+
+#ifndef PRODUCT
+  if (PrintMiscellaneous && Verbose) {
+    tty->print("getisax(2) returned: " PTR32_FORMAT, av);
     if (avn > 1) {
-      uint_t av2 = avs[1];
+      tty->print(", " PTR32_FORMAT, avs[1]);
+    }
+    tty->cr();
+  }
+#endif
+
+  if (av & AV_SPARC_MUL32)  features |= hardware_mul32_m;
+  if (av & AV_SPARC_DIV32)  features |= hardware_div32_m;
+  if (av & AV_SPARC_FSMULD) features |= hardware_fsmuld_m;
+  if (av & AV_SPARC_V8PLUS) features |= v9_instructions_m;
+  if (av & AV_SPARC_POPC)   features |= hardware_popc_m;
+  if (av & AV_SPARC_VIS)    features |= vis1_instructions_m;
+  if (av & AV_SPARC_VIS2)   features |= vis2_instructions_m;
+  if (avn > 1) {
+    uint_t av2 = avs[1];
 #ifndef AV2_SPARC_SPARC5
 #define AV2_SPARC_SPARC5 0x00000008 /* The 29 new fp and sub instructions */
 #endif
-      if (av2 & AV2_SPARC_SPARC5)       features |= sparc5_instructions_m;
-    }
+    if (av2 & AV2_SPARC_SPARC5)       features |= sparc5_instructions_m;
+  }
 
-    // Next values are not defined before Solaris 10
-    // but Solaris 8 is used for jdk6 update builds.
+  // We only build on Solaris 10 and up, but some of the values below
+  // are not defined on all versions of Solaris 10, so we define them,
+  // if necessary.
 #ifndef AV_SPARC_ASI_BLK_INIT
 #define AV_SPARC_ASI_BLK_INIT 0x0080  /* ASI_BLK_INIT_xxx ASI */
 #endif
-    if (av & AV_SPARC_ASI_BLK_INIT) features |= blk_init_instructions_m;
+  if (av & AV_SPARC_ASI_BLK_INIT) features |= blk_init_instructions_m;
 
 #ifndef AV_SPARC_FMAF
 #define AV_SPARC_FMAF 0x0100        /* Fused Multiply-Add */
 #endif
-    if (av & AV_SPARC_FMAF)         features |= fmaf_instructions_m;
+  if (av & AV_SPARC_FMAF)         features |= fmaf_instructions_m;
 
 #ifndef AV_SPARC_FMAU
-#define    AV_SPARC_FMAU    0x0200  /* Unfused Multiply-Add */
+#define AV_SPARC_FMAU    0x0200  /* Unfused Multiply-Add */
 #endif
-    if (av & AV_SPARC_FMAU)         features |= fmau_instructions_m;
+  if (av & AV_SPARC_FMAU)         features |= fmau_instructions_m;
 
 #ifndef AV_SPARC_VIS3
-#define    AV_SPARC_VIS3    0x0400  /* VIS3 instruction set extensions */
+#define AV_SPARC_VIS3    0x0400  /* VIS3 instruction set extensions */
 #endif
-    if (av & AV_SPARC_VIS3)         features |= vis3_instructions_m;
+  if (av & AV_SPARC_VIS3)         features |= vis3_instructions_m;
 
 #ifndef AV_SPARC_CBCOND
 #define AV_SPARC_CBCOND 0x10000000  /* compare and branch instrs supported */
 #endif
-    if (av & AV_SPARC_CBCOND)       features |= cbcond_instructions_m;
+  if (av & AV_SPARC_CBCOND)       features |= cbcond_instructions_m;
 
 #ifndef AV_SPARC_AES
 #define AV_SPARC_AES 0x00020000  /* aes instrs supported */
 #endif
-    if (av & AV_SPARC_AES)       features |= aes_instructions_m;
+  if (av & AV_SPARC_AES)       features |= aes_instructions_m;
 
 #ifndef AV_SPARC_SHA1
 #define AV_SPARC_SHA1   0x00400000  /* sha1 instruction supported */
 #endif
-    if (av & AV_SPARC_SHA1)         features |= sha1_instruction_m;
+  if (av & AV_SPARC_SHA1)         features |= sha1_instruction_m;
 
 #ifndef AV_SPARC_SHA256
 #define AV_SPARC_SHA256 0x00800000  /* sha256 instruction supported */
 #endif
-    if (av & AV_SPARC_SHA256)       features |= sha256_instruction_m;
+  if (av & AV_SPARC_SHA256)       features |= sha256_instruction_m;
 
 #ifndef AV_SPARC_SHA512
 #define AV_SPARC_SHA512 0x01000000  /* sha512 instruction supported */
 #endif
-    if (av & AV_SPARC_SHA512)       features |= sha512_instruction_m;
-
-  } else {
-    // getisax(2) failed, use the old legacy code.
-#ifndef PRODUCT
-    if (PrintMiscellaneous && Verbose)
-      tty->print_cr("getisax(2) is not supported.");
-#endif
-
-    char   tmp;
-    size_t bufsize = sysinfo(SI_ISALIST, &tmp, 1);
-    char*  buf     = (char*) malloc(bufsize);
-
-    if (buf != NULL) {
-      if (sysinfo(SI_ISALIST, buf, bufsize) == bufsize) {
-        // Figure out what kind of sparc we have
-        char *sparc_string = strstr(buf, "sparc");
-        if (sparc_string != NULL) {              features |= v8_instructions_m;
-          if (sparc_string[5] == 'v') {
-            if (sparc_string[6] == '8') {
-              if (sparc_string[7] == '-') {      features |= hardware_mul32_m;
-                                                 features |= hardware_div32_m;
-              } else if (sparc_string[7] == 'p') features |= generic_v9_m;
-              else                               features |= generic_v8_m;
-            } else if (sparc_string[6] == '9')   features |= generic_v9_m;
-          }
-        }
-
-        // Check for visualization instructions
-        char *vis = strstr(buf, "vis");
-        if (vis != NULL) {                       features |= vis1_instructions_m;
-          if (vis[3] == '2')                     features |= vis2_instructions_m;
-        }
-      }
-      free(buf);
-    }
-  }
+  if (av & AV_SPARC_SHA512)       features |= sha512_instruction_m;
 
   // Determine the machine type.
-  do_sysinfo(SI_MACHINE, "sun4v", &features, sun4v_m);
-
-  {
-    // Using kstat to determine the machine type.
-    kstat_ctl_t* kc = kstat_open();
-    kstat_t* ksp = kstat_lookup(kc, (char*)"cpu_info", -1, NULL);
-    const char* implementation = "UNKNOWN";
-    if (ksp != NULL) {
-      if (kstat_read(kc, ksp, NULL) != -1 && ksp->ks_data != NULL) {
-        kstat_named_t* knm = (kstat_named_t *)ksp->ks_data;
-        for (int i = 0; i < ksp->ks_ndata; i++) {
-          if (strcmp((const char*)&(knm[i].name),"implementation") == 0) {
-#ifndef KSTAT_DATA_STRING
-#define KSTAT_DATA_STRING   9
-#endif
-            if (knm[i].data_type == KSTAT_DATA_CHAR) {
-              // VM is running on Solaris 8 which does not have value.str.
-              implementation = &(knm[i].value.c[0]);
-            } else if (knm[i].data_type == KSTAT_DATA_STRING) {
-              // VM is running on Solaris 10.
-#ifndef KSTAT_NAMED_STR_PTR
-              // Solaris 8 was used to build VM, define the structure it misses.
-              struct str_t {
-                union {
-                  char *ptr;     /* NULL-term string */
-                  char __pad[8]; /* 64-bit padding */
-                } addr;
-                uint32_t len;    /* # bytes for strlen + '\0' */
-              };
-#define KSTAT_NAMED_STR_PTR(knptr) (( (str_t*)&((knptr)->value) )->addr.ptr)
-#endif
-              implementation = KSTAT_NAMED_STR_PTR(&knm[i]);
-            }
-#ifndef PRODUCT
-            if (PrintMiscellaneous && Verbose) {
-              tty->print_cr("cpu_info.implementation: %s", implementation);
-            }
-#endif
-            // Convert to UPPER case before compare.
-            char* impl = strdup(implementation);
-
-            for (int i = 0; impl[i] != 0; i++)
-              impl[i] = (char)toupper((uint)impl[i]);
-            if (strstr(impl, "SPARC64") != NULL) {
-              features |= sparc64_family_m;
-            } else if (strstr(impl, "SPARC-M") != NULL) {
-              // M-series SPARC is based on T-series.
-              features |= (M_family_m | T_family_m);
-            } else if (strstr(impl, "SPARC-T") != NULL) {
-              features |= T_family_m;
-              if (strstr(impl, "SPARC-T1") != NULL) {
-                features |= T1_model_m;
-              }
-            } else {
-              if (strstr(impl, "SPARC") == NULL) {
-#ifndef PRODUCT
-                // kstat on Solaris 8 virtual machines (branded zones)
-                // returns "(unsupported)" implementation.
-                warning("kstat cpu_info implementation = '%s', should contain SPARC", impl);
-#endif
-                implementation = "SPARC";
-              }
-            }
-            free((void*)impl);
-            break;
-          }
-        } // for(
-      }
-    }
-    assert(strcmp(implementation, "UNKNOWN") != 0,
-           "unknown cpu info (changed kstat interface?)");
-    kstat_close(kc);
+  if (Sysinfo(SI_MACHINE).match("sun4v")) {
+    features |= sun4v_m;
   }
 
-  // Figure out cache line sizes using PICL
-  PICL picl((features & sparc64_family_m) != 0, (features & sun4v_m) != 0);
-  _L2_data_cache_line_size = picl.L2_data_cache_line_size();
+  // If SI_CPUBRAND works, that means Solaris 12 API to get the cache line sizes
+  // is available to us as well
+  Sysinfo cpu_info(SI_CPUBRAND);
+  bool use_solaris_12_api = cpu_info.valid();
+  const char* impl;
+  int impl_m = 0;
+  if (use_solaris_12_api) {
+    impl = cpu_info.value();
+#ifndef PRODUCT
+  if (PrintMiscellaneous && Verbose) {
+    tty->print_cr("Parsing CPU implementation from %s", impl);
+  }
+#endif
+    impl_m = parse_features(impl);
+  } else {
+    // Otherwise use kstat to determine the machine type.
+    kstat_ctl_t* kc = kstat_open();
+    if (kc != NULL) {
+      kstat_t* ksp = kstat_lookup(kc, (char*)"cpu_info", -1, NULL);
+      if (ksp != NULL) {
+        if (kstat_read(kc, ksp, NULL) != -1 && ksp->ks_data != NULL) {
+          kstat_named_t* knm = (kstat_named_t *)ksp->ks_data;
+          for (int i = 0; i < ksp->ks_ndata; i++) {
+            if (strcmp((const char*)&(knm[i].name), "implementation") == 0) {
+              impl = KSTAT_NAMED_STR_PTR(&knm[i]);
+#ifndef PRODUCT
+              if (PrintMiscellaneous && Verbose) {
+                tty->print_cr("Parsing CPU implementation from %s", impl);
+              }
+#endif
+              impl_m = parse_features(impl);
+              break;
+            }
+          }
+        }
+      }
+      kstat_close(kc);
+    }
+  }
+  assert(impl_m != 0, err_msg("Unknown CPU implementation %s", impl));
+  features |= impl_m;
 
+  bool is_sun4v = (features & sun4v_m) != 0;
+  if (use_solaris_12_api && is_sun4v) {
+    // If Solaris 12 API is supported and it's sun4v use sysconf() to get the cache line sizes
+    Sysconf l1_dcache_line_size(_SC_DCACHE_LINESZ);
+    if (l1_dcache_line_size.valid()) {
+      _L1_data_cache_line_size =  l1_dcache_line_size.value();
+    }
+
+    Sysconf l2_dcache_line_size(_SC_L2CACHE_LINESZ);
+    if (l2_dcache_line_size.valid()) {
+      _L2_data_cache_line_size = l2_dcache_line_size.value();
+    }
+  } else {
+    // Otherwise figure out the cache line sizes using PICL
+    bool is_fujitsu = (features & sparc64_family_m) != 0;
+    PICL picl(is_fujitsu, is_sun4v);
+    _L1_data_cache_line_size = picl.L1_data_cache_line_size();
+    _L2_data_cache_line_size = picl.L2_data_cache_line_size();
+  }
   return features;
 }
diff --git a/hotspot/src/share/vm/adlc/formssel.cpp b/hotspot/src/share/vm/adlc/formssel.cpp
index ffb13e7..36914d3 100644
--- a/hotspot/src/share/vm/adlc/formssel.cpp
+++ b/hotspot/src/share/vm/adlc/formssel.cpp
@@ -648,6 +648,7 @@
   if( strcmp(_matrule->_opType,"MemBarReleaseLock") == 0 ) return true;
   if( strcmp(_matrule->_opType,"MemBarAcquireLock") == 0 ) return true;
   if( strcmp(_matrule->_opType,"MemBarStoreStore") == 0 ) return true;
+  if( strcmp(_matrule->_opType,"MemBarVolatile") == 0 ) return true;
   if( strcmp(_matrule->_opType,"StoreFence") == 0 ) return true;
   if( strcmp(_matrule->_opType,"LoadFence") == 0 ) return true;
 
diff --git a/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp b/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp
index bba1452..b6d4180 100644
--- a/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp
+++ b/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp
@@ -1485,6 +1485,21 @@
   // Check to see whether we are inlining. If so, Return
   // instructions become Gotos to the continuation point.
   if (continuation() != NULL) {
+
+    int invoke_bci = state()->caller_state()->bci();
+
+    if (x != NULL) {
+      ciMethod* caller = state()->scope()->caller()->method();
+      Bytecodes::Code invoke_raw_bc = caller->raw_code_at_bci(invoke_bci);
+      if (invoke_raw_bc == Bytecodes::_invokehandle || invoke_raw_bc == Bytecodes::_invokedynamic) {
+        ciType* declared_ret_type = caller->get_declared_signature_at_bci(invoke_bci)->return_type();
+        if (declared_ret_type->is_klass() && x->exact_type() == NULL &&
+            x->declared_type() != declared_ret_type && declared_ret_type != compilation()->env()->Object_klass()) {
+          x = append(new TypeCast(declared_ret_type->as_klass(), x, copy_state_before()));
+        }
+      }
+    }
+
     assert(!method()->is_synchronized() || InlineSynchronizedMethods, "can not inline synchronized methods yet");
 
     if (compilation()->env()->dtrace_method_probes()) {
@@ -1508,7 +1523,6 @@
     // State at end of inlined method is the state of the caller
     // without the method parameters on stack, including the
     // return value, if any, of the inlined method on operand stack.
-    int invoke_bci = state()->caller_state()->bci();
     set_state(state()->caller_state()->copy_for_parsing());
     if (x != NULL) {
       state()->push(x->type(), x);
diff --git a/hotspot/src/share/vm/c1/c1_Instruction.cpp b/hotspot/src/share/vm/c1/c1_Instruction.cpp
index 99d00bd..fb206de 100644
--- a/hotspot/src/share/vm/c1/c1_Instruction.cpp
+++ b/hotspot/src/share/vm/c1/c1_Instruction.cpp
@@ -360,7 +360,8 @@
 }
 
 ciType* Invoke::declared_type() const {
-  ciType *t = _target->signature()->return_type();
+  ciSignature* declared_signature = state()->scope()->method()->get_declared_signature_at_bci(state()->bci());
+  ciType *t = declared_signature->return_type();
   assert(t->basic_type() != T_VOID, "need return value of void method?");
   return t;
 }
diff --git a/hotspot/src/share/vm/c1/c1_LIR.cpp b/hotspot/src/share/vm/c1/c1_LIR.cpp
index a6ba988..7608679 100644
--- a/hotspot/src/share/vm/c1/c1_LIR.cpp
+++ b/hotspot/src/share/vm/c1/c1_LIR.cpp
@@ -1516,6 +1516,17 @@
   append(c);
 }
 
+void LIR_List::null_check(LIR_Opr opr, CodeEmitInfo* info, bool deoptimize_on_null) {
+  if (deoptimize_on_null) {
+    // Emit an explicit null check and deoptimize if opr is null
+    CodeStub* deopt = new DeoptimizeStub(info);
+    cmp(lir_cond_equal, opr, LIR_OprFact::oopConst(NULL));
+    branch(lir_cond_equal, T_OBJECT, deopt);
+  } else {
+    // Emit an implicit null check
+    append(new LIR_Op1(lir_null_check, opr, info));
+  }
+}
 
 void LIR_List::cas_long(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value,
                         LIR_Opr t1, LIR_Opr t2, LIR_Opr result) {
diff --git a/hotspot/src/share/vm/c1/c1_LIR.hpp b/hotspot/src/share/vm/c1/c1_LIR.hpp
index 19acfb3..5f4ee0a 100644
--- a/hotspot/src/share/vm/c1/c1_LIR.hpp
+++ b/hotspot/src/share/vm/c1/c1_LIR.hpp
@@ -2153,7 +2153,7 @@
   void   pack64(LIR_Opr src, LIR_Opr dst) { append(new LIR_Op1(lir_pack64,   src, dst, T_LONG, lir_patch_none, NULL)); }
   void unpack64(LIR_Opr src, LIR_Opr dst) { append(new LIR_Op1(lir_unpack64, src, dst, T_LONG, lir_patch_none, NULL)); }
 
-  void null_check(LIR_Opr opr, CodeEmitInfo* info)         { append(new LIR_Op1(lir_null_check, opr, info)); }
+  void null_check(LIR_Opr opr, CodeEmitInfo* info, bool deoptimize_on_null = false);
   void throw_exception(LIR_Opr exceptionPC, LIR_Opr exceptionOop, CodeEmitInfo* info) {
     append(new LIR_Op2(lir_throw, exceptionPC, exceptionOop, LIR_OprFact::illegalOpr, info));
   }
diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
index ed937fe..7d23f8c 100644
--- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
+++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
@@ -1700,8 +1700,10 @@
   if (x->needs_null_check() &&
       (needs_patching ||
        MacroAssembler::needs_explicit_null_check(x->offset()))) {
-    // emit an explicit null check because the offset is too large
-    __ null_check(object.result(), new CodeEmitInfo(info));
+    // Emit an explicit null check because the offset is too large.
+    // If the class is not loaded and the object is NULL, we need to deoptimize to throw a
+    // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
+    __ null_check(object.result(), new CodeEmitInfo(info), /* deoptimize */ needs_patching);
   }
 
   LIR_Address* address;
@@ -1785,8 +1787,10 @@
       obj = new_register(T_OBJECT);
       __ move(LIR_OprFact::oopConst(NULL), obj);
     }
-    // emit an explicit null check because the offset is too large
-    __ null_check(obj, new CodeEmitInfo(info));
+    // Emit an explicit null check because the offset is too large.
+    // If the class is not loaded and the object is NULL, we need to deoptimize to throw a
+    // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
+    __ null_check(obj, new CodeEmitInfo(info), /* deoptimize */ needs_patching);
   }
 
   LIR_Opr reg = rlock_result(x, field_type);
@@ -3191,14 +3195,14 @@
       Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
       int start = 0;
       int stop = data->is_CallTypeData() ? ((ciCallTypeData*)data)->number_of_arguments() : ((ciVirtualCallTypeData*)data)->number_of_arguments();
-      if (x->inlined() && x->callee()->is_static() && Bytecodes::has_receiver(bc)) {
+      if (x->callee()->is_loaded() && x->callee()->is_static() && Bytecodes::has_receiver(bc)) {
         // first argument is not profiled at call (method handle invoke)
         assert(x->method()->raw_code_at_bci(bci) == Bytecodes::_invokehandle, "invokehandle expected");
         start = 1;
       }
       ciSignature* callee_signature = x->callee()->signature();
       // method handle call to virtual method
-      bool has_receiver = x->inlined() && !x->callee()->is_static() && !Bytecodes::has_receiver(bc);
+      bool has_receiver = x->callee()->is_loaded() && !x->callee()->is_static() && !Bytecodes::has_receiver(bc);
       ciSignatureStream callee_signature_stream(callee_signature, has_receiver ? x->callee()->holder() : NULL);
 
       bool ignored_will_link;
diff --git a/hotspot/src/share/vm/c1/c1_ValueMap.hpp b/hotspot/src/share/vm/c1/c1_ValueMap.hpp
index e394118..ee5c398 100644
--- a/hotspot/src/share/vm/c1/c1_ValueMap.hpp
+++ b/hotspot/src/share/vm/c1/c1_ValueMap.hpp
@@ -158,6 +158,12 @@
   void do_UnsafePutRaw   (UnsafePutRaw*    x) { kill_memory(); }
   void do_UnsafePutObject(UnsafePutObject* x) { kill_memory(); }
   void do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x) { kill_memory(); }
+  void do_UnsafeGetRaw   (UnsafeGetRaw*    x) { /* nothing to do */ }
+  void do_UnsafeGetObject(UnsafeGetObject* x) {
+    if (x->is_volatile()) { // the JMM requires this
+      kill_memory();
+    }
+  }
   void do_Intrinsic      (Intrinsic*       x) { if (!x->preserves_state()) kill_memory(); }
 
   void do_Phi            (Phi*             x) { /* nothing to do */ }
@@ -198,8 +204,6 @@
   void do_OsrEntry       (OsrEntry*        x) { /* nothing to do */ }
   void do_ExceptionObject(ExceptionObject* x) { /* nothing to do */ }
   void do_RoundFP        (RoundFP*         x) { /* nothing to do */ }
-  void do_UnsafeGetRaw   (UnsafeGetRaw*    x) { /* nothing to do */ }
-  void do_UnsafeGetObject(UnsafeGetObject* x) { /* nothing to do */ }
   void do_UnsafePrefetchRead (UnsafePrefetchRead*  x) { /* nothing to do */ }
   void do_UnsafePrefetchWrite(UnsafePrefetchWrite* x) { /* nothing to do */ }
   void do_ProfileCall    (ProfileCall*     x) { /* nothing to do */ }
diff --git a/hotspot/src/share/vm/ci/ciField.cpp b/hotspot/src/share/vm/ci/ciField.cpp
index 7dd09a9..b448d77 100644
--- a/hotspot/src/share/vm/ci/ciField.cpp
+++ b/hotspot/src/share/vm/ci/ciField.cpp
@@ -207,7 +207,7 @@
   // Check to see if the field is constant.
   bool is_final = this->is_final();
   bool is_stable = FoldStableValues && this->is_stable();
-  if (_holder->is_initialized() && (is_final || is_stable)) {
+  if (_holder->is_initialized() && ((is_final && !has_initialized_final_update()) || is_stable)) {
     if (!this->is_static()) {
       // A field can be constant if it's a final static field or if
       // it's a final non-static field of a trusted class (classes in
diff --git a/hotspot/src/share/vm/ci/ciField.hpp b/hotspot/src/share/vm/ci/ciField.hpp
index 75263e3..3e46da5 100644
--- a/hotspot/src/share/vm/ci/ciField.hpp
+++ b/hotspot/src/share/vm/ci/ciField.hpp
@@ -124,22 +124,8 @@
     return _holder->is_shared() && !is_static();
   }
 
-  // Is this field a constant?
-  //
-  // Clarification: A field is considered constant if:
-  //   1. The field is both static and final
-  //   2. The canonical holder of the field has undergone
-  //      static initialization.
-  //   3. If the field is an object or array, then the oop
-  //      in question is allocated in perm space.
-  //   4. The field is not one of the special static/final
-  //      non-constant fields.  These are java.lang.System.in
-  //      and java.lang.System.out.  Abomination.
-  //
-  // A field is also considered constant if it is marked @Stable
-  // and is non-null (or non-zero, if a primitive).
-  // For non-static fields, the null/zero check must be
-  // arranged by the user, as constant_value().is_null_or_zero().
+  // Is this field a constant? See ciField::initialize_from() for details
+  // about how a field is determined to be constant.
   bool is_constant() { return _is_constant; }
 
   // Get the constant value of this field.
@@ -176,6 +162,9 @@
   bool is_stable      () { return flags().is_stable(); }
   bool is_volatile    () { return flags().is_volatile(); }
   bool is_transient   () { return flags().is_transient(); }
+  // The field is modified outside of instance initializer methods
+  // (or class/initializer methods if the field is static).
+  bool has_initialized_final_update() { return flags().has_initialized_final_update(); }
 
   bool is_call_site_target() {
     ciInstanceKlass* callsite_klass = CURRENT_ENV->CallSite_klass();
diff --git a/hotspot/src/share/vm/ci/ciFlags.hpp b/hotspot/src/share/vm/ci/ciFlags.hpp
index 60d5632..ac4d5f1 100644
--- a/hotspot/src/share/vm/ci/ciFlags.hpp
+++ b/hotspot/src/share/vm/ci/ciFlags.hpp
@@ -46,20 +46,25 @@
 
 public:
   // Java access flags
-  bool is_public      () const         { return (_flags & JVM_ACC_PUBLIC      ) != 0; }
-  bool is_private     () const         { return (_flags & JVM_ACC_PRIVATE     ) != 0; }
-  bool is_protected   () const         { return (_flags & JVM_ACC_PROTECTED   ) != 0; }
-  bool is_static      () const         { return (_flags & JVM_ACC_STATIC      ) != 0; }
-  bool is_final       () const         { return (_flags & JVM_ACC_FINAL       ) != 0; }
-  bool is_synchronized() const         { return (_flags & JVM_ACC_SYNCHRONIZED) != 0; }
-  bool is_super       () const         { return (_flags & JVM_ACC_SUPER       ) != 0; }
-  bool is_volatile    () const         { return (_flags & JVM_ACC_VOLATILE    ) != 0; }
-  bool is_transient   () const         { return (_flags & JVM_ACC_TRANSIENT   ) != 0; }
-  bool is_native      () const         { return (_flags & JVM_ACC_NATIVE      ) != 0; }
-  bool is_interface   () const         { return (_flags & JVM_ACC_INTERFACE   ) != 0; }
-  bool is_abstract    () const         { return (_flags & JVM_ACC_ABSTRACT    ) != 0; }
-  bool is_strict      () const         { return (_flags & JVM_ACC_STRICT      ) != 0; }
-  bool is_stable      () const         { return (_flags & JVM_ACC_FIELD_STABLE) != 0; }
+  bool is_public               () const { return (_flags & JVM_ACC_PUBLIC                    ) != 0; }
+  bool is_private              () const { return (_flags & JVM_ACC_PRIVATE                   ) != 0; }
+  bool is_protected            () const { return (_flags & JVM_ACC_PROTECTED                 ) != 0; }
+  bool is_static               () const { return (_flags & JVM_ACC_STATIC                    ) != 0; }
+  bool is_final                () const { return (_flags & JVM_ACC_FINAL                     ) != 0; }
+  bool is_synchronized         () const { return (_flags & JVM_ACC_SYNCHRONIZED              ) != 0; }
+  bool is_super                () const { return (_flags & JVM_ACC_SUPER                     ) != 0; }
+  bool is_volatile             () const { return (_flags & JVM_ACC_VOLATILE                  ) != 0; }
+  bool is_transient            () const { return (_flags & JVM_ACC_TRANSIENT                 ) != 0; }
+  bool is_native               () const { return (_flags & JVM_ACC_NATIVE                    ) != 0; }
+  bool is_interface            () const { return (_flags & JVM_ACC_INTERFACE                 ) != 0; }
+  bool is_abstract             () const { return (_flags & JVM_ACC_ABSTRACT                  ) != 0; }
+  bool is_strict               () const { return (_flags & JVM_ACC_STRICT                    ) != 0; }
+  bool is_stable               () const { return (_flags & JVM_ACC_FIELD_STABLE              ) != 0; }
+  // In case the current object represents a field, return true if
+  // the field is modified outside of instance initializer methods
+  // (or class/initializer methods if the field is static) and false
+  // otherwise.
+  bool has_initialized_final_update() const { return (_flags & JVM_ACC_FIELD_INITIALIZED_FINAL_UPDATE) != 0; };
 
   // Conversion
   jint   as_int()                      { return _flags; }
diff --git a/hotspot/src/share/vm/ci/ciMethod.hpp b/hotspot/src/share/vm/ci/ciMethod.hpp
index 68bc1eb..5560e6d 100644
--- a/hotspot/src/share/vm/ci/ciMethod.hpp
+++ b/hotspot/src/share/vm/ci/ciMethod.hpp
@@ -243,6 +243,21 @@
 
   ciField*      get_field_at_bci( int bci, bool &will_link);
   ciMethod*     get_method_at_bci(int bci, bool &will_link, ciSignature* *declared_signature);
+
+  ciSignature*  get_declared_signature_at_bci(int bci) {
+    bool ignored_will_link;
+    ciSignature* declared_signature;
+    get_method_at_bci(bci, ignored_will_link, &declared_signature);
+    assert(declared_signature != NULL, "cannot be null");
+    return declared_signature;
+  }
+
+  ciMethod*     get_method_at_bci(int bci) {
+    bool ignored_will_link;
+    ciSignature* ignored_declared_signature;
+    return get_method_at_bci(bci, ignored_will_link, &ignored_declared_signature);
+  }
+
   // Given a certain calling environment, find the monomorphic target
   // for the call.  Return NULL if the call is not monomorphic in
   // its calling environment.
diff --git a/hotspot/src/share/vm/classfile/classFileError.cpp b/hotspot/src/share/vm/classfile/classFileError.cpp
index 3c3302f..a2ca479 100644
--- a/hotspot/src/share/vm/classfile/classFileError.cpp
+++ b/hotspot/src/share/vm/classfile/classFileError.cpp
@@ -56,6 +56,13 @@
                        msg, index, name, _class_name->as_C_string());
 }
 
+void ClassFileParser::classfile_parse_error(const char* msg, const char* name, const char* signature, TRAPS) {
+  assert(_class_name != NULL, "invariant");
+  ResourceMark rm(THREAD);
+  Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_ClassFormatError(),
+                     msg, name, signature, _class_name->as_C_string());
+}
+
 PRAGMA_DIAG_POP
 
 void StackMapStream::stackmap_format_error(const char* msg, TRAPS) {
diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp
index 33a289f..59a68f8 100644
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp
@@ -821,11 +821,12 @@
       THREAD, NameSigHash*, HASH_ROW_SIZE);
     initialize_hashtable(interface_names);
     bool dup = false;
+    Symbol* name = NULL;
     {
       debug_only(No_Safepoint_Verifier nsv;)
       for (index = 0; index < length; index++) {
         Klass* k = _local_interfaces->at(index);
-        Symbol* name = InstanceKlass::cast(k)->name();
+        name = InstanceKlass::cast(k)->name();
         // If no duplicates, add (name, NULL) in hashtable interface_names.
         if (!put_after_lookup(name, NULL, interface_names)) {
           dup = true;
@@ -834,7 +835,8 @@
       }
     }
     if (dup) {
-      classfile_parse_error("Duplicate interface name in class file %s", CHECK_NULL);
+      classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
+               name->as_C_string(), CHECK_NULL);
     }
   }
   return _local_interfaces;
@@ -1279,11 +1281,13 @@
       THREAD, NameSigHash*, HASH_ROW_SIZE);
     initialize_hashtable(names_and_sigs);
     bool dup = false;
+    Symbol* name = NULL;
+    Symbol* sig = NULL;
     {
       debug_only(No_Safepoint_Verifier nsv;)
       for (AllFieldStream fs(fields, _cp); !fs.done(); fs.next()) {
-        Symbol* name = fs.name();
-        Symbol* sig = fs.signature();
+        name = fs.name();
+        sig = fs.signature();
         // If no duplicates, add name/signature in hashtable names_and_sigs.
         if (!put_after_lookup(name, sig, names_and_sigs)) {
           dup = true;
@@ -1292,8 +1296,8 @@
       }
     }
     if (dup) {
-      classfile_parse_error("Duplicate field name&signature in class file %s",
-                            CHECK_NULL);
+      classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
+                             name->as_C_string(), sig->as_klass_external_name(), CHECK_NULL);
     }
   }
 
@@ -2580,20 +2584,24 @@
         THREAD, NameSigHash*, HASH_ROW_SIZE);
       initialize_hashtable(names_and_sigs);
       bool dup = false;
+      Symbol* name = NULL;
+      Symbol* sig = NULL;
       {
         debug_only(No_Safepoint_Verifier nsv;)
         for (int i = 0; i < length; i++) {
           Method* m = _methods->at(i);
+          name = m->name();
+          sig = m->signature();
           // If no duplicates, add name/signature in hashtable names_and_sigs.
-          if (!put_after_lookup(m->name(), m->signature(), names_and_sigs)) {
+          if (!put_after_lookup(name, sig, names_and_sigs)) {
             dup = true;
             break;
           }
         }
       }
       if (dup) {
-        classfile_parse_error("Duplicate method name&signature in class file %s",
-                              CHECK_NULL);
+        classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
+                              name->as_C_string(), sig->as_klass_external_name(), CHECK_NULL);
       }
     }
   }
diff --git a/hotspot/src/share/vm/classfile/classFileParser.hpp b/hotspot/src/share/vm/classfile/classFileParser.hpp
index 74367f5..73ccdeb 100644
--- a/hotspot/src/share/vm/classfile/classFileParser.hpp
+++ b/hotspot/src/share/vm/classfile/classFileParser.hpp
@@ -314,6 +314,7 @@
   void classfile_parse_error(const char* msg, int index, TRAPS);
   void classfile_parse_error(const char* msg, const char *name, TRAPS);
   void classfile_parse_error(const char* msg, int index, const char *name, TRAPS);
+  void classfile_parse_error(const char* msg, const char* name, const char* signature, TRAPS);
   inline void guarantee_property(bool b, const char* msg, TRAPS) {
     if (!b) { classfile_parse_error(msg, CHECK); }
   }
diff --git a/hotspot/src/share/vm/classfile/classLoader.cpp b/hotspot/src/share/vm/classfile/classLoader.cpp
index ef5766e..a33263b 100644
--- a/hotspot/src/share/vm/classfile/classLoader.cpp
+++ b/hotspot/src/share/vm/classfile/classLoader.cpp
@@ -1627,7 +1627,6 @@
                 if (nm != NULL && !m->is_method_handle_intrinsic()) {
                   // Throw out the code so that the code cache doesn't fill up
                   nm->make_not_entrant();
-                  m->clear_code();
                 }
                 CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization,
                                               methodHandle(), 0, "CTW", THREAD);
@@ -1646,7 +1645,6 @@
             if (nm != NULL && !m->is_method_handle_intrinsic()) {
               // Throw out the code so that the code cache doesn't fill up
               nm->make_not_entrant();
-              m->clear_code();
             }
           }
         }
diff --git a/hotspot/src/share/vm/classfile/classLoaderData.cpp b/hotspot/src/share/vm/classfile/classLoaderData.cpp
index 1f25e15..d6d1312 100644
--- a/hotspot/src/share/vm/classfile/classLoaderData.cpp
+++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -78,7 +78,7 @@
   // The null-class-loader should always be kept alive.
   _keep_alive(is_anonymous || h_class_loader.is_null()),
   _metaspace(NULL), _unloading(false), _klasses(NULL),
-  _claimed(0), _jmethod_ids(NULL), _handles(NULL), _deallocate_list(NULL),
+  _claimed(0), _jmethod_ids(NULL), _handles(), _deallocate_list(NULL),
   _next(NULL), _dependencies(dependencies),
   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true)) {
     // empty
@@ -96,6 +96,45 @@
   _list_head = oopFactory::new_objectArray(2, CHECK);
 }
 
+ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
+  Chunk* c = _head;
+  while (c != NULL) {
+    Chunk* next = c->_next;
+    delete c;
+    c = next;
+  }
+}
+
+oop* ClassLoaderData::ChunkedHandleList::add(oop o) {
+  if (_head == NULL || _head->_size == Chunk::CAPACITY) {
+    Chunk* next = new Chunk(_head);
+    OrderAccess::release_store_ptr(&_head, next);
+  }
+  oop* handle = &_head->_data[_head->_size];
+  *handle = o;
+  OrderAccess::release_store(&_head->_size, _head->_size + 1);
+  return handle;
+}
+
+inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
+  for (juint i = 0; i < size; i++) {
+    if (c->_data[i] != NULL) {
+      f->do_oop(&c->_data[i]);
+    }
+  }
+}
+
+void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
+  Chunk* head = (Chunk*) OrderAccess::load_ptr_acquire(&_head);
+  if (head != NULL) {
+    // Must be careful when reading size of head
+    oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size));
+    for (Chunk* c = head->_next; c != NULL; c = c->_next) {
+      oops_do_chunk(f, c, c->_size);
+    }
+  }
+}
+
 bool ClassLoaderData::claim() {
   if (_claimed == 1) {
     return false;
@@ -111,7 +150,7 @@
 
   f->do_oop(&_class_loader);
   _dependencies.oops_do(f);
-  _handles->oops_do(f);
+  _handles.oops_do(f);
   if (klass_closure != NULL) {
     classes_do(klass_closure);
   }
@@ -342,11 +381,6 @@
     _metaspace = NULL;
     // release the metaspace
     delete m;
-    // release the handles
-    if (_handles != NULL) {
-      JNIHandleBlock::release_block(_handles);
-      _handles = NULL;
-    }
   }
 
   // Clear all the JNI handles for methods
@@ -406,15 +440,9 @@
   return _metaspace;
 }
 
-JNIHandleBlock* ClassLoaderData::handles() const           { return _handles; }
-void ClassLoaderData::set_handles(JNIHandleBlock* handles) { _handles = handles; }
-
 jobject ClassLoaderData::add_handle(Handle h) {
   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
-  if (handles() == NULL) {
-    set_handles(JNIHandleBlock::allocate_block());
-  }
-  return handles()->allocate_handle(h());
+  return (jobject) _handles.add(h());
 }
 
 // Add this metadata pointer to be freed when it's safe.  This is only during
@@ -479,7 +507,6 @@
       p2i(class_loader() != NULL ? class_loader()->klass() : NULL), loader_name());
   if (claimed()) out->print(" claimed ");
   if (is_unloading()) out->print(" unloading ");
-  out->print(" handles " INTPTR_FORMAT, p2i(handles()));
   out->cr();
   if (metaspace_or_null() != NULL) {
     out->print_cr("metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
diff --git a/hotspot/src/share/vm/classfile/classLoaderData.hpp b/hotspot/src/share/vm/classfile/classLoaderData.hpp
index e12512d..8083b70 100644
--- a/hotspot/src/share/vm/classfile/classLoaderData.hpp
+++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -51,7 +51,6 @@
 
 class ClassLoaderData;
 class JNIMethodBlock;
-class JNIHandleBlock;
 class Metadebug;
 
 // GC root for walking class loader data created
@@ -145,6 +144,31 @@
     void oops_do(OopClosure* f);
   };
 
+  class ChunkedHandleList VALUE_OBJ_CLASS_SPEC {
+    struct Chunk : public CHeapObj<mtClass> {
+      static const size_t CAPACITY = 32;
+
+      oop _data[CAPACITY];
+      volatile juint _size;
+      Chunk* _next;
+
+      Chunk(Chunk* c) : _next(c), _size(0) { }
+    };
+
+    Chunk* _head;
+
+    void oops_do_chunk(OopClosure* f, Chunk* c, const juint size);
+
+   public:
+    ChunkedHandleList() : _head(NULL) {}
+    ~ChunkedHandleList();
+
+    // Only one thread at a time can add, guarded by ClassLoaderData::metaspace_lock().
+    // However, multiple threads can execute oops_do concurrently with add.
+    oop* add(oop o);
+    void oops_do(OopClosure* f);
+  };
+
   friend class ClassLoaderDataGraph;
   friend class ClassLoaderDataGraphKlassIteratorAtomic;
   friend class ClassLoaderDataGraphMetaspaceIterator;
@@ -169,7 +193,8 @@
                            // Has to be an int because we cas it.
   Klass* _klasses;         // The classes defined by the class loader.
 
-  JNIHandleBlock* _handles; // Handles to constant pool arrays
+  ChunkedHandleList _handles; // Handles to constant pool arrays, etc, which
+                              // have the same life cycle of the corresponding ClassLoader.
 
   // These method IDs are created for the class loader and set to NULL when the
   // class loader is unloaded.  They are rarely freed, only for redefine classes
@@ -196,9 +221,6 @@
 
   void set_metaspace(Metaspace* m) { _metaspace = m; }
 
-  JNIHandleBlock* handles() const;
-  void set_handles(JNIHandleBlock* handles);
-
   Mutex* metaspace_lock() const { return _metaspace_lock; }
 
   // GC interface.
diff --git a/hotspot/src/share/vm/classfile/javaClasses.cpp b/hotspot/src/share/vm/classfile/javaClasses.cpp
index 65900a2..fbd7cc5 100644
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -2852,6 +2852,15 @@
   mname->address_field_put(_vmindex_offset, (address) index);
 }
 
+bool java_lang_invoke_MemberName::equals(oop mn1, oop mn2) {
+  if (mn1 == mn2) {
+     return true;
+  }
+  return (vmtarget(mn1) == vmtarget(mn2) && flags(mn1) == flags(mn2) &&
+          vmindex(mn1) == vmindex(mn2) &&
+          clazz(mn1) == clazz(mn2));
+}
+
 oop java_lang_invoke_LambdaForm::vmentry(oop lform) {
   assert(is_instance(lform), "wrong type");
   return lform->obj_field(_vmentry_offset);
diff --git a/hotspot/src/share/vm/classfile/javaClasses.hpp b/hotspot/src/share/vm/classfile/javaClasses.hpp
index 02784dc..db61183 100644
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -1132,6 +1132,8 @@
   static int flags_offset_in_bytes()            { return _flags_offset; }
   static int vmtarget_offset_in_bytes()         { return _vmtarget_offset; }
   static int vmindex_offset_in_bytes()          { return _vmindex_offset; }
+
+  static bool equals(oop mt1, oop mt2);
 };
 
 
diff --git a/hotspot/src/share/vm/classfile/symbolTable.cpp b/hotspot/src/share/vm/classfile/symbolTable.cpp
index 38868b2..ec97077 100644
--- a/hotspot/src/share/vm/classfile/symbolTable.cpp
+++ b/hotspot/src/share/vm/classfile/symbolTable.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -96,7 +96,7 @@
 int SymbolTable::_symbols_counted = 0;
 volatile int SymbolTable::_parallel_claimed_idx = 0;
 
-void SymbolTable::buckets_unlink(int start_idx, int end_idx, int* processed, int* removed, size_t* memory_total) {
+void SymbolTable::buckets_unlink(int start_idx, int end_idx, BucketUnlinkContext* context, size_t* memory_total) {
   for (int i = start_idx; i < end_idx; ++i) {
     HashtableEntry<Symbol*, mtSymbol>** p = the_table()->bucket_addr(i);
     HashtableEntry<Symbol*, mtSymbol>* entry = the_table()->bucket(i);
@@ -110,15 +110,14 @@
       }
       Symbol* s = entry->literal();
       (*memory_total) += s->size();
-      (*processed)++;
+      context->_num_processed++;
       assert(s != NULL, "just checking");
       // If reference count is zero, remove.
       if (s->refcount() == 0) {
         assert(!entry->is_shared(), "shared entries should be kept live");
         delete s;
-        (*removed)++;
         *p = entry->next();
-        the_table()->free_entry(entry);
+        context->free_entry(entry);
       } else {
         p = entry->next_addr();
       }
@@ -132,9 +131,14 @@
 // This is done late during GC.
 void SymbolTable::unlink(int* processed, int* removed) {
   size_t memory_total = 0;
-  buckets_unlink(0, the_table()->table_size(), processed, removed, &memory_total);
-  _symbols_removed += *removed;
-  _symbols_counted += *processed;
+  BucketUnlinkContext context;
+  buckets_unlink(0, the_table()->table_size(), &context, &memory_total);
+  _the_table->bulk_free_entries(&context);
+  *processed = context._num_processed;
+  *removed = context._num_removed;
+
+  _symbols_removed = context._num_removed;
+  _symbols_counted = context._num_processed;
   // Exclude printing for normal PrintGCDetails because people parse
   // this output.
   if (PrintGCDetails && Verbose && WizardMode) {
@@ -148,6 +152,7 @@
 
   size_t memory_total = 0;
 
+  BucketUnlinkContext context;
   for (;;) {
     // Grab next set of buckets to scan
     int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
@@ -157,10 +162,15 @@
     }
 
     int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
-    buckets_unlink(start_idx, end_idx, processed, removed, &memory_total);
+    buckets_unlink(start_idx, end_idx, &context, &memory_total);
   }
-  Atomic::add(*processed, &_symbols_counted);
-  Atomic::add(*removed, &_symbols_removed);
+
+  _the_table->bulk_free_entries(&context);
+  *processed = context._num_processed;
+  *removed = context._num_removed;
+
+  Atomic::add(context._num_processed, &_symbols_counted);
+  Atomic::add(context._num_removed, &_symbols_removed);
   // Exclude printing for normal PrintGCDetails because people parse
   // this output.
   if (PrintGCDetails && Verbose && WizardMode) {
@@ -811,7 +821,11 @@
 }
 
 void StringTable::unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int* processed, int* removed) {
-  buckets_unlink_or_oops_do(is_alive, f, 0, the_table()->table_size(), processed, removed);
+  BucketUnlinkContext context;
+  buckets_unlink_or_oops_do(is_alive, f, 0, the_table()->table_size(), &context);
+  _the_table->bulk_free_entries(&context);
+  *processed = context._num_processed;
+  *removed = context._num_removed;
 }
 
 void StringTable::possibly_parallel_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int* processed, int* removed) {
@@ -820,6 +834,7 @@
   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
   const int limit = the_table()->table_size();
 
+  BucketUnlinkContext context;
   for (;;) {
     // Grab next set of buckets to scan
     int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
@@ -829,8 +844,11 @@
     }
 
     int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
-    buckets_unlink_or_oops_do(is_alive, f, start_idx, end_idx, processed, removed);
+    buckets_unlink_or_oops_do(is_alive, f, start_idx, end_idx, &context);
   }
+  _the_table->bulk_free_entries(&context);
+  *processed = context._num_processed;
+  *removed = context._num_removed;
 }
 
 void StringTable::buckets_oops_do(OopClosure* f, int start_idx, int end_idx) {
@@ -856,7 +874,7 @@
   }
 }
 
-void StringTable::buckets_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int start_idx, int end_idx, int* processed, int* removed) {
+void StringTable::buckets_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int start_idx, int end_idx, BucketUnlinkContext* context) {
   const int limit = the_table()->table_size();
 
   assert(0 <= start_idx && start_idx <= limit,
@@ -880,10 +898,9 @@
         p = entry->next_addr();
       } else {
         *p = entry->next();
-        the_table()->free_entry(entry);
-        (*removed)++;
+        context->free_entry(entry);
       }
-      (*processed)++;
+      context->_num_processed++;
       entry = *p;
     }
   }
diff --git a/hotspot/src/share/vm/classfile/symbolTable.hpp b/hotspot/src/share/vm/classfile/symbolTable.hpp
index d658440..58fd223 100644
--- a/hotspot/src/share/vm/classfile/symbolTable.hpp
+++ b/hotspot/src/share/vm/classfile/symbolTable.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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,8 +124,11 @@
 
   static volatile int _parallel_claimed_idx;
 
-  // Release any dead symbols
-  static void buckets_unlink(int start_idx, int end_idx, int* processed, int* removed, size_t* memory_total);
+  typedef SymbolTable::BucketUnlinkContext BucketUnlinkContext;
+  // Release any dead symbols. Unlinked bucket entries are collected in the given
+  // context to be freed later.
+  // This allows multiple threads to work on the table at once.
+  static void buckets_unlink(int start_idx, int end_idx, BucketUnlinkContext* context, size_t* memory_total);
 public:
   enum {
     symbol_alloc_batch_size = 8,
@@ -274,9 +277,13 @@
   // Apply the give oop closure to the entries to the buckets
   // in the range [start_idx, end_idx).
   static void buckets_oops_do(OopClosure* f, int start_idx, int end_idx);
+
+  typedef StringTable::BucketUnlinkContext BucketUnlinkContext;
   // Unlink or apply the give oop closure to the entries to the buckets
-  // in the range [start_idx, end_idx).
-  static void buckets_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int start_idx, int end_idx, int* processed, int* removed);
+  // in the range [start_idx, end_idx). Unlinked bucket entries are collected in the given
+  // context to be freed later.
+  // This allows multiple threads to work on the table at once.
+  static void buckets_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int start_idx, int end_idx, BucketUnlinkContext* context);
 
   StringTable() : RehashableHashtable<oop, mtSymbol>((int)StringTableSize,
                               sizeof (HashtableEntry<oop, mtSymbol>)) {}
diff --git a/hotspot/src/share/vm/classfile/systemDictionary.cpp b/hotspot/src/share/vm/classfile/systemDictionary.cpp
index 31be14b..1dfe3b6 100644
--- a/hotspot/src/share/vm/classfile/systemDictionary.cpp
+++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp
@@ -1084,15 +1084,18 @@
                                                              THREAD);
 
   const char* pkg = "java/";
+  size_t pkglen = strlen(pkg);
   if (!HAS_PENDING_EXCEPTION &&
       !class_loader.is_null() &&
       parsed_name != NULL &&
-      !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
+      parsed_name->utf8_length() >= (int)pkglen &&
+      !strncmp((const char*)parsed_name->bytes(), pkg, pkglen)) {
     // It is illegal to define classes in the "java." package from
     // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
     ResourceMark rm(THREAD);
     char* name = parsed_name->as_C_string();
     char* index = strrchr(name, '/');
+    assert(index != NULL, "must be");
     *index = '\0'; // chop to just the package name
     while ((index = strchr(name, '/')) != NULL) {
       *index = '.'; // replace '/' with '.' in package name
diff --git a/hotspot/src/share/vm/classfile/verifier.cpp b/hotspot/src/share/vm/classfile/verifier.cpp
index 17a9959..b53b4ae 100644
--- a/hotspot/src/share/vm/classfile/verifier.cpp
+++ b/hotspot/src/share/vm/classfile/verifier.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2017, 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
@@ -1969,7 +1969,7 @@
   InstanceKlass* target_instance = InstanceKlass::cast(target_class);
   fieldDescriptor fd;
   if (is_method) {
-    Method* m = target_instance->uncached_lookup_method(field_name, field_sig, Klass::normal);
+    Method* m = target_instance->uncached_lookup_method(field_name, field_sig, Klass::find_overpass);
     if (m != NULL && m->is_protected()) {
       if (!this_class->is_same_class_package(m->method_holder())) {
         return true;
@@ -2539,7 +2539,7 @@
       Klass* ref_klass = load_class(ref_class_type.name(), CHECK);
       Method* m = InstanceKlass::cast(ref_klass)->uncached_lookup_method(
         vmSymbols::object_initializer_name(),
-        cp->signature_ref_at(bcs->get_index_u2()), Klass::normal);
+        cp->signature_ref_at(bcs->get_index_u2()), Klass::find_overpass);
       // Do nothing if method is not found.  Let resolution detect the error.
       if (m != NULL) {
         instanceKlassHandle mh(THREAD, m->method_holder());
diff --git a/hotspot/src/share/vm/code/nmethod.cpp b/hotspot/src/share/vm/code/nmethod.cpp
index 6ea39ae..b897b6a 100644
--- a/hotspot/src/share/vm/code/nmethod.cpp
+++ b/hotspot/src/share/vm/code/nmethod.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -254,7 +254,8 @@
 
 
 address ExceptionCache::test_address(address addr) {
-  for (int i=0; i<count(); i++) {
+  int limit = count();
+  for (int i = 0; i < limit; i++) {
     if (pc_at(i) == addr) {
       return handler_at(i);
     }
@@ -265,9 +266,11 @@
 
 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
   if (test_address(addr) == handler) return true;
-  if (count() < cache_size) {
-    set_pc_at(count(),addr);
-    set_handler_at(count(), handler);
+
+  int index = count();
+  if (index < cache_size) {
+    set_pc_at(index, addr);
+    set_handler_at(index, handler);
     increment_count();
     return true;
   }
@@ -380,10 +383,11 @@
   assert(new_entry != NULL,"Must be non null");
   assert(new_entry->next() == NULL, "Must be null");
 
-  if (exception_cache() != NULL) {
-    new_entry->set_next(exception_cache());
+  ExceptionCache *ec = exception_cache();
+  if (ec != NULL) {
+    new_entry->set_next(ec);
   }
-  set_exception_cache(new_entry);
+  release_set_exception_cache(new_entry);
 }
 
 void nmethod::clean_exception_cache(BoolObjectClosure* is_alive) {
@@ -1151,6 +1155,7 @@
 // Clear ICStubs of all compiled ICs
 void nmethod::clear_ic_stubs() {
   assert_locked_or_safepoint(CompiledIC_lock);
+  ResourceMark rm;
   RelocIterator iter(this);
   while(iter.next()) {
     if (iter.type() == relocInfo::virtual_call_type) {
@@ -1505,7 +1510,7 @@
     if (method() != NULL && (method()->code() == this ||
                              method()->from_compiled_entry() == verified_entry_point())) {
       HandleMark hm;
-      method()->clear_code();
+      method()->clear_code(false /* already owns Patching_lock */);
     }
   } // leave critical region under Patching_lock
 
@@ -2290,7 +2295,7 @@
     assert(cur != NULL, "not NULL-terminated");
     nmethod* next = cur->_oops_do_mark_link;
     cur->_oops_do_mark_link = NULL;
-    cur->verify_oop_relocations();
+    DEBUG_ONLY(cur->verify_oop_relocations());
     NOT_PRODUCT(if (TraceScavenge)  cur->print_on(tty, "oops_do, unmark"));
     cur = next;
   }
diff --git a/hotspot/src/share/vm/code/nmethod.hpp b/hotspot/src/share/vm/code/nmethod.hpp
index b7d6890..5b16f33 100644
--- a/hotspot/src/share/vm/code/nmethod.hpp
+++ b/hotspot/src/share/vm/code/nmethod.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -39,15 +39,16 @@
   Klass*   _exception_type;
   address  _pc[cache_size];
   address  _handler[cache_size];
-  int      _count;
+  volatile int _count;
   ExceptionCache* _next;
 
   address pc_at(int index)                     { assert(index >= 0 && index < count(),""); return _pc[index]; }
   void    set_pc_at(int index, address a)      { assert(index >= 0 && index < cache_size,""); _pc[index] = a; }
   address handler_at(int index)                { assert(index >= 0 && index < count(),""); return _handler[index]; }
   void    set_handler_at(int index, address a) { assert(index >= 0 && index < cache_size,""); _handler[index] = a; }
-  int     count()                              { return _count; }
-  void    increment_count()                    { _count++; }
+  int     count()                              { return OrderAccess::load_acquire(&_count); }
+  // increment_count is only called under lock, but there may be concurrent readers.
+  void    increment_count()                    { OrderAccess::release_store(&_count, _count + 1); }
 
  public:
 
@@ -237,7 +238,7 @@
   // counter is decreased (by 1) while sweeping.
   int _hotness_counter;
 
-  ExceptionCache *_exception_cache;
+  ExceptionCache * volatile _exception_cache;
   PcDescCache     _pc_desc_cache;
 
   // These are used for compiled synchronized native methods to
@@ -433,7 +434,7 @@
 
   // flag accessing and manipulation
   bool  is_in_use() const                         { return _state == in_use; }
-  bool  is_alive() const                          { return _state == in_use || _state == not_entrant; }
+  bool  is_alive() const                          { unsigned char s = _state; return s == in_use || s == not_entrant; }
   bool  is_not_entrant() const                    { return _state == not_entrant; }
   bool  is_zombie() const                         { return _state == zombie; }
   bool  is_unloaded() const                       { return _state == unloaded;   }
@@ -555,8 +556,10 @@
   void  set_stack_traversal_mark(long l)          { _stack_traversal_mark = l; }
 
   // Exception cache support
+  // Note: _exception_cache may be read concurrently. We rely on memory_order_consume here.
   ExceptionCache* exception_cache() const         { return _exception_cache; }
   void set_exception_cache(ExceptionCache *ec)    { _exception_cache = ec; }
+  void release_set_exception_cache(ExceptionCache *ec) { OrderAccess::release_store_ptr(&_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 clean_exception_cache(BoolObjectClosure* is_alive);
diff --git a/hotspot/src/share/vm/code/relocInfo.cpp b/hotspot/src/share/vm/code/relocInfo.cpp
index 174a615..343aa04 100644
--- a/hotspot/src/share/vm/code/relocInfo.cpp
+++ b/hotspot/src/share/vm/code/relocInfo.cpp
@@ -128,9 +128,9 @@
   if (nm == NULL && begin != NULL) {
     // allow nmethod to be deduced from beginning address
     CodeBlob* cb = CodeCache::find_blob(begin);
-    nm = cb->as_nmethod_or_null();
+    nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
   }
-  assert(nm != NULL, "must be able to deduce nmethod from other arguments");
+  guarantee(nm != NULL, "must be able to deduce nmethod from other arguments");
 
   _code    = nm;
   _current = nm->relocation_begin() - 1;
diff --git a/hotspot/src/share/vm/compiler/compileBroker.cpp b/hotspot/src/share/vm/compiler/compileBroker.cpp
index dad99ec..32a753c 100644
--- a/hotspot/src/share/vm/compiler/compileBroker.cpp
+++ b/hotspot/src/share/vm/compiler/compileBroker.cpp
@@ -1851,6 +1851,10 @@
           tty->print_cr("Opening compilation log %s", file_name);
         }
         CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id);
+        if (log == NULL) {
+          fclose(fp);
+          return;
+        }
         thread->init_log(log);
 
         if (xtty != NULL) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
index 74fae43..45bc364 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
diff --git a/hotspot/src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp b/hotspot/src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp
index 9209f0d..3464218 100644
--- a/hotspot/src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp
@@ -452,9 +452,13 @@
   // event lock and do the read again in case some other thread had already
   // succeeded and done the resize.
   int cur_collection = Universe::heap()->total_collections();
-  if (_last_LNC_resizing_collection[i] != cur_collection) {
+  // Updated _last_LNC_resizing_collection[i] must not be visible before
+  // _lowest_non_clean and friends are visible. Therefore use acquire/release
+  // to guarantee this on non TSO architecures.
+  if (OrderAccess::load_acquire(&_last_LNC_resizing_collection[i]) != cur_collection) {
     MutexLocker x(ParGCRareEvent_lock);
-    if (_last_LNC_resizing_collection[i] != cur_collection) {
+    // This load_acquire is here for clarity only. The MutexLocker already fences.
+    if (OrderAccess::load_acquire(&_last_LNC_resizing_collection[i]) != cur_collection) {
       if (_lowest_non_clean[i] == NULL ||
           n_chunks != _lowest_non_clean_chunk_size[i]) {
 
@@ -474,7 +478,8 @@
             _lowest_non_clean[i][j] = NULL;
         }
       }
-      _last_LNC_resizing_collection[i] = cur_collection;
+      // Make sure this gets visible only after _lowest_non_clean* was initialized
+      OrderAccess::release_store(&_last_LNC_resizing_collection[i], cur_collection);
     }
   }
   // In any case, now do the initialization.
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
index 260dc72..7d85c34 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
@@ -171,7 +171,7 @@
   ParallelScavengeHeap* heap = PSParallelCompact::gc_heap();
   uint parallel_gc_threads = heap->gc_task_manager()->workers();
   uint active_gc_threads = heap->gc_task_manager()->active_workers();
-  RegionTaskQueueSet* qset = ParCompactionManager::region_array();
+  OopTaskQueueSet* qset = ParCompactionManager::stack_array();
   ParallelTaskTerminator terminator(active_gc_threads, qset);
   GCTaskQueue* q = GCTaskQueue::create();
   for(uint i=0; i<parallel_gc_threads; i++) {
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
index 8175ded..b2c3b06 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
@@ -2355,7 +2355,7 @@
   ParallelScavengeHeap* heap = gc_heap();
   uint parallel_gc_threads = heap->gc_task_manager()->workers();
   uint active_gc_threads = heap->gc_task_manager()->active_workers();
-  TaskQueueSetSuper* qset = ParCompactionManager::region_array();
+  TaskQueueSetSuper* qset = ParCompactionManager::stack_array();
   ParallelTaskTerminator terminator(active_gc_threads, qset);
 
   PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);
diff --git a/hotspot/src/share/vm/interpreter/linkResolver.cpp b/hotspot/src/share/vm/interpreter/linkResolver.cpp
index ed95074..e7b6b8c 100644
--- a/hotspot/src/share/vm/interpreter/linkResolver.cpp
+++ b/hotspot/src/share/vm/interpreter/linkResolver.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -289,11 +289,11 @@
 // returns first instance method
 // Looks up method in classes, then looks up local default methods
 void LinkResolver::lookup_instance_method_in_klasses(methodHandle& result, KlassHandle klass, Symbol* name, Symbol* signature, TRAPS) {
-  Method* result_oop = klass->uncached_lookup_method(name, signature, Klass::normal);
+  Method* result_oop = klass->uncached_lookup_method(name, signature, Klass::find_overpass);
   result = methodHandle(THREAD, result_oop);
   while (!result.is_null() && result->is_static() && result->method_holder()->super() != NULL) {
     KlassHandle super_klass = KlassHandle(THREAD, result->method_holder()->super());
-    result = methodHandle(THREAD, super_klass->uncached_lookup_method(name, signature, Klass::normal));
+    result = methodHandle(THREAD, super_klass->uncached_lookup_method(name, signature, Klass::find_overpass));
   }
 
   if (klass->oop_is_array()) {
@@ -320,7 +320,9 @@
   // First check in default method array
   if (!resolved_method->is_abstract() &&
     (InstanceKlass::cast(klass())->default_methods() != NULL)) {
-    int index = InstanceKlass::find_method_index(InstanceKlass::cast(klass())->default_methods(), name, signature, false, false);
+    int index = InstanceKlass::find_method_index(InstanceKlass::cast(klass())->default_methods(),
+                                                 name, signature, Klass::find_overpass,
+                                                 Klass::find_static, Klass::find_private);
     if (index >= 0 ) {
       vtable_index = InstanceKlass::cast(klass())->default_vtable_indices()->at(index);
     }
@@ -1189,7 +1191,7 @@
   assert(resolved_method->method_holder()->is_linked(), "must be linked");
 
   // do lookup based on receiver klass using the vtable index
-  if (resolved_method->method_holder()->is_interface()) { // miranda method
+  if (resolved_method->method_holder()->is_interface()) { // default or miranda method
     vtable_index = vtable_index_of_interface_method(resolved_klass,
                            resolved_method);
     assert(vtable_index >= 0 , "we should have valid vtable index at this point");
@@ -1198,7 +1200,7 @@
     selected_method = methodHandle(THREAD, inst->method_at_vtable(vtable_index));
   } else {
     // at this point we are sure that resolved_method is virtual and not
-    // a miranda method; therefore, it must have a valid vtable index.
+    // a default or miranda method; therefore, it must have a valid vtable index.
     assert(!resolved_method->has_itable_index(), "");
     vtable_index = resolved_method->vtable_index();
     // We could get a negative vtable_index for final methods,
diff --git a/hotspot/src/share/vm/interpreter/rewriter.cpp b/hotspot/src/share/vm/interpreter/rewriter.cpp
index 2474ae7..b2d89c89 100644
--- a/hotspot/src/share/vm/interpreter/rewriter.cpp
+++ b/hotspot/src/share/vm/interpreter/rewriter.cpp
@@ -396,10 +396,45 @@
           break;
         }
 
+        case Bytecodes::_putstatic      :
+        case Bytecodes::_putfield       : {
+          if (!reverse) {
+            // Check if any final field of the class given as parameter is modified
+            // outside of initializer methods of the class. Fields that are modified
+            // are marked with a flag. For marked fields, the compilers do not perform
+            // constant folding (as the field can be changed after initialization).
+            //
+            // The check is performed after verification and only if verification has
+            // succeeded. Therefore, the class is guaranteed to be well-formed.
+            InstanceKlass* klass = method->method_holder();
+            u2 bc_index = Bytes::get_Java_u2(bcp + prefix_length + 1);
+            constantPoolHandle cp(method->constants());
+            Symbol* ref_class_name = cp->klass_name_at(cp->klass_ref_index_at(bc_index));
+
+            if (klass->name() == ref_class_name) {
+              Symbol* field_name = cp->name_ref_at(bc_index);
+              Symbol* field_sig = cp->signature_ref_at(bc_index);
+
+              fieldDescriptor fd;
+              if (klass->find_field(field_name, field_sig, &fd) != NULL) {
+                if (fd.access_flags().is_final()) {
+                  if (fd.access_flags().is_static()) {
+                    if (!method->is_static_initializer()) {
+                      fd.set_has_initialized_final_update(true);
+                    }
+                  } else {
+                    if (!method->is_object_initializer()) {
+                      fd.set_has_initialized_final_update(true);
+                    }
+                  }
+                }
+              }
+            }
+          }
+        }
+        // fall through
         case Bytecodes::_getstatic      : // fall through
-        case Bytecodes::_putstatic      : // fall through
         case Bytecodes::_getfield       : // fall through
-        case Bytecodes::_putfield       : // fall through
         case Bytecodes::_invokevirtual  : // fall through
         case Bytecodes::_invokestatic   :
         case Bytecodes::_invokeinterface:
diff --git a/hotspot/src/share/vm/memory/cardTableModRefBS.hpp b/hotspot/src/share/vm/memory/cardTableModRefBS.hpp
index c824e61..ae15ba7 100644
--- a/hotspot/src/share/vm/memory/cardTableModRefBS.hpp
+++ b/hotspot/src/share/vm/memory/cardTableModRefBS.hpp
@@ -217,7 +217,7 @@
   CardArr* _lowest_non_clean;
   size_t*  _lowest_non_clean_chunk_size;
   uintptr_t* _lowest_non_clean_base_chunk_index;
-  int* _last_LNC_resizing_collection;
+  volatile int* _last_LNC_resizing_collection;
 
   // Initializes "lowest_non_clean" to point to the array for the region
   // covering "sp", and "lowest_non_clean_base_chunk_index" to the chunk
diff --git a/hotspot/src/share/vm/oops/arrayKlass.cpp b/hotspot/src/share/vm/oops/arrayKlass.cpp
index 1c381bb..09907d6 100644
--- a/hotspot/src/share/vm/oops/arrayKlass.cpp
+++ b/hotspot/src/share/vm/oops/arrayKlass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -71,10 +71,13 @@
   return super()->find_field(name, sig, fd);
 }
 
-Method* ArrayKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
+Method* ArrayKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {
   // There are no methods in an array klass but the super class (Object) has some
   assert(super(), "super klass must be present");
-  return super()->uncached_lookup_method(name, signature, mode);
+  // Always ignore overpass methods in superclasses, although technically the
+  // super klass of an array, (j.l.Object) should not have
+  // any overpass methods present.
+  return super()->uncached_lookup_method(name, signature, Klass::skip_overpass);
 }
 
 ArrayKlass::ArrayKlass(Symbol* name) {
diff --git a/hotspot/src/share/vm/oops/arrayKlass.hpp b/hotspot/src/share/vm/oops/arrayKlass.hpp
index d697cac..d28ece3 100644
--- a/hotspot/src/share/vm/oops/arrayKlass.hpp
+++ b/hotspot/src/share/vm/oops/arrayKlass.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -90,7 +90,7 @@
   Klass* find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
 
   // Lookup operations
-  Method* uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const;
+  Method* uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const;
 
   // Casting from Klass*
   static ArrayKlass* cast(Klass* k) {
diff --git a/hotspot/src/share/vm/oops/constMethod.cpp b/hotspot/src/share/vm/oops/constMethod.cpp
index 8c7911a..a496149 100644
--- a/hotspot/src/share/vm/oops/constMethod.cpp
+++ b/hotspot/src/share/vm/oops/constMethod.cpp
@@ -390,8 +390,12 @@
   ResourceMark rm;
   assert(is_constMethod(), "must be constMethod");
   st->print_cr("%s", internal_name());
-  st->print(" - method:       " INTPTR_FORMAT " ", p2i((address)method()));
-  method()->print_value_on(st); st->cr();
+  Method* m = method();
+  st->print(" - method:       " INTPTR_FORMAT " ", p2i((address)m));
+  if (m != NULL) {
+    m->print_value_on(st);
+  }
+  st->cr();
   if (has_stackmap_table()) {
     st->print(" - stackmap data:       ");
     stackmap_data()->print_value_on(st);
@@ -404,7 +408,12 @@
 void ConstMethod::print_value_on(outputStream* st) const {
   assert(is_constMethod(), "must be constMethod");
   st->print(" const part of method " );
-  method()->print_value_on(st);
+  Method* m = method();
+  if (m != NULL) {
+    m->print_value_on(st);
+  } else {
+    st->print("NULL");
+  }
 }
 
 #if INCLUDE_SERVICES
@@ -444,7 +453,7 @@
 
   // Verification can occur during oop construction before the method or
   // other fields have been initialized.
-  guarantee(method()->is_method(), "should be method");
+  guarantee(method() != NULL && method()->is_method(), "should be method");
 
   address m_end = (address)((intptr_t) this + size());
   address compressed_table_start = code_end();
diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp
index 481742d..b1c09f6 100644
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -616,7 +616,11 @@
 
 bool InstanceKlass::link_class_impl(
     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
-  // check for error state
+  // check for error state.
+  // This is checking for the wrong state.  If the state is initialization_error,
+  // then this class *was* linked.  The CDS code does a try_link_class and uses
+  // initialization_error to mark classes to not include in the archive during
+  // DumpSharedSpaces.  This should be removed when the CDS bug is fixed.
   if (this_oop->is_in_error_state()) {
     ResourceMark rm(THREAD);
     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
@@ -801,37 +805,22 @@
 }
 
 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
-void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_oop, TRAPS) {
-  if (this_oop->has_default_methods()) {
-    for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
-      Klass* iface = this_oop->local_interfaces()->at(i);
-      InstanceKlass* ik = InstanceKlass::cast(iface);
-      if (ik->should_be_initialized()) {
-        if (ik->has_default_methods()) {
-          ik->initialize_super_interfaces(ik, THREAD);
-        }
-        // Only initialize() interfaces that "declare" concrete methods.
-        // has_default_methods drives searching superinterfaces since it
-        // means has_default_methods in its superinterface hierarchy
-        if (!HAS_PENDING_EXCEPTION && ik->declares_default_methods()) {
-          ik->initialize(THREAD);
-        }
-        if (HAS_PENDING_EXCEPTION) {
-          Handle e(THREAD, PENDING_EXCEPTION);
-          CLEAR_PENDING_EXCEPTION;
-          {
-            EXCEPTION_MARK;
-            // Locks object, set state, and notify all waiting threads
-            this_oop->set_initialization_state_and_notify(
-                initialization_error, THREAD);
+void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_k, TRAPS) {
+  assert (this_k->has_default_methods(), "caller should have checked this");
+  for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
+    Klass* iface = this_k->local_interfaces()->at(i);
+    InstanceKlass* ik = InstanceKlass::cast(iface);
 
-            // ignore any exception thrown, superclass initialization error is
-            // thrown below
-            CLEAR_PENDING_EXCEPTION;
-          }
-          THROW_OOP(e());
-        }
-      }
+    // Initialization is depth first search ie. we start with top of the inheritance tree
+    // has_default_methods drives searching superinterfaces since it
+    // means has_default_methods in its superinterface hierarchy
+    if (ik->has_default_methods()) {
+      ik->initialize_super_interfaces(ik, CHECK);
+    }
+
+    // Only initialize() interfaces that "declare" concrete methods.
+    if (ik->should_be_initialized() && ik->declares_default_methods()) {
+      ik->initialize(CHECK);
     }
   }
 }
@@ -897,30 +886,36 @@
   }
 
   // Step 7
-  Klass* super_klass = this_oop->super();
-  if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
-    super_klass->initialize(THREAD);
+  // Next, if C is a class rather than an interface, initialize its super class and super
+  // interfaces.
+  if (!this_oop->is_interface()) {
+    Klass* super_klass = this_oop->super();
+    if (super_klass != NULL && super_klass->should_be_initialized()) {
+      super_klass->initialize(THREAD);
+    }
+    // If C implements any interfaces that declares a non-abstract, non-static method,
+    // the initialization of C triggers initialization of its super interfaces.
+    // Only need to recurse if has_default_methods which includes declaring and
+    // inheriting default methods
+    if (!HAS_PENDING_EXCEPTION && this_oop->has_default_methods()) {
+      this_oop->initialize_super_interfaces(this_oop, THREAD);
+    }
 
+    // If any exceptions, complete abruptly, throwing the same exception as above.
     if (HAS_PENDING_EXCEPTION) {
       Handle e(THREAD, PENDING_EXCEPTION);
       CLEAR_PENDING_EXCEPTION;
       {
         EXCEPTION_MARK;
-        this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
-        CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
+        // Locks object, set state, and notify all waiting threads
+        this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
+        CLEAR_PENDING_EXCEPTION;
       }
       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
       THROW_OOP(e());
     }
   }
 
-  // Recursively initialize any superinterfaces that declare default methods
-  // Only need to recurse if has_default_methods which includes declaring and
-  // inheriting default methods
-  if (this_oop->has_default_methods()) {
-    this_oop->initialize_super_interfaces(this_oop, CHECK);
-  }
-
   // Step 8
   {
     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
@@ -981,10 +976,15 @@
 
 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   oop init_lock = this_oop->init_lock();
-  ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
-  this_oop->set_init_state(state);
-  this_oop->fence_and_clear_init_lock();
-  ol.notify_all(CHECK);
+  if (init_lock != NULL) {
+    ObjectLocker ol(init_lock, THREAD);
+    this_oop->set_init_state(state);
+    this_oop->fence_and_clear_init_lock();
+    ol.notify_all(CHECK);
+  } else {
+    assert(init_lock != NULL, "The initialization state should never be set twice");
+    this_oop->set_init_state(state);
+  }
 }
 
 // The embedded _implementor field can only record one implementor.
@@ -1475,18 +1475,23 @@
 
 // find_method looks up the name/signature in the local methods array
 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
-  return find_method_impl(name, signature, false);
+  return find_method_impl(name, signature, find_overpass, find_static, find_private);
 }
 
-Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const {
-  return InstanceKlass::find_method_impl(methods(), name, signature, skipping_overpass, false);
+Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature,
+                                        OverpassLookupMode overpass_mode,
+                                        StaticLookupMode static_mode,
+                                        PrivateLookupMode private_mode) const {
+  return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);
 }
 
 // find_instance_method looks up the name/signature in the local methods array
 // and skips over static methods
 Method* InstanceKlass::find_instance_method(
     Array<Method*>* methods, Symbol* name, Symbol* signature) {
-  Method* meth = InstanceKlass::find_method_impl(methods, name, signature, false, true);
+  Method* meth = InstanceKlass::find_method_impl(methods, name, signature,
+                                                 find_overpass, skip_static, find_private);
+  assert(((meth == NULL) || !meth->is_static()), "find_instance_method should have skipped statics");
   return meth;
 }
 
@@ -1496,22 +1501,51 @@
     return InstanceKlass::find_instance_method(methods(), name, signature);
 }
 
+// Find looks up the name/signature in the local methods array
+// and filters on the overpass, static and private flags
+// This returns the first one found
+// note that the local methods array can have up to one overpass, one static
+// and one instance (private or not) with the same name/signature
+Method* InstanceKlass::find_local_method(Symbol* name, Symbol* signature,
+                                        OverpassLookupMode overpass_mode,
+                                        StaticLookupMode static_mode,
+                                        PrivateLookupMode private_mode) const {
+  return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);
+}
+
+// Find looks up the name/signature in the local methods array
+// and filters on the overpass, static and private flags
+// This returns the first one found
+// note that the local methods array can have up to one overpass, one static
+// and one instance (private or not) with the same name/signature
+Method* InstanceKlass::find_local_method(Array<Method*>* methods,
+                                        Symbol* name, Symbol* signature,
+                                        OverpassLookupMode overpass_mode,
+                                        StaticLookupMode static_mode,
+                                        PrivateLookupMode private_mode) {
+  return InstanceKlass::find_method_impl(methods, name, signature, overpass_mode, static_mode, private_mode);
+}
+
+
 // find_method looks up the name/signature in the local methods array
 Method* InstanceKlass::find_method(
     Array<Method*>* methods, Symbol* name, Symbol* signature) {
-  return InstanceKlass::find_method_impl(methods, name, signature, false, false);
+  return InstanceKlass::find_method_impl(methods, name, signature, find_overpass, find_static, find_private);
 }
 
 Method* InstanceKlass::find_method_impl(
-    Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static) {
-  int hit = find_method_index(methods, name, signature, skipping_overpass, skipping_static);
+    Array<Method*>* methods, Symbol* name, Symbol* signature,
+    OverpassLookupMode overpass_mode, StaticLookupMode static_mode,
+    PrivateLookupMode private_mode) {
+  int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
   return hit >= 0 ? methods->at(hit): NULL;
 }
 
-bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static) {
-    return (m->signature() == signature) &&
+bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static, bool skipping_private) {
+    return  ((m->signature() == signature) &&
             (!skipping_overpass || !m->is_overpass()) &&
-            (!skipping_static || !m->is_static());
+            (!skipping_static || !m->is_static()) &&
+            (!skipping_private || !m->is_private()));
 }
 
 // Used directly for default_methods to find the index into the
@@ -1521,15 +1555,25 @@
 // the search continues to find a potential non-overpass match.  This capability
 // is important during method resolution to prefer a static method, for example,
 // over an overpass method.
+// There is the possibility in any _method's array to have the same name/signature
+// for a static method, an overpass method and a local instance method
+// To correctly catch a given method, the search criteria may need
+// to explicitly skip the other two. For local instance methods, it
+// is often necessary to skip private methods
 int InstanceKlass::find_method_index(
-    Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static) {
+    Array<Method*>* methods, Symbol* name, Symbol* signature,
+    OverpassLookupMode overpass_mode, StaticLookupMode static_mode,
+    PrivateLookupMode private_mode) {
+  bool skipping_overpass = (overpass_mode == skip_overpass);
+  bool skipping_static = (static_mode == skip_static);
+  bool skipping_private = (private_mode == skip_private);
   int hit = binary_search(methods, name);
   if (hit != -1) {
     Method* m = methods->at(hit);
 
     // Do linear search to find matching signature.  First, quick check
     // for common case, ignoring overpasses if requested.
-    if (method_matches(m, signature, skipping_overpass, skipping_static)) return hit;
+    if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return hit;
 
     // search downwards through overloaded methods
     int i;
@@ -1537,18 +1581,18 @@
         Method* m = methods->at(i);
         assert(m->is_method(), "must be method");
         if (m->name() != name) break;
-        if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
+        if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;
     }
     // search upwards
     for (i = hit + 1; i < methods->length(); ++i) {
         Method* m = methods->at(i);
         assert(m->is_method(), "must be method");
         if (m->name() != name) break;
-        if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
+        if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;
     }
     // not found
 #ifdef ASSERT
-    int index = skipping_overpass || skipping_static ? -1 : linear_search(methods, name, signature);
+    int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : linear_search(methods, name, signature);
     assert(index == -1, err_msg("binary search should have found entry %d", index));
 #endif
   }
@@ -1574,16 +1618,16 @@
 
 // uncached_lookup_method searches both the local class methods array and all
 // superclasses methods arrays, skipping any overpass methods in superclasses.
-Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
-  MethodLookupMode lookup_mode = mode;
+Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {
+  OverpassLookupMode overpass_local_mode = overpass_mode;
   Klass* klass = const_cast<InstanceKlass*>(this);
   while (klass != NULL) {
-    Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, (lookup_mode == skip_overpass));
+    Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, overpass_local_mode, find_static, find_private);
     if (method != NULL) {
       return method;
     }
     klass = InstanceKlass::cast(klass)->super();
-    lookup_mode = skip_overpass;   // Always ignore overpass methods in superclasses
+    overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
   }
   return NULL;
 }
@@ -1613,7 +1657,7 @@
   }
   // Look up interfaces
   if (m == NULL) {
-    m = lookup_method_in_all_interfaces(name, signature, normal);
+    m = lookup_method_in_all_interfaces(name, signature, find_defaults);
   }
   return m;
 }
@@ -1623,7 +1667,7 @@
 // They should only be found in the initial InterfaceMethodRef
 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
                                                        Symbol* signature,
-                                                       MethodLookupMode mode) const {
+                                                       DefaultsLookupMode defaults_mode) const {
   Array<Klass*>* all_ifs = transitive_interfaces();
   int num_ifs = all_ifs->length();
   InstanceKlass *ik = NULL;
@@ -1631,7 +1675,7 @@
     ik = InstanceKlass::cast(all_ifs->at(i));
     Method* m = ik->lookup_method(name, signature);
     if (m != NULL && m->is_public() && !m->is_static() &&
-        ((mode != skip_defaults) || !m->is_default_method())) {
+        ((defaults_mode != skip_defaults) || !m->is_default_method())) {
       return m;
     }
   }
@@ -3018,7 +3062,7 @@
   return NULL;
 }
 
-bool InstanceKlass::add_member_name(Handle mem_name) {
+oop InstanceKlass::add_member_name(Handle mem_name, bool intern) {
   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
   MutexLocker ml(MemberNameTable_lock);
   DEBUG_ONLY(No_Safepoint_Verifier nsv);
@@ -3028,7 +3072,7 @@
   // is called!
   Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());
   if (method->is_obsolete()) {
-    return false;
+    return NULL;
   } else if (method->is_old()) {
     // Replace method with redefined version
     java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));
@@ -3037,8 +3081,11 @@
   if (_member_names == NULL) {
     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
   }
-  _member_names->add_member_name(mem_name_wref);
-  return true;
+  if (intern) {
+    return _member_names->find_or_add_member_name(mem_name_wref);
+  } else {
+    return _member_names->add_member_name(mem_name_wref);
+  }
 }
 
 // -----------------------------------------------------------------------------------------------------
diff --git a/hotspot/src/share/vm/oops/instanceKlass.hpp b/hotspot/src/share/vm/oops/instanceKlass.hpp
index dc4a565..e1fba31 100644
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -527,18 +527,36 @@
   Method* find_instance_method(Symbol* name, Symbol* signature);
   static Method* find_instance_method(Array<Method*>* methods, Symbol* name, Symbol* signature);
 
-  // true if method matches signature and conforms to skipping_X conditions.
-  static bool method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static);
+  // find a local method (returns NULL if not found)
+  Method* find_local_method(Symbol* name, Symbol* signature,
+                           OverpassLookupMode overpass_mode,
+                           StaticLookupMode static_mode,
+                           PrivateLookupMode private_mode) const;
 
-  // find a local method index in default_methods (returns -1 if not found)
-  static int find_method_index(Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static);
+  // find a local method from given methods array (returns NULL if not found)
+  static Method* find_local_method(Array<Method*>* methods,
+                           Symbol* name, Symbol* signature,
+                           OverpassLookupMode overpass_mode,
+                           StaticLookupMode static_mode,
+                           PrivateLookupMode private_mode);
+
+  // true if method matches signature and conforms to skipping_X conditions.
+  static bool method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static, bool skipping_private);
+
+  // find a local method index in methods or default_methods (returns -1 if not found)
+  static int find_method_index(Array<Method*>* methods,
+                               Symbol* name, Symbol* signature,
+                               OverpassLookupMode overpass_mode,
+                               StaticLookupMode static_mode,
+                               PrivateLookupMode private_mode);
+
 
   // lookup operation (returns NULL if not found)
-  Method* uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const;
+  Method* uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const;
 
   // lookup a method in all the interfaces that this class implements
   // (returns NULL if not found)
-  Method* lookup_method_in_all_interfaces(Symbol* name, Symbol* signature, MethodLookupMode mode) const;
+  Method* lookup_method_in_all_interfaces(Symbol* name, Symbol* signature, DefaultsLookupMode defaults_mode) const;
 
   // lookup a method in local defaults then in all interfaces
   // (returns NULL if not found)
@@ -1089,8 +1107,15 @@
   Klass* array_klass_impl(bool or_null, TRAPS);
 
   // find a local method (returns NULL if not found)
-  Method* find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const;
-  static Method* find_method_impl(Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static);
+  Method* find_method_impl(Symbol* name, Symbol* signature,
+                           OverpassLookupMode overpass_mode,
+                           StaticLookupMode static_mode,
+                           PrivateLookupMode private_mode) const;
+  static Method* find_method_impl(Array<Method*>* methods,
+                                  Symbol* name, Symbol* signature,
+                                  OverpassLookupMode overpass_mode,
+                                  StaticLookupMode static_mode,
+                                  PrivateLookupMode private_mode);
 
   // Free CHeap allocated fields.
   void release_C_heap_structures();
@@ -1105,7 +1130,7 @@
   // JSR-292 support
   MemberNameTable* member_names() { return _member_names; }
   void set_member_names(MemberNameTable* member_names) { _member_names = member_names; }
-  bool add_member_name(Handle member_name);
+  oop add_member_name(Handle member_name, bool intern);
 
 public:
   // JVMTI support
diff --git a/hotspot/src/share/vm/oops/klass.cpp b/hotspot/src/share/vm/oops/klass.cpp
index 7b01be6..e24a43d 100644
--- a/hotspot/src/share/vm/oops/klass.cpp
+++ b/hotspot/src/share/vm/oops/klass.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -140,7 +140,7 @@
   return NULL;
 }
 
-Method* Klass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
+Method* Klass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {
 #ifdef ASSERT
   tty->print_cr("Error: uncached_lookup_method called on a klass oop."
                 " Likely error: reflection method does not correctly"
diff --git a/hotspot/src/share/vm/oops/klass.hpp b/hotspot/src/share/vm/oops/klass.hpp
index 3222dc9..297932f 100644
--- a/hotspot/src/share/vm/oops/klass.hpp
+++ b/hotspot/src/share/vm/oops/klass.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -192,7 +192,10 @@
   void* operator new(size_t size, ClassLoaderData* loader_data, size_t word_size, TRAPS) throw();
 
  public:
-  enum MethodLookupMode { normal, skip_overpass, skip_defaults };
+  enum DefaultsLookupMode { find_defaults, skip_defaults };
+  enum OverpassLookupMode { find_overpass, skip_overpass };
+  enum StaticLookupMode   { find_static,   skip_static };
+  enum PrivateLookupMode  { find_private,  skip_private };
 
   bool is_klass() const volatile { return true; }
 
@@ -458,10 +461,10 @@
   // lookup operation for MethodLookupCache
   friend class MethodLookupCache;
   virtual Klass* find_field(Symbol* name, Symbol* signature, fieldDescriptor* fd) const;
-  virtual Method* uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const;
+  virtual Method* uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const;
  public:
   Method* lookup_method(Symbol* name, Symbol* signature) const {
-    return uncached_lookup_method(name, signature, normal);
+    return uncached_lookup_method(name, signature, find_overpass);
   }
 
   // array class with specific rank
diff --git a/hotspot/src/share/vm/oops/klassVtable.cpp b/hotspot/src/share/vm/oops/klassVtable.cpp
index 639ce01..b6220ef 100644
--- a/hotspot/src/share/vm/oops/klassVtable.cpp
+++ b/hotspot/src/share/vm/oops/klassVtable.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -696,7 +696,7 @@
   // this check for all access permissions.
   InstanceKlass *sk = InstanceKlass::cast(super);
   if (sk->has_miranda_methods()) {
-    if (sk->lookup_method_in_all_interfaces(name, signature, Klass::normal) != NULL) {
+    if (sk->lookup_method_in_all_interfaces(name, signature, Klass::find_defaults) != NULL) {
       return false;  // found a matching miranda; we do not need a new entry
     }
   }
@@ -729,7 +729,6 @@
   if (mhk->is_interface()) {
     assert(m->is_public(), "should be public");
     assert(ik()->implements_interface(method_holder) , "this class should implement the interface");
-    // the search could find a miranda or a default method
     if (is_miranda(m, ik()->methods(), ik()->default_methods(), ik()->super())) {
       return true;
     }
@@ -737,25 +736,57 @@
   return false;
 }
 
-// check if a method is a miranda method, given a class's methods table,
-// its default_method table  and its super
-// Miranda methods are calculated twice:
-// first: before vtable size calculation: including abstract and superinterface default
+// Check if a method is a miranda method, given a class's methods array,
+// its default_method table and its super class.
+// "Miranda" means an abstract non-private method that would not be
+// overridden for the local class.
+// A "miranda" method should only include non-private interface
+// instance methods, i.e. not private methods, not static methods,
+// not default methods (concrete interface methods), not overpass methods.
+// If a given class already has a local (including overpass) method, a
+// default method, or any of its superclasses has the same which would have
+// overridden an abstract method, then this is not a miranda method.
+//
+// Miranda methods are checked multiple times.
+// Pass 1: during class load/class file parsing: before vtable size calculation:
+// include superinterface abstract and default methods (non-private instance).
 // We include potential default methods to give them space in the vtable.
-// During the first run, the default_methods list is empty
-// This is seen by default method creation
-// Second: recalculated during vtable initialization: only include abstract methods.
+// During the first run, the current instanceKlass has not yet been
+// created, the superclasses and superinterfaces do have instanceKlasses
+// but may not have vtables, the default_methods list is empty, no overpasses.
+// This is seen by default method creation.
+//
+// Pass 2: recalculated during vtable initialization: only include abstract methods.
+// The goal of pass 2 is to walk through the superinterfaces to see if any of
+// the superinterface methods (which were all abstract pre-default methods)
+// need to be added to the vtable.
+// With the addition of default methods, we have three new challenges:
+// overpasses, static interface methods and private interface methods.
+// Static and private interface methods do not get added to the vtable and
+// are not seen by the method resolution process, so we skip those.
+// Overpass methods are already in the vtable, so vtable lookup will
+// find them and we don't need to add a miranda method to the end of
+// the vtable. So we look for overpass methods and if they are found we
+// return false. Note that we inherit our superclasses vtable, so
+// the superclass' search also needs to use find_overpass so that if
+// one is found we return false.
+// False means - we don't need a miranda method added to the vtable.
+//
 // During the second run, default_methods is set up, so concrete methods from
 // superinterfaces with matching names/signatures to default_methods are already
 // in the default_methods list and do not need to be appended to the vtable
-// as mirandas
-// This is seen by link resolution and selection.
-// "miranda" means not static, not defined by this class.
-// private methods in interfaces do not belong in the miranda list.
-// the caller must make sure that the method belongs to an interface implemented by the class
-// Miranda methods only include public interface instance methods
-// Not private methods, not static methods, not default == concrete abstract
-// Miranda methods also do not include overpass methods in interfaces
+// as mirandas. Abstract methods may already have been handled via
+// overpasses - either local or superclass overpasses, which may be
+// in the vtable already.
+//
+// Pass 3: They are also checked by link resolution and selection,
+// for invocation on a method (not interface method) reference that
+// resolves to a method with an interface as its method_holder.
+// Used as part of walking from the bottom of the vtable to find
+// the vtable index for the miranda method.
+//
+// Part of the Miranda Rights in the US mean that if you do not have
+// an attorney one will be appointed for you.
 bool klassVtable::is_miranda(Method* m, Array<Method*>* class_methods,
                              Array<Method*>* default_methods, Klass* super) {
   if (m->is_static() || m->is_private() || m->is_overpass()) {
@@ -763,44 +794,36 @@
   }
   Symbol* name = m->name();
   Symbol* signature = m->signature();
-  Method* mo;
 
-  if ((mo = InstanceKlass::find_instance_method(class_methods, name, signature)) == NULL) {
-    // did not find it in the method table of the current class
-    if ((default_methods == NULL) ||
-        InstanceKlass::find_method(default_methods, name, signature) == NULL) {
-      if (super == NULL) {
-        // super doesn't exist
-        return true;
-      }
-
-      mo = InstanceKlass::cast(super)->lookup_method(name, signature);
-      while (mo != NULL && mo->access_flags().is_static()
-             && mo->method_holder() != NULL
-             && mo->method_holder()->super() != NULL)
-      {
-         mo = mo->method_holder()->super()->uncached_lookup_method(name, signature, Klass::normal);
-      }
-      if (mo == NULL || mo->access_flags().is_private() ) {
-        // super class hierarchy does not implement it or protection is different
-        return true;
-      }
-    }
-  } else {
-     // if the local class has a private method, the miranda will not
-     // override it, so a vtable slot is needed
-     if (mo->access_flags().is_private()) {
-
-       // Second round, weed out any superinterface methods that turned
-       // into default methods, i.e. were concrete not abstract in the end
-       if ((default_methods == NULL) ||
-         InstanceKlass::find_method(default_methods, name, signature) == NULL) {
-         return true;
-       }
-    }
+  // First look in local methods to see if already covered
+  if (InstanceKlass::find_local_method(class_methods, name, signature,
+              Klass::find_overpass, Klass::skip_static, Klass::skip_private) != NULL)
+  {
+    return false;
   }
 
-  return false;
+  // Check local default methods
+  if ((default_methods != NULL) &&
+    (InstanceKlass::find_method(default_methods, name, signature) != NULL))
+   {
+     return false;
+   }
+
+  InstanceKlass* cursuper;
+  // Iterate on all superclasses, which should have instanceKlasses
+  // Note that we explicitly look for overpasses at each level.
+  // Overpasses may or may not exist for supers for pass 1,
+  // they should have been created for pass 2 and later.
+
+  for (cursuper = InstanceKlass::cast(super); cursuper != NULL;  cursuper = (InstanceKlass*)cursuper->super())
+  {
+     if (cursuper->find_local_method(name, signature,
+           Klass::find_overpass, Klass::skip_static, Klass::skip_private) != NULL) {
+       return false;
+     }
+  }
+
+  return true;
 }
 
 // Scans current_interface_methods for miranda methods that do not
@@ -836,7 +859,7 @@
       if (is_miranda(im, class_methods, default_methods, super)) { // is it a miranda at all?
         InstanceKlass *sk = InstanceKlass::cast(super);
         // check if it is a duplicate of a super's miranda
-        if (sk->lookup_method_in_all_interfaces(im->name(), im->signature(), Klass::normal) == NULL) {
+        if (sk->lookup_method_in_all_interfaces(im->name(), im->signature(), Klass::find_defaults) == NULL) {
           new_mirandas->append(im);
         }
         if (all_mirandas != NULL) {
diff --git a/hotspot/src/share/vm/oops/method.cpp b/hotspot/src/share/vm/oops/method.cpp
index b1db4dc..35d5508 100644
--- a/hotspot/src/share/vm/oops/method.cpp
+++ b/hotspot/src/share/vm/oops/method.cpp
@@ -98,7 +98,7 @@
   // Fix and bury in Method*
   set_interpreter_entry(NULL); // sets i2i entry and from_int
   set_adapter_entry(NULL);
-  clear_code(); // from_c/from_i get set to c2i/i2i
+  clear_code(false /* don't need a lock */); // from_c/from_i get set to c2i/i2i
 
   if (access_flags.is_native()) {
     clear_native_function();
@@ -590,7 +590,7 @@
 }
 
 bool Method::is_initializer() const {
-  return name() == vmSymbols::object_initializer_name() || is_static_initializer();
+  return is_object_initializer() || is_static_initializer();
 }
 
 bool Method::has_valid_initializer_flags() const {
@@ -606,6 +606,9 @@
          has_valid_initializer_flags();
 }
 
+bool Method::is_object_initializer() const {
+   return name() == vmSymbols::object_initializer_name();
+}
 
 objArrayHandle Method::resolved_checked_exceptions_impl(Method* this_oop, TRAPS) {
   int length = this_oop->checked_exceptions_length();
@@ -843,8 +846,8 @@
 }
 
 // Revert to using the interpreter and clear out the nmethod
-void Method::clear_code() {
-
+void Method::clear_code(bool acquire_lock /* = true */) {
+  MutexLockerEx pl(acquire_lock ? Patching_lock : NULL, Mutex::_no_safepoint_check_flag);
   // this may be NULL if c2i adapters have not been made yet
   // Only should happen at allocate time.
   if (_adapter == NULL) {
@@ -972,6 +975,7 @@
 
 // Install compiled code.  Instantly it can execute.
 void Method::set_code(methodHandle mh, nmethod *code) {
+  MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
   assert( code, "use clear_code to remove code" );
   assert( mh->check_code(), "" );
 
diff --git a/hotspot/src/share/vm/oops/method.hpp b/hotspot/src/share/vm/oops/method.hpp
index 974bced..90b7029 100644
--- a/hotspot/src/share/vm/oops/method.hpp
+++ b/hotspot/src/share/vm/oops/method.hpp
@@ -445,7 +445,7 @@
   address verified_code_entry();
   bool check_code() const;      // Not inline to avoid circular ref
   nmethod* volatile code() const                 { assert( check_code(), "" ); return (nmethod *)OrderAccess::load_ptr_acquire(&_code); }
-  void clear_code();            // Clear out any compiled code
+  void clear_code(bool acquire_lock = true);            // Clear out any compiled code
   static void set_code(methodHandle mh, nmethod* code);
   void set_adapter_entry(AdapterHandlerEntry* adapter) {  _adapter = adapter; }
   address get_i2c_entry();
@@ -627,6 +627,9 @@
   // valid static initializer flags.
   bool is_static_initializer() const;
 
+  // returns true if the method name is <init>
+  bool is_object_initializer() const;
+
   // compiled code support
   // NOTE: code() is inherently racy as deopt can be clearing code
   // simultaneously. Use with caution.
diff --git a/hotspot/src/share/vm/opto/block.cpp b/hotspot/src/share/vm/opto/block.cpp
index f0599a1..245ce42 100644
--- a/hotspot/src/share/vm/opto/block.cpp
+++ b/hotspot/src/share/vm/opto/block.cpp
@@ -1208,6 +1208,9 @@
       if (j >= 1 && n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_CreateEx) {
         assert(j == 1 || block->get_node(j-1)->is_Phi(), "CreateEx must be first instruction in block");
       }
+      if (n->needs_anti_dependence_check()) {
+        verify_anti_dependences(block, n);
+      }
       for (uint k = 0; k < n->req(); k++) {
         Node *def = n->in(k);
         if (def && def != n) {
diff --git a/hotspot/src/share/vm/opto/block.hpp b/hotspot/src/share/vm/opto/block.hpp
index d085b29..0c7363e 100644
--- a/hotspot/src/share/vm/opto/block.hpp
+++ b/hotspot/src/share/vm/opto/block.hpp
@@ -185,14 +185,13 @@
   Block* lone_fall_through();   // Return lone fall-through Block or null
 
   Block* dom_lca(Block* that);  // Compute LCA in dominator tree.
-#ifdef ASSERT
+
   bool dominates(Block* that) {
     int dom_diff = this->_dom_depth - that->_dom_depth;
     if (dom_diff > 0)  return false;
     for (; dom_diff < 0; dom_diff++)  that = that->_idom;
     return this == that;
   }
-#endif
 
   // Report the alignment required by this block.  Must be a power of 2.
   // The previous block will insert nops to get this alignment.
@@ -473,9 +472,9 @@
   MachNode* _goto;
 
   Block* insert_anti_dependences(Block* LCA, Node* load, bool verify = false);
-  void verify_anti_dependences(Block* LCA, Node* load) {
+  void verify_anti_dependences(Block* LCA, Node* load) const {
     assert(LCA == get_block_for_node(load), "should already be scheduled");
-    insert_anti_dependences(LCA, load, true);
+    const_cast<PhaseCFG*>(this)->insert_anti_dependences(LCA, load, true);
   }
 
   bool move_to_next(Block* bx, uint b_index);
diff --git a/hotspot/src/share/vm/opto/callGenerator.cpp b/hotspot/src/share/vm/opto/callGenerator.cpp
index 2d89751..a79f1d2 100644
--- a/hotspot/src/share/vm/opto/callGenerator.cpp
+++ b/hotspot/src/share/vm/opto/callGenerator.cpp
@@ -188,7 +188,10 @@
   // the call instruction will have a seemingly deficient out-count.
   // (The bailout says something misleading about an "infinite loop".)
   if (kit.gvn().type(receiver)->higher_equal(TypePtr::NULL_PTR)) {
-    kit.inc_sp(method()->arg_size());  // restore arguments
+    assert(Bytecodes::is_invoke(kit.java_bc()), err_msg("%d: %s", kit.java_bc(), Bytecodes::name(kit.java_bc())));
+    ciMethod* declared_method = kit.method()->get_method_at_bci(kit.bci());
+    int arg_size = declared_method->signature()->arg_size_for_bc(kit.java_bc());
+    kit.inc_sp(arg_size);  // restore arguments
     kit.uncommon_trap(Deoptimization::Reason_null_check,
                       Deoptimization::Action_none,
                       NULL, "null receiver");
@@ -1119,7 +1122,10 @@
 JVMState* UncommonTrapCallGenerator::generate(JVMState* jvms) {
   GraphKit kit(jvms);
   // Take the trap with arguments pushed on the stack.  (Cf. null_check_receiver).
-  int nargs = method()->arg_size();
+  // Callsite signature can be different from actual method being called (i.e _linkTo* sites).
+  // Use callsite signature always.
+  ciMethod* declared_method = kit.method()->get_method_at_bci(kit.bci());
+  int nargs = declared_method->arg_size();
   kit.inc_sp(nargs);
   assert(nargs <= kit.sp() && kit.sp() <= jvms->stk_size(), "sane sp w/ args pushed");
   if (_reason == Deoptimization::Reason_class_check &&
diff --git a/hotspot/src/share/vm/opto/callnode.cpp b/hotspot/src/share/vm/opto/callnode.cpp
index a99af80..0320e31 100644
--- a/hotspot/src/share/vm/opto/callnode.cpp
+++ b/hotspot/src/share/vm/opto/callnode.cpp
@@ -743,8 +743,8 @@
       }
       // May modify (by reflection) if an boxing object is passed
       // as argument or returned.
-      if (returns_pointer() && (proj_out(TypeFunc::Parms) != NULL)) {
-        Node* proj = proj_out(TypeFunc::Parms);
+      Node* proj = returns_pointer() ? proj_out(TypeFunc::Parms) : NULL;
+      if (proj != NULL) {
         const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
         if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
                                  (inst_t->klass() == boxing_klass))) {
diff --git a/hotspot/src/share/vm/opto/cfgnode.hpp b/hotspot/src/share/vm/opto/cfgnode.hpp
index e795483..74461aa 100644
--- a/hotspot/src/share/vm/opto/cfgnode.hpp
+++ b/hotspot/src/share/vm/opto/cfgnode.hpp
@@ -119,6 +119,9 @@
 // input in slot 0.
 class PhiNode : public TypeNode {
   const TypePtr* const _adr_type; // non-null only for Type::MEMORY nodes.
+  // The following fields are only used for data PhiNodes to indicate
+  // that the PhiNode represents the value of a known instance field.
+        int _inst_mem_id; // Instance memory id (node index of the memory Phi)
   const int _inst_id;     // Instance id of the memory slice.
   const int _inst_index;  // Alias index of the instance memory slice.
   // Array elements references have the same alias_idx but different offset.
@@ -138,11 +141,13 @@
   };
 
   PhiNode( Node *r, const Type *t, const TypePtr* at = NULL,
+           const int imid = -1,
            const int iid = TypeOopPtr::InstanceTop,
            const int iidx = Compile::AliasIdxTop,
            const int ioffs = Type::OffsetTop )
     : TypeNode(t,r->req()),
       _adr_type(at),
+      _inst_mem_id(imid),
       _inst_id(iid),
       _inst_index(iidx),
       _inst_offset(ioffs)
@@ -187,11 +192,14 @@
   virtual bool pinned() const { return in(0) != 0; }
   virtual const TypePtr *adr_type() const { verify_adr_type(true); return _adr_type; }
 
+  void  set_inst_mem_id(int inst_mem_id) { _inst_mem_id = inst_mem_id; }
+  const int inst_mem_id() const { return _inst_mem_id; }
   const int inst_id()     const { return _inst_id; }
   const int inst_index()  const { return _inst_index; }
   const int inst_offset() const { return _inst_offset; }
-  bool is_same_inst_field(const Type* tp, int id, int index, int offset) {
+  bool is_same_inst_field(const Type* tp, int mem_id, int id, int index, int offset) {
     return type()->basic_type() == tp->basic_type() &&
+           inst_mem_id() == mem_id &&
            inst_id()     == id     &&
            inst_index()  == index  &&
            inst_offset() == offset &&
diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp
index e021924..439e55e 100644
--- a/hotspot/src/share/vm/opto/compile.cpp
+++ b/hotspot/src/share/vm/opto/compile.cpp
@@ -1595,6 +1595,17 @@
   }
 }
 
+BasicType Compile::AliasType::basic_type() const {
+  if (element() != NULL) {
+    const Type* element = adr_type()->is_aryptr()->elem();
+    return element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type();
+  } if (field() != NULL) {
+    return field()->layout_type();
+  } else {
+    return T_ILLEGAL; // unknown
+  }
+}
+
 //---------------------------------print_on------------------------------------
 #ifndef PRODUCT
 void Compile::AliasType::print_on(outputStream* st) {
diff --git a/hotspot/src/share/vm/opto/compile.hpp b/hotspot/src/share/vm/opto/compile.hpp
index 34028fc..022c8fc 100644
--- a/hotspot/src/share/vm/opto/compile.hpp
+++ b/hotspot/src/share/vm/opto/compile.hpp
@@ -152,6 +152,8 @@
       _element = e;
     }
 
+    BasicType basic_type() const;
+
     void print_on(outputStream* st) PRODUCT_RETURN;
   };
 
diff --git a/hotspot/src/share/vm/opto/connode.cpp b/hotspot/src/share/vm/opto/connode.cpp
index 3d99249..604e971 100644
--- a/hotspot/src/share/vm/opto/connode.cpp
+++ b/hotspot/src/share/vm/opto/connode.cpp
@@ -999,8 +999,7 @@
   }
 
 #ifdef _LP64
-  // Convert ConvI2L(AddI(x, y)) to AddL(ConvI2L(x), ConvI2L(y)) or
-  // ConvI2L(CastII(AddI(x, y))) to AddL(ConvI2L(CastII(x)), ConvI2L(CastII(y))),
+  // Convert ConvI2L(AddI(x, y)) to AddL(ConvI2L(x), ConvI2L(y))
   // but only if x and y have subranges that cannot cause 32-bit overflow,
   // under the assumption that x+y is in my own subrange this->type().
 
@@ -1024,13 +1023,6 @@
 
   Node* z = in(1);
   int op = z->Opcode();
-  Node* ctrl = NULL;
-  if (op == Op_CastII && z->as_CastII()->has_range_check()) {
-    // Skip CastII node but save control dependency
-    ctrl = z->in(0);
-    z = z->in(1);
-    op = z->Opcode();
-  }
   if (op == Op_AddI || op == Op_SubI) {
     Node* x = z->in(1);
     Node* y = z->in(2);
@@ -1090,8 +1082,8 @@
     }
     assert(rxlo == (int)rxlo && rxhi == (int)rxhi, "x should not overflow");
     assert(rylo == (int)rylo && ryhi == (int)ryhi, "y should not overflow");
-    Node* cx = phase->C->constrained_convI2L(phase, x, TypeInt::make(rxlo, rxhi, widen), ctrl);
-    Node* cy = phase->C->constrained_convI2L(phase, y, TypeInt::make(rylo, ryhi, widen), ctrl);
+    Node* cx = phase->C->constrained_convI2L(phase, x, TypeInt::make(rxlo, rxhi, widen), NULL);
+    Node* cy = phase->C->constrained_convI2L(phase, y, TypeInt::make(rylo, ryhi, widen), NULL);
     switch (op) {
     case Op_AddI:  return new (phase->C) AddLNode(cx, cy);
     case Op_SubI:  return new (phase->C) SubLNode(cx, cy);
diff --git a/hotspot/src/share/vm/opto/doCall.cpp b/hotspot/src/share/vm/opto/doCall.cpp
index 5ec9aab..3667693 100644
--- a/hotspot/src/share/vm/opto/doCall.cpp
+++ b/hotspot/src/share/vm/opto/doCall.cpp
@@ -205,16 +205,22 @@
 
       int morphism = profile.morphism();
       if (speculative_receiver_type != NULL) {
-        // We have a speculative type, we should be able to resolve
-        // the call. We do that before looking at the profiling at
-        // this invoke because it may lead to bimorphic inlining which
-        // a speculative type should help us avoid.
-        receiver_method = callee->resolve_invoke(jvms->method()->holder(),
-                                                 speculative_receiver_type);
-        if (receiver_method == NULL) {
-          speculative_receiver_type = NULL;
+        if (!too_many_traps(caller, bci, Deoptimization::Reason_speculate_class_check)) {
+          // We have a speculative type, we should be able to resolve
+          // the call. We do that before looking at the profiling at
+          // this invoke because it may lead to bimorphic inlining which
+          // a speculative type should help us avoid.
+          receiver_method = callee->resolve_invoke(jvms->method()->holder(),
+                                                   speculative_receiver_type);
+          if (receiver_method == NULL) {
+            speculative_receiver_type = NULL;
+          } else {
+            morphism = 1;
+          }
         } else {
-          morphism = 1;
+          // speculation failed before. Use profiling at the call
+          // (could allow bimorphic inlining for instance).
+          speculative_receiver_type = NULL;
         }
       }
       if (receiver_method == NULL &&
@@ -252,7 +258,7 @@
                                     Deoptimization::Reason_bimorphic :
                                     (speculative_receiver_type == NULL ? Deoptimization::Reason_class_check : Deoptimization::Reason_speculate_class_check);
           if ((morphism == 1 || (morphism == 2 && next_hit_cg != NULL)) &&
-              !too_many_traps(jvms->method(), jvms->bci(), reason)
+              !too_many_traps(caller, bci, reason)
              ) {
             // Generate uncommon trap for class check failure path
             // in case of monomorphic or bimorphic virtual call site.
diff --git a/hotspot/src/share/vm/opto/graphKit.cpp b/hotspot/src/share/vm/opto/graphKit.cpp
index 38e0ce2..16313f0 100644
--- a/hotspot/src/share/vm/opto/graphKit.cpp
+++ b/hotspot/src/share/vm/opto/graphKit.cpp
@@ -1452,7 +1452,11 @@
 // factory methods in "int adr_idx"
 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
                           int adr_idx,
-                          MemNode::MemOrd mo, LoadNode::ControlDependency control_dependency, bool require_atomic_access) {
+                          MemNode::MemOrd mo,
+                          LoadNode::ControlDependency control_dependency,
+                          bool require_atomic_access,
+                          bool unaligned,
+                          bool mismatched) {
   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
   const TypePtr* adr_type = NULL; // debug-mode-only argument
   debug_only(adr_type = C->get_adr_type(adr_idx));
@@ -1465,6 +1469,12 @@
   } else {
     ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency);
   }
+  if (unaligned) {
+    ld->as_Load()->set_unaligned_access();
+  }
+  if (mismatched) {
+    ld->as_Load()->set_mismatched_access();
+  }
   ld = _gvn.transform(ld);
   if ((bt == T_OBJECT) && C->do_escape_analysis() || C->eliminate_boxing()) {
     // Improve graph before escape analysis and boxing elimination.
@@ -1476,7 +1486,9 @@
 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
                                 int adr_idx,
                                 MemNode::MemOrd mo,
-                                bool require_atomic_access) {
+                                bool require_atomic_access,
+                                bool unaligned,
+                                bool mismatched) {
   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
   const TypePtr* adr_type = NULL;
   debug_only(adr_type = C->get_adr_type(adr_idx));
@@ -1489,6 +1501,12 @@
   } else {
     st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo);
   }
+  if (unaligned) {
+    st->as_Store()->set_unaligned_access();
+  }
+  if (mismatched) {
+    st->as_Store()->set_mismatched_access();
+  }
   st = _gvn.transform(st);
   set_memory(st, adr_idx);
   // Back-to-back stores can only remove intermediate store with DU info
@@ -1588,7 +1606,8 @@
                           const TypeOopPtr* val_type,
                           BasicType bt,
                           bool use_precise,
-                          MemNode::MemOrd mo) {
+                          MemNode::MemOrd mo,
+                          bool mismatched) {
   // Transformation of a value which could be NULL pointer (CastPP #NULL)
   // could be delayed during Parse (for example, in adjust_map_after_if()).
   // Execute transformation here to avoid barrier generation in such case.
@@ -1608,7 +1627,7 @@
               NULL /* pre_val */,
               bt);
 
-  Node* store = store_to_memory(control(), adr, val, bt, adr_idx, mo);
+  Node* store = store_to_memory(control(), adr, val, bt, adr_idx, mo, mismatched);
   post_barrier(control(), store, obj, adr, adr_idx, val, bt, use_precise);
   return store;
 }
@@ -1620,7 +1639,8 @@
                              const TypePtr* adr_type,
                              Node* val,
                              BasicType bt,
-                             MemNode::MemOrd mo) {
+                             MemNode::MemOrd mo,
+                             bool mismatched) {
   Compile::AliasType* at = C->alias_type(adr_type);
   const TypeOopPtr* val_type = NULL;
   if (adr_type->isa_instptr()) {
@@ -1639,7 +1659,7 @@
   if (val_type == NULL) {
     val_type = TypeInstPtr::BOTTOM;
   }
-  return store_oop(ctl, obj, adr, adr_type, val, val_type, bt, true, mo);
+  return store_oop(ctl, obj, adr, adr_type, val, val_type, bt, true, mo, mismatched);
 }
 
 
@@ -1683,6 +1703,9 @@
   const Type* elemtype = arytype->elem();
   BasicType elembt = elemtype->array_element_basic_type();
   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
+  if (elembt == T_NARROWOOP) {
+    elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
+  }
   Node* ld = make_load(ctl, adr, elemtype, elembt, arytype, MemNode::unordered);
   return ld;
 }
diff --git a/hotspot/src/share/vm/opto/graphKit.hpp b/hotspot/src/share/vm/opto/graphKit.hpp
index d7c32b3..c584cef 100644
--- a/hotspot/src/share/vm/opto/graphKit.hpp
+++ b/hotspot/src/share/vm/opto/graphKit.hpp
@@ -517,23 +517,28 @@
   // of volatile fields.
   Node* make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
                   MemNode::MemOrd mo, LoadNode::ControlDependency control_dependency = LoadNode::DependsOnlyOnTest,
-                  bool require_atomic_access = false) {
+                  bool require_atomic_access = false, bool unaligned = false,
+                  bool mismatched = false) {
     // This version computes alias_index from bottom_type
     return make_load(ctl, adr, t, bt, adr->bottom_type()->is_ptr(),
-                     mo, control_dependency, require_atomic_access);
+                     mo, control_dependency, require_atomic_access,
+                     unaligned, mismatched);
   }
   Node* make_load(Node* ctl, Node* adr, const Type* t, BasicType bt, const TypePtr* adr_type,
                   MemNode::MemOrd mo, LoadNode::ControlDependency control_dependency = LoadNode::DependsOnlyOnTest,
-                  bool require_atomic_access = false) {
+                  bool require_atomic_access = false, bool unaligned = false,
+                  bool mismatched = false) {
     // This version computes alias_index from an address type
     assert(adr_type != NULL, "use other make_load factory");
     return make_load(ctl, adr, t, bt, C->get_alias_index(adr_type),
-                     mo, control_dependency, require_atomic_access);
+                     mo, control_dependency, require_atomic_access,
+                     unaligned, mismatched);
   }
   // This is the base version which is given an alias index.
   Node* make_load(Node* ctl, Node* adr, const Type* t, BasicType bt, int adr_idx,
                   MemNode::MemOrd mo, LoadNode::ControlDependency control_dependency = LoadNode::DependsOnlyOnTest,
-                  bool require_atomic_access = false);
+                  bool require_atomic_access = false, bool unaligned = false,
+                  bool mismatched = false);
 
   // Create & transform a StoreNode and store the effect into the
   // parser's memory state.
@@ -546,19 +551,24 @@
   Node* store_to_memory(Node* ctl, Node* adr, Node* val, BasicType bt,
                         const TypePtr* adr_type,
                         MemNode::MemOrd mo,
-                        bool require_atomic_access = false) {
+                        bool require_atomic_access = false,
+                        bool unaligned = false,
+                        bool mismatched = false) {
     // This version computes alias_index from an address type
     assert(adr_type != NULL, "use other store_to_memory factory");
     return store_to_memory(ctl, adr, val, bt,
                            C->get_alias_index(adr_type),
-                           mo, require_atomic_access);
+                           mo, require_atomic_access,
+                           unaligned, mismatched);
   }
   // This is the base version which is given alias index
   // Return the new StoreXNode
   Node* store_to_memory(Node* ctl, Node* adr, Node* val, BasicType bt,
                         int adr_idx,
                         MemNode::MemOrd,
-                        bool require_atomic_access = false);
+                        bool require_atomic_access = false,
+                        bool unaligned = false,
+                        bool mismatched = false);
 
 
   // All in one pre-barrier, store, post_barrier
@@ -581,7 +591,8 @@
                   const TypeOopPtr* val_type,
                   BasicType bt,
                   bool use_precise,
-                  MemNode::MemOrd mo);
+                  MemNode::MemOrd mo,
+                  bool mismatched = false);
 
   Node* store_oop_to_object(Node* ctl,
                             Node* obj,   // containing obj
@@ -612,7 +623,8 @@
                              const TypePtr* adr_type,
                              Node* val,
                              BasicType bt,
-                             MemNode::MemOrd mo);
+                             MemNode::MemOrd mo,
+                             bool mismatched = false);
 
   // For the few case where the barriers need special help
   void pre_barrier(bool do_load, Node* ctl,
@@ -656,7 +668,10 @@
   // callee (with all arguments still on the stack).
   Node* null_check_receiver_before_call(ciMethod* callee) {
     assert(!callee->is_static(), "must be a virtual method");
-    const int nargs = callee->arg_size();
+    // Callsite signature can be different from actual method being called (i.e _linkTo* sites).
+    // Use callsite signature always.
+    ciMethod* declared_method = method()->get_method_at_bci(bci());
+    const int nargs = declared_method->arg_size();
     inc_sp(nargs);
     Node* n = null_check_receiver();
     dec_sp(nargs);
diff --git a/hotspot/src/share/vm/opto/idealKit.cpp b/hotspot/src/share/vm/opto/idealKit.cpp
index ee4c212..552c13e 100644
--- a/hotspot/src/share/vm/opto/idealKit.cpp
+++ b/hotspot/src/share/vm/opto/idealKit.cpp
@@ -368,7 +368,8 @@
 
 Node* IdealKit::store(Node* ctl, Node* adr, Node *val, BasicType bt,
                       int adr_idx,
-                      MemNode::MemOrd mo, bool require_atomic_access) {
+                      MemNode::MemOrd mo, bool require_atomic_access,
+                      bool mismatched) {
   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory");
   const TypePtr* adr_type = NULL;
   debug_only(adr_type = C->get_adr_type(adr_idx));
@@ -379,6 +380,9 @@
   } else {
     st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo);
   }
+  if (mismatched) {
+    st->as_Store()->set_mismatched_access();
+  }
   st = transform(st);
   set_memory(st, adr_idx);
 
diff --git a/hotspot/src/share/vm/opto/idealKit.hpp b/hotspot/src/share/vm/opto/idealKit.hpp
index 7581570..7ce1cd0 100644
--- a/hotspot/src/share/vm/opto/idealKit.hpp
+++ b/hotspot/src/share/vm/opto/idealKit.hpp
@@ -227,7 +227,9 @@
               BasicType bt,
               int adr_idx,
               MemNode::MemOrd mo,
-              bool require_atomic_access = false);
+              bool require_atomic_access = false,
+              bool mismatched = false
+              );
 
   // Store a card mark ordered after store_oop
   Node* storeCM(Node* ctl,
diff --git a/hotspot/src/share/vm/opto/ifnode.cpp b/hotspot/src/share/vm/opto/ifnode.cpp
index 957dc88..c1ee196 100644
--- a/hotspot/src/share/vm/opto/ifnode.cpp
+++ b/hotspot/src/share/vm/opto/ifnode.cpp
@@ -1081,8 +1081,9 @@
   // be skipped. For example, range check predicate has two checks
   // for lower and upper bounds.
   ProjNode* unc_proj = proj_out(1 - prev_dom->as_Proj()->_con)->as_Proj();
-  if (unc_proj->is_uncommon_trap_proj(Deoptimization::Reason_predicate))
-   prev_dom = idom;
+  if ((unc_proj != NULL) && (unc_proj->is_uncommon_trap_proj(Deoptimization::Reason_predicate))) {
+    prev_dom = idom;
+  }
 
   // Now walk the current IfNode's projections.
   // Loop ends when 'this' has no more uses.
diff --git a/hotspot/src/share/vm/opto/lcm.cpp b/hotspot/src/share/vm/opto/lcm.cpp
index 8f6844f..dd93b0f 100644
--- a/hotspot/src/share/vm/opto/lcm.cpp
+++ b/hotspot/src/share/vm/opto/lcm.cpp
@@ -246,6 +246,14 @@
       continue;
     }
 
+    // Check that node's control edge is not-null block's head or dominates it,
+    // otherwise we can't hoist it because there are other control dependencies.
+    Node* ctrl = mach->in(0);
+    if (ctrl != NULL && !(ctrl == not_null_block->head() ||
+        get_block_for_node(ctrl)->dominates(not_null_block))) {
+      continue;
+    }
+
     // check if the offset is not too high for implicit exception
     {
       intptr_t offset = 0;
@@ -383,9 +391,12 @@
   block->add_inst(best);
   map_node_to_block(best, block);
 
-  // Move the control dependence
-  if (best->in(0) && best->in(0) == old_block->head())
-    best->set_req(0, block->head());
+  // Move the control dependence if it is pinned to not-null block.
+  // Don't change it in other cases: NULL or dominating control.
+  if (best->in(0) == not_null_block->head()) {
+    // Set it to control edge of null check.
+    best->set_req(0, proj->in(0)->in(0));
+  }
 
   // Check for flag-killing projections that also need to be hoisted
   // Should be DU safe because no edge updates.
@@ -441,6 +452,18 @@
 
   latency_from_uses(nul_chk);
   latency_from_uses(best);
+
+  // insert anti-dependences to defs in this block
+  if (! best->needs_anti_dependence_check()) {
+    for (uint k = 1; k < block->number_of_nodes(); k++) {
+      Node *n = block->get_node(k);
+      if (n->needs_anti_dependence_check() &&
+          n->in(LoadNode::Memory) == best->in(StoreNode::Memory)) {
+        // Found anti-dependent load
+        insert_anti_dependences(block, n);
+      }
+    }
+  }
 }
 
 
@@ -1088,11 +1111,12 @@
     Block *sb = block->_succs[i];
     // Clone the entire area; ignoring the edge fixup for now.
     for( uint j = end; j > beg; j-- ) {
-      // It is safe here to clone a node with anti_dependence
-      // since clones dominate on each path.
       Node *clone = block->get_node(j-1)->clone();
       sb->insert_node(clone, 1);
       map_node_to_block(clone, sb);
+      if (clone->needs_anti_dependence_check()) {
+        insert_anti_dependences(sb, clone);
+      }
     }
   }
 
diff --git a/hotspot/src/share/vm/opto/library_call.cpp b/hotspot/src/share/vm/opto/library_call.cpp
index f2a2937..d708499 100644
--- a/hotspot/src/share/vm/opto/library_call.cpp
+++ b/hotspot/src/share/vm/opto/library_call.cpp
@@ -230,7 +230,7 @@
   // Generates the guards that check whether the result of
   // Unsafe.getObject should be recorded in an SATB log buffer.
   void insert_pre_barrier(Node* base_oop, Node* offset, Node* pre_val, bool need_mem_bar);
-  bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile);
+  bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile, bool is_unaligned);
   bool inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static);
   static bool klass_needs_init_guard(Node* kls);
   bool inline_unsafe_allocate();
@@ -795,63 +795,63 @@
   case vmIntrinsics::_indexOf:                  return inline_string_indexOf();
   case vmIntrinsics::_equals:                   return inline_string_equals();
 
-  case vmIntrinsics::_getObject:                return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,  !is_volatile);
-  case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile);
-  case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,    !is_volatile);
-  case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile);
-  case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile);
-  case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile);
-  case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile);
-  case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
-  case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
+  case vmIntrinsics::_getObject:                return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,  !is_volatile, false);
+  case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile, false);
+  case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,    !is_volatile, false);
+  case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile, false);
+  case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile, false);
+  case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile, false);
+  case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile, false);
+  case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,   !is_volatile, false);
+  case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,  !is_volatile, false);
 
-  case vmIntrinsics::_putObject:                return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,  !is_volatile);
-  case vmIntrinsics::_putBoolean:               return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN, !is_volatile);
-  case vmIntrinsics::_putByte:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,    !is_volatile);
-  case vmIntrinsics::_putShort:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile);
-  case vmIntrinsics::_putChar:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile);
-  case vmIntrinsics::_putInt:                   return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile);
-  case vmIntrinsics::_putLong:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile);
-  case vmIntrinsics::_putFloat:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
-  case vmIntrinsics::_putDouble:                return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
+  case vmIntrinsics::_putObject:                return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,  !is_volatile, false);
+  case vmIntrinsics::_putBoolean:               return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN, !is_volatile, false);
+  case vmIntrinsics::_putByte:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,    !is_volatile, false);
+  case vmIntrinsics::_putShort:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile, false);
+  case vmIntrinsics::_putChar:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile, false);
+  case vmIntrinsics::_putInt:                   return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile, false);
+  case vmIntrinsics::_putLong:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile, false);
+  case vmIntrinsics::_putFloat:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,   !is_volatile, false);
+  case vmIntrinsics::_putDouble:                return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,  !is_volatile, false);
 
-  case vmIntrinsics::_getByte_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE,    !is_volatile);
-  case vmIntrinsics::_getShort_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT,   !is_volatile);
-  case vmIntrinsics::_getChar_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR,    !is_volatile);
-  case vmIntrinsics::_getInt_raw:               return inline_unsafe_access( is_native_ptr, !is_store, T_INT,     !is_volatile);
-  case vmIntrinsics::_getLong_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_LONG,    !is_volatile);
-  case vmIntrinsics::_getFloat_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
-  case vmIntrinsics::_getDouble_raw:            return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
-  case vmIntrinsics::_getAddress_raw:           return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile);
+  case vmIntrinsics::_getByte_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE,    !is_volatile, false);
+  case vmIntrinsics::_getShort_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT,   !is_volatile, false);
+  case vmIntrinsics::_getChar_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR,    !is_volatile, false);
+  case vmIntrinsics::_getInt_raw:               return inline_unsafe_access( is_native_ptr, !is_store, T_INT,     !is_volatile, false);
+  case vmIntrinsics::_getLong_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_LONG,    !is_volatile, false);
+  case vmIntrinsics::_getFloat_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT,   !is_volatile, false);
+  case vmIntrinsics::_getDouble_raw:            return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE,  !is_volatile, false);
+  case vmIntrinsics::_getAddress_raw:           return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile, false);
 
-  case vmIntrinsics::_putByte_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_BYTE,    !is_volatile);
-  case vmIntrinsics::_putShort_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_SHORT,   !is_volatile);
-  case vmIntrinsics::_putChar_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_CHAR,    !is_volatile);
-  case vmIntrinsics::_putInt_raw:               return inline_unsafe_access( is_native_ptr,  is_store, T_INT,     !is_volatile);
-  case vmIntrinsics::_putLong_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_LONG,    !is_volatile);
-  case vmIntrinsics::_putFloat_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
-  case vmIntrinsics::_putDouble_raw:            return inline_unsafe_access( is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
-  case vmIntrinsics::_putAddress_raw:           return inline_unsafe_access( is_native_ptr,  is_store, T_ADDRESS, !is_volatile);
+  case vmIntrinsics::_putByte_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_BYTE,    !is_volatile, false);
+  case vmIntrinsics::_putShort_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_SHORT,   !is_volatile, false);
+  case vmIntrinsics::_putChar_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_CHAR,    !is_volatile, false);
+  case vmIntrinsics::_putInt_raw:               return inline_unsafe_access( is_native_ptr,  is_store, T_INT,     !is_volatile, false);
+  case vmIntrinsics::_putLong_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_LONG,    !is_volatile, false);
+  case vmIntrinsics::_putFloat_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_FLOAT,   !is_volatile, false);
+  case vmIntrinsics::_putDouble_raw:            return inline_unsafe_access( is_native_ptr,  is_store, T_DOUBLE,  !is_volatile, false);
+  case vmIntrinsics::_putAddress_raw:           return inline_unsafe_access( is_native_ptr,  is_store, T_ADDRESS, !is_volatile, false);
 
-  case vmIntrinsics::_getObjectVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   is_volatile);
-  case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  is_volatile);
-  case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     is_volatile);
-  case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    is_volatile);
-  case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     is_volatile);
-  case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      is_volatile);
-  case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     is_volatile);
-  case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    is_volatile);
-  case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   is_volatile);
+  case vmIntrinsics::_getObjectVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   is_volatile, false);
+  case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  is_volatile, false);
+  case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     is_volatile, false);
+  case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    is_volatile, false);
+  case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     is_volatile, false);
+  case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      is_volatile, false);
+  case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     is_volatile, false);
+  case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    is_volatile, false);
+  case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   is_volatile, false);
 
-  case vmIntrinsics::_putObjectVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   is_volatile);
-  case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  is_volatile);
-  case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     is_volatile);
-  case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    is_volatile);
-  case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     is_volatile);
-  case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      is_volatile);
-  case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     is_volatile);
-  case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    is_volatile);
-  case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   is_volatile);
+  case vmIntrinsics::_putObjectVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   is_volatile, false);
+  case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  is_volatile, false);
+  case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     is_volatile, false);
+  case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    is_volatile, false);
+  case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     is_volatile, false);
+  case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      is_volatile, false);
+  case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     is_volatile, false);
+  case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    is_volatile, false);
+  case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   is_volatile, false);
 
   case vmIntrinsics::_prefetchRead:             return inline_unsafe_prefetch(!is_native_ptr, !is_store, !is_static);
   case vmIntrinsics::_prefetchWrite:            return inline_unsafe_prefetch(!is_native_ptr,  is_store, !is_static);
@@ -2554,8 +2554,9 @@
   return NULL;
 }
 
-bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
+bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile, bool unaligned) {
   if (callee()->is_static())  return false;  // caller must have the capability!
+  assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
 
 #ifndef PRODUCT
   {
@@ -2629,16 +2630,45 @@
     val = is_store ? argument(3) : NULL;
   }
 
+  // Can base be NULL? Otherwise, always on-heap access.
+  bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop));
+
   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
 
+  // Try to categorize the address.
+  Compile::AliasType* alias_type = C->alias_type(adr_type);
+  assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
+
+  if (alias_type->adr_type() == TypeInstPtr::KLASS ||
+      alias_type->adr_type() == TypeAryPtr::RANGE) {
+    return false; // not supported
+  }
+
+  bool mismatched = false;
+  BasicType bt = alias_type->basic_type();
+  if (bt != T_ILLEGAL) {
+    assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
+    if (bt == T_BYTE && adr_type->isa_aryptr()) {
+      // Alias type doesn't differentiate between byte[] and boolean[]).
+      // Use address type to get the element type.
+      bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
+    }
+    if (bt == T_ARRAY || bt == T_NARROWOOP) {
+      // accessing an array field with getObject is not a mismatch
+      bt = T_OBJECT;
+    }
+    if ((bt == T_OBJECT) != (type == T_OBJECT)) {
+      // Don't intrinsify mismatched object accesses
+      return false;
+    }
+    mismatched = (bt != type);
+  }
+
+  assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
+
   // First guess at the value type.
   const Type *value_type = Type::get_const_basic_type(type);
 
-  // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
-  // there was not enough information to nail it down.
-  Compile::AliasType* alias_type = C->alias_type(adr_type);
-  assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
-
   // We will need memory barriers unless we can determine a unique
   // alias category for this reference.  (Note:  If for some reason
   // the barriers get omitted and the unsafe reference begins to "pollute"
@@ -2701,7 +2731,7 @@
     MemNode::MemOrd mo = is_volatile ? MemNode::acquire : MemNode::unordered;
     // To be valid, unsafe loads may depend on other conditions than
     // the one that guards them: pin the Load node
-    Node* p = make_load(control(), adr, value_type, type, adr_type, mo, LoadNode::Pinned, is_volatile);
+    Node* p = make_load(control(), adr, value_type, type, adr_type, mo, LoadNode::Pinned, is_volatile, unaligned, mismatched);
     // load value
     switch (type) {
     case T_BOOLEAN:
@@ -2747,12 +2777,12 @@
 
     MemNode::MemOrd mo = is_volatile ? MemNode::release : MemNode::unordered;
     if (type != T_OBJECT ) {
-      (void) store_to_memory(control(), adr, val, type, adr_type, mo, is_volatile);
+      (void) store_to_memory(control(), adr, val, type, adr_type, mo, is_volatile, unaligned, mismatched);
     } else {
       // Possibly an oop being stored to Java heap or native memory
-      if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
+      if (!can_access_non_heap) {
         // oop to Java heap.
-        (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo);
+        (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo, mismatched);
       } else {
         // We can't tell at compile time if we are storing in the Java heap or outside
         // of it. So we need to emit code to conditionally do the proper type of
@@ -2764,11 +2794,11 @@
         __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
           // Sync IdealKit and graphKit.
           sync_kit(ideal);
-          Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo);
+          Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo, mismatched);
           // Update IdealKit memory.
           __ sync_kit(this);
         } __ else_(); {
-          __ store(__ ctrl(), adr, val, type, alias_type->index(), mo, is_volatile);
+          __ store(__ ctrl(), adr, val, type, alias_type->index(), mo, is_volatile, mismatched);
         } __ end_if();
         // Final sync IdealKit and GraphKit.
         final_sync(ideal);
@@ -2939,12 +2969,6 @@
     newval   = argument(4);  // type: oop, int, or long
   }
 
-  // Null check receiver.
-  receiver = null_check(receiver);
-  if (stopped()) {
-    return true;
-  }
-
   // Build field offset expression.
   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
   // to be plain byte offsets, which are also the same as those accepted
@@ -2955,11 +2979,18 @@
   Node* adr = make_unsafe_address(base, offset);
   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
 
+  Compile::AliasType* alias_type = C->alias_type(adr_type);
+  BasicType bt = alias_type->basic_type();
+  if (bt != T_ILLEGAL &&
+      ((bt == T_OBJECT || bt == T_ARRAY) != (type == T_OBJECT))) {
+    // Don't intrinsify mismatched object accesses.
+    return false;
+  }
+
   // For CAS, unlike inline_unsafe_access, there seems no point in
   // trying to refine types. Just use the coarse types here.
-  const Type *value_type = Type::get_const_basic_type(type);
-  Compile::AliasType* alias_type = C->alias_type(adr_type);
   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
+  const Type *value_type = Type::get_const_basic_type(type);
 
   if (kind == LS_xchg && type == T_OBJECT) {
     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
@@ -2968,6 +2999,12 @@
     }
   }
 
+  // Null check receiver.
+  receiver = null_check(receiver);
+  if (stopped()) {
+    return true;
+  }
+
   int alias_idx = C->get_alias_index(adr_type);
 
   // Memory-model-wise, a LoadStore acts like a little synchronized
@@ -6459,7 +6496,20 @@
 
 //------------------------------get_key_start_from_aescrypt_object-----------------------
 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
+#ifdef PPC64
+  // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
+  // Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
+  // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
+  // The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).
+  Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I", /*is_exact*/ false);
+  assert (objSessionK != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
+  if (objSessionK == NULL) {
+    return (Node *) NULL;
+  }
+  Node* objAESCryptKey = load_array_element(control(), objSessionK, intcon(0), TypeAryPtr::OOPS);
+#else
   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
+#endif // PPC64
   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
   if (objAESCryptKey == NULL) return (Node *) NULL;
 
diff --git a/hotspot/src/share/vm/opto/loopTransform.cpp b/hotspot/src/share/vm/opto/loopTransform.cpp
index a61c8a6..e39ffcb 100644
--- a/hotspot/src/share/vm/opto/loopTransform.cpp
+++ b/hotspot/src/share/vm/opto/loopTransform.cpp
@@ -2714,6 +2714,11 @@
     return false;
   }
 
+  Node* exit = head->loopexit()->proj_out(0);
+  if (exit == NULL) {
+    return false;
+  }
+
 #ifndef PRODUCT
   if (TraceLoopOpts) {
     tty->print("ArrayFill    ");
@@ -2831,7 +2836,6 @@
 */
 
   // Redirect the old control and memory edges that are outside the loop.
-  Node* exit = head->loopexit()->proj_out(0);
   // Sometimes the memory phi of the head is used as the outgoing
   // state of the loop.  It's safe in this case to replace it with the
   // result_mem.
diff --git a/hotspot/src/share/vm/opto/macro.cpp b/hotspot/src/share/vm/opto/macro.cpp
index 01b329c..d1e1f32 100644
--- a/hotspot/src/share/vm/opto/macro.cpp
+++ b/hotspot/src/share/vm/opto/macro.cpp
@@ -401,7 +401,7 @@
   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
     Node* phi = region->fast_out(k);
     if (phi->is_Phi() && phi != mem &&
-        phi->as_Phi()->is_same_inst_field(phi_type, instance_id, alias_idx, offset)) {
+        phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
       return phi;
     }
   }
@@ -420,7 +420,7 @@
   GrowableArray <Node *> values(length, length, NULL, false);
 
   // create a new Phi for the value
-  PhiNode *phi = new (C) PhiNode(mem->in(0), phi_type, NULL, instance_id, alias_idx, offset);
+  PhiNode *phi = new (C) PhiNode(mem->in(0), phi_type, NULL, mem->_idx, instance_id, alias_idx, offset);
   transform_later(phi);
   value_phis->push(phi, mem->_idx);
 
diff --git a/hotspot/src/share/vm/opto/matcher.cpp b/hotspot/src/share/vm/opto/matcher.cpp
index f4097b3..d6ee92f 100644
--- a/hotspot/src/share/vm/opto/matcher.cpp
+++ b/hotspot/src/share/vm/opto/matcher.cpp
@@ -1020,7 +1020,7 @@
             if (C->failing())  return NULL;
             if (m == NULL) { Matcher::soft_match_failure(); return NULL; }
           } else {                  // Nothing the matcher cares about
-            if( n->is_Proj() && n->in(0)->is_Multi()) {       // Projections?
+            if (n->is_Proj() && n->in(0) != NULL && n->in(0)->is_Multi()) {       // Projections?
               // Convert to machine-dependent projection
               m = n->in(0)->as_Multi()->match( n->as_Proj(), this );
 #ifdef ASSERT
@@ -1657,6 +1657,7 @@
 
   // Build the object to represent this state & prepare for recursive calls
   MachNode *mach = s->MachNodeGenerator( rule, C );
+  guarantee(mach != NULL, "Missing MachNode");
   mach->_opnds[0] = s->MachOperGenerator( _reduceOp[rule], C );
   assert( mach->_opnds[0] != NULL, "Missing result operand" );
   Node *leaf = s->_leaf;
diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp
index 80e25c9..2cfbae6 100644
--- a/hotspot/src/share/vm/opto/memnode.cpp
+++ b/hotspot/src/share/vm/opto/memnode.cpp
@@ -67,8 +67,15 @@
   dump_adr_type(this, _adr_type, st);
 
   Compile* C = Compile::current();
-  if( C->alias_type(_adr_type)->is_volatile() )
+  if (C->alias_type(_adr_type)->is_volatile()) {
     st->print(" Volatile!");
+  }
+  if (_unaligned_access) {
+    st->print(" unaligned");
+  }
+  if (_mismatched_access) {
+    st->print(" mismatched");
+  }
 }
 
 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
@@ -1149,13 +1156,16 @@
       // Use _idx of address base (could be Phi node) for boxed values.
       intptr_t   ignore = 0;
       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
+      if (base == NULL) {
+        return this;
+      }
       this_iid = base->_idx;
     }
     const Type* this_type = bottom_type();
     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
       Node* phi = region->fast_out(i);
       if (phi->is_Phi() && phi != mem &&
-          phi->as_Phi()->is_same_inst_field(this_type, this_iid, this_index, this_offset)) {
+          phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) {
         return phi;
       }
     }
@@ -1400,7 +1410,7 @@
     this_iid = base->_idx;
   }
   PhaseIterGVN* igvn = phase->is_IterGVN();
-  Node* phi = new (C) PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
+  Node* phi = new (C) PhiNode(region, this_type, NULL, mem->_idx, this_iid, this_index, this_offset);
   for (uint i = 1; i < region->req(); i++) {
     Node* x;
     Node* the_clone = NULL;
@@ -3322,6 +3332,9 @@
 // within the initialized memory.
 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
   const int FAIL = 0;
+  if (st->is_unaligned_access()) {
+    return FAIL;
+  }
   if (st->req() != MemNode::ValueIn + 1)
     return FAIL;                // an inscrutable StoreNode (card mark?)
   Node* ctl = st->in(MemNode::Control);
@@ -4025,9 +4038,10 @@
     // if it is the last unused 4 bytes of an instance, forget about it
     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
     if (zeroes_done + BytesPerLong >= size_limit) {
-      assert(allocation() != NULL, "");
-      if (allocation()->Opcode() == Op_Allocate) {
-        Node* klass_node = allocation()->in(AllocateNode::KlassNode);
+      AllocateNode* alloc = allocation();
+      assert(alloc != NULL, "must be present");
+      if (alloc != NULL && alloc->Opcode() == Op_Allocate) {
+        Node* klass_node = alloc->in(AllocateNode::KlassNode);
         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
         if (zeroes_done == k->layout_helper())
           zeroes_done = size_limit;
diff --git a/hotspot/src/share/vm/opto/memnode.hpp b/hotspot/src/share/vm/opto/memnode.hpp
index f2ed639..32d8af8 100644
--- a/hotspot/src/share/vm/opto/memnode.hpp
+++ b/hotspot/src/share/vm/opto/memnode.hpp
@@ -39,11 +39,14 @@
 //------------------------------MemNode----------------------------------------
 // Load or Store, possibly throwing a NULL pointer exception
 class MemNode : public Node {
+private:
+  bool _unaligned_access; // Unaligned access from unsafe
+  bool _mismatched_access; // Mismatched access from unsafe: byte read in integer array for instance
 protected:
 #ifdef ASSERT
   const TypePtr* _adr_type;     // What kind of memory is being addressed?
 #endif
-  virtual uint size_of() const; // Size is bigger (ASSERT only)
+  virtual uint size_of() const;
 public:
   enum { Control,               // When is it safe to do this load?
          Memory,                // Chunk of memory is being loaded from
@@ -57,17 +60,17 @@
   } MemOrd;
 protected:
   MemNode( Node *c0, Node *c1, Node *c2, const TypePtr* at )
-    : Node(c0,c1,c2   ) {
+    : Node(c0,c1,c2   ), _unaligned_access(false), _mismatched_access(false) {
     init_class_id(Class_Mem);
     debug_only(_adr_type=at; adr_type();)
   }
   MemNode( Node *c0, Node *c1, Node *c2, const TypePtr* at, Node *c3 )
-    : Node(c0,c1,c2,c3) {
+    : Node(c0,c1,c2,c3), _unaligned_access(false), _mismatched_access(false) {
     init_class_id(Class_Mem);
     debug_only(_adr_type=at; adr_type();)
   }
   MemNode( Node *c0, Node *c1, Node *c2, const TypePtr* at, Node *c3, Node *c4)
-    : Node(c0,c1,c2,c3,c4) {
+    : Node(c0,c1,c2,c3,c4), _unaligned_access(false), _mismatched_access(false) {
     init_class_id(Class_Mem);
     debug_only(_adr_type=at; adr_type();)
   }
@@ -129,6 +132,11 @@
   // the given memory state?  (The state may or may not be in(Memory).)
   Node* can_see_stored_value(Node* st, PhaseTransform* phase) const;
 
+  void set_unaligned_access() { _unaligned_access = true; }
+  bool is_unaligned_access() const { return _unaligned_access; }
+  void set_mismatched_access() { _mismatched_access = true; }
+  bool is_mismatched_access() const { return _mismatched_access; }
+
 #ifndef PRODUCT
   static void dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st);
   virtual void dump_spec(outputStream *st) const;
diff --git a/hotspot/src/share/vm/opto/phaseX.cpp b/hotspot/src/share/vm/opto/phaseX.cpp
index f090fcc..1782cb9 100644
--- a/hotspot/src/share/vm/opto/phaseX.cpp
+++ b/hotspot/src/share/vm/opto/phaseX.cpp
@@ -481,6 +481,8 @@
   uint current_idx = 0; // The current new node ID. Incremented after every assignment.
   for (uint i = 0; i < _useful.size(); i++) {
     Node* n = _useful.at(i);
+    // Sanity check that fails if we ever decide to execute this phase after EA
+    assert(!n->is_Phi() || n->as_Phi()->inst_mem_id() == -1, "should not be linked to data Phi");
     const Type* type = gvn->type_or_null(n);
     new_type_array.map(current_idx, type);
 
@@ -1378,6 +1380,18 @@
     i -= num_edges;    // we deleted 1 or more copies of this edge
   }
 
+  // Search for instance field data PhiNodes in the same region pointing to the old
+  // memory PhiNode and update their instance memory ids to point to the new node.
+  if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != NULL) {
+    Node* region = old->in(0);
+    for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
+      PhiNode* phi = region->fast_out(i)->isa_Phi();
+      if (phi != NULL && phi->inst_mem_id() == (int)old->_idx) {
+        phi->set_inst_mem_id((int)nn->_idx);
+      }
+    }
+  }
+
   // Smash all inputs to 'old', isolating him completely
   Node *temp = new (C) Node(1);
   temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
diff --git a/hotspot/src/share/vm/opto/stringopts.cpp b/hotspot/src/share/vm/opto/stringopts.cpp
index 70962e3..d92a3d7 100644
--- a/hotspot/src/share/vm/opto/stringopts.cpp
+++ b/hotspot/src/share/vm/opto/stringopts.cpp
@@ -891,8 +891,9 @@
       ctrl_path.push(cn);
       ctrl_path.push(cn->proj_out(0));
       ctrl_path.push(cn->proj_out(0)->unique_out());
-      if (cn->proj_out(0)->unique_out()->as_Catch()->proj_out(0) != NULL) {
-        ctrl_path.push(cn->proj_out(0)->unique_out()->as_Catch()->proj_out(0));
+      Node* catchproj = cn->proj_out(0)->unique_out()->as_Catch()->proj_out(0);
+      if (catchproj != NULL) {
+        ctrl_path.push(catchproj);
       }
     } else {
       ShouldNotReachHere();
diff --git a/hotspot/src/share/vm/opto/type.hpp b/hotspot/src/share/vm/opto/type.hpp
index 4506c3a..cf7857a 100644
--- a/hotspot/src/share/vm/opto/type.hpp
+++ b/hotspot/src/share/vm/opto/type.hpp
@@ -209,11 +209,11 @@
   static int cmp( const Type *const t1, const Type *const t2 );
   // Test for higher or equal in lattice
   // Variant that drops the speculative part of the types
-  int higher_equal(const Type *t) const {
+  bool higher_equal(const Type *t) const {
     return !cmp(meet(t),t->remove_speculative());
   }
   // Variant that keeps the speculative part of the types
-  int higher_equal_speculative(const Type *t) const {
+  bool higher_equal_speculative(const Type *t) const {
     return !cmp(meet_speculative(t),t);
   }
 
@@ -882,7 +882,7 @@
 
   // If not InstanceTop or InstanceBot, indicates that this is
   // a particular instance of this type which is distinct.
-  // This is the the node index of the allocation node creating this instance.
+  // This is the node index of the allocation node creating this instance.
   int           _instance_id;
 
   // Extra type information profiling gave us. We propagate it the
diff --git a/hotspot/src/share/vm/prims/jni.cpp b/hotspot/src/share/vm/prims/jni.cpp
index 8a41ca4..95fd4d2 100644
--- a/hotspot/src/share/vm/prims/jni.cpp
+++ b/hotspot/src/share/vm/prims/jni.cpp
@@ -5129,6 +5129,7 @@
     run_unit_test(TestKlass_test());
     run_unit_test(Test_linked_list());
     run_unit_test(TestChunkedList_test());
+    run_unit_test(ObjectMonitor::sanity_checks());
 #if INCLUDE_VM_STRUCTS
     run_unit_test(VMStructs::test());
 #endif
diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp
index f1b13f2..36aa9cb 100644
--- a/hotspot/src/share/vm/prims/jvm.cpp
+++ b/hotspot/src/share/vm/prims/jvm.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -643,7 +643,7 @@
       // This can safepoint and redefine method, so need both new_obj and method
       // in a handle, for two different reasons.  new_obj can move, method can be
       // deleted if nothing is using it on the stack.
-      m->method_holder()->add_member_name(new_obj());
+      m->method_holder()->add_member_name(new_obj(), false);
     }
   }
 
@@ -1346,7 +1346,7 @@
   Method* m_oop = object->klass()->uncached_lookup_method(
                                            vmSymbols::run_method_name(),
                                            vmSymbols::void_object_signature(),
-                                           Klass::normal);
+                                           Klass::find_overpass);
   methodHandle m (THREAD, m_oop);
   if (m.is_null() || !m->is_method() || !m()->is_public() || m()->is_static()) {
     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "No run method");
diff --git a/hotspot/src/share/vm/prims/jvmtiEnv.cpp b/hotspot/src/share/vm/prims/jvmtiEnv.cpp
index 0c92c88..98624be 100644
--- a/hotspot/src/share/vm/prims/jvmtiEnv.cpp
+++ b/hotspot/src/share/vm/prims/jvmtiEnv.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -1000,8 +1000,9 @@
   GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list =
       new (ResourceObj::C_HEAP, mtInternal) GrowableArray<jvmtiMonitorStackDepthInfo*>(1, true);
 
-  uint32_t debug_bits = 0;
-  if (is_thread_fully_suspended(java_thread, true, &debug_bits)) {
+  // It is only safe to perform the direct operation on the current
+  // thread. All other usage needs to use a vm-safepoint-op for safety.
+  if (java_thread == calling_thread) {
     err = get_owned_monitors(calling_thread, java_thread, owned_monitors_list);
   } else {
     // JVMTI get monitors info at safepoint. Do not require target thread to
@@ -1045,8 +1046,9 @@
   GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list =
          new (ResourceObj::C_HEAP, mtInternal) GrowableArray<jvmtiMonitorStackDepthInfo*>(1, true);
 
-  uint32_t debug_bits = 0;
-  if (is_thread_fully_suspended(java_thread, true, &debug_bits)) {
+  // It is only safe to perform the direct operation on the current
+  // thread. All other usage needs to use a vm-safepoint-op for safety.
+  if (java_thread == calling_thread) {
     err = get_owned_monitors(calling_thread, java_thread, owned_monitors_list);
   } else {
     // JVMTI get owned monitors info at safepoint. Do not require target thread to
@@ -1087,9 +1089,11 @@
 jvmtiError
 JvmtiEnv::GetCurrentContendedMonitor(JavaThread* java_thread, jobject* monitor_ptr) {
   jvmtiError err = JVMTI_ERROR_NONE;
-  uint32_t debug_bits = 0;
   JavaThread* calling_thread  = JavaThread::current();
-  if (is_thread_fully_suspended(java_thread, true, &debug_bits)) {
+
+  // It is only safe to perform the direct operation on the current
+  // thread. All other usage needs to use a vm-safepoint-op for safety.
+  if (java_thread == calling_thread) {
     err = get_current_contended_monitor(calling_thread, java_thread, monitor_ptr);
   } else {
     // get contended monitor information at safepoint.
@@ -1298,8 +1302,10 @@
 jvmtiError
 JvmtiEnv::GetStackTrace(JavaThread* java_thread, jint start_depth, jint max_frame_count, jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
   jvmtiError err = JVMTI_ERROR_NONE;
-  uint32_t debug_bits = 0;
-  if (is_thread_fully_suspended(java_thread, true, &debug_bits)) {
+
+  // It is only safe to perform the direct operation on the current
+  // thread. All other usage needs to use a vm-safepoint-op for safety.
+  if (java_thread == JavaThread::current()) {
     err = get_stack_trace(java_thread, start_depth, max_frame_count, frame_buffer, count_ptr);
   } else {
     // JVMTI get stack trace at safepoint. Do not require target thread to
diff --git a/hotspot/src/share/vm/prims/jvmtiEnvBase.hpp b/hotspot/src/share/vm/prims/jvmtiEnvBase.hpp
index 084e19b..e8c23b1 100644
--- a/hotspot/src/share/vm/prims/jvmtiEnvBase.hpp
+++ b/hotspot/src/share/vm/prims/jvmtiEnvBase.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -356,8 +356,12 @@
   }
   VMOp_Type type() const { return VMOp_GetOwnedMonitorInfo; }
   void doit() {
-    ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread, _java_thread,
-                                                         _owned_monitors_list);
+    _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
+    if (Threads::includes(_java_thread) && !_java_thread->is_exiting()
+                                        && _java_thread->threadObj() != NULL) {
+      _result = ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread, _java_thread,
+                                                            _owned_monitors_list);
+    }
   }
   jvmtiError result() { return _result; }
 };
@@ -439,9 +443,13 @@
   jvmtiError result() { return _result; }
   VMOp_Type type() const { return VMOp_GetStackTrace; }
   void doit() {
-    _result = ((JvmtiEnvBase *)_env)->get_stack_trace(_java_thread,
-                                                      _start_depth, _max_count,
-                                                      _frame_buffer, _count_ptr);
+    _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
+    if (Threads::includes(_java_thread) && !_java_thread->is_exiting()
+                                        && _java_thread->threadObj() != NULL) {
+      _result = ((JvmtiEnvBase *)_env)->get_stack_trace(_java_thread,
+                                                        _start_depth, _max_count,
+                                                        _frame_buffer, _count_ptr);
+    }
   }
 };
 
diff --git a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp
index 7903b1d..f610db2 100644
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,6 +42,7 @@
 #include "runtime/deoptimization.hpp"
 #include "runtime/relocator.hpp"
 #include "utilities/bitMap.inline.hpp"
+#include "utilities/events.hpp"
 
 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
 
@@ -172,6 +173,9 @@
   // Free os::malloc allocated memory.
   os::free(_scratch_classes);
 
+  // Reset the_class_oop to null for error printing.
+  _the_class_oop = NULL;
+
   if (RC_TRACE_ENABLED(0x00000004)) {
     // Used to have separate timers for "doit" and "all", but the timer
     // overhead skewed the measurements.
@@ -4096,6 +4100,13 @@
     java_lang_Class::classRedefinedCount(the_class_mirror),
     os::available_memory() >> 10));
 
+  {
+    ResourceMark rm(THREAD);
+    Events::log_redefinition(THREAD, "redefined class name=%s, count=%d",
+                             the_class->external_name(),
+                             java_lang_Class::classRedefinedCount(the_class_mirror));
+
+  }
   RC_TIMER_STOP(_timer_rsc_phase2);
 } // end redefine_single_class()
 
@@ -4240,3 +4251,11 @@
     tty->cr();
   }
 }
+
+void VM_RedefineClasses::print_on_error(outputStream* st) const {
+  VM_Operation::print_on_error(st);
+  if (_the_class_oop != NULL) {
+    ResourceMark rm;
+    st->print_cr(", redefining class %s", _the_class_oop->external_name());
+  }
+}
diff --git a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp
index a7d1136..d2611f2 100644
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -538,5 +538,8 @@
   static unsigned char * get_cached_class_file_bytes(JvmtiCachedClassFileData *cache) {
     return cache == NULL ? NULL : cache->data;
   }
+
+  // Error printing
+  void print_on_error(outputStream* st) const;
 };
 #endif // SHARE_VM_PRIMS_JVMTIREDEFINECLASSES_HPP
diff --git a/hotspot/src/share/vm/prims/methodHandles.cpp b/hotspot/src/share/vm/prims/methodHandles.cpp
index e477c70..6c7cdb5 100644
--- a/hotspot/src/share/vm/prims/methodHandles.cpp
+++ b/hotspot/src/share/vm/prims/methodHandles.cpp
@@ -173,7 +173,7 @@
   return NULL;
 }
 
-oop MethodHandles::init_method_MemberName(Handle mname, CallInfo& info) {
+oop MethodHandles::init_method_MemberName(Handle mname, CallInfo& info, bool intern) {
   assert(info.resolved_appendix().is_null(), "only normal methods here");
   methodHandle m = info.resolved_method();
   KlassHandle m_klass = m->method_holder();
@@ -270,13 +270,7 @@
   // If relevant, the vtable or itable value is stored as vmindex.
   // This is done eagerly, since it is readily available without
   // constructing any new objects.
-  // TO DO: maybe intern mname_oop
-  if (m->method_holder()->add_member_name(mname)) {
-    return mname();
-  } else {
-    // Redefinition caused this to fail.  Return NULL (and an exception?)
-    return NULL;
-  }
+  return m->method_holder()->add_member_name(mname, intern);
 }
 
 oop MethodHandles::init_field_MemberName(Handle mname, fieldDescriptor& fd, bool is_setter) {
@@ -917,7 +911,9 @@
         if (!java_lang_invoke_MemberName::is_instance(result()))
           return -99;  // caller bug!
         CallInfo info(m);
-        oop saved = MethodHandles::init_method_MemberName(result, info);
+        // Since this is going through the methods to create MemberNames, don't search
+        // for matching methods already in the table
+        oop saved = MethodHandles::init_method_MemberName(result, info, /*intern*/false);
         if (saved != result())
           results->obj_at_put(rfill-1, saved);  // show saved instance to user
       } else if (++overflow >= overflow_limit) {
@@ -949,9 +945,34 @@
   }
 }
 
-void MemberNameTable::add_member_name(jweak mem_name_wref) {
+oop MemberNameTable::add_member_name(jweak mem_name_wref) {
   assert_locked_or_safepoint(MemberNameTable_lock);
   this->push(mem_name_wref);
+  return JNIHandles::resolve(mem_name_wref);
+}
+
+oop MemberNameTable::find_or_add_member_name(jweak mem_name_wref) {
+  assert_locked_or_safepoint(MemberNameTable_lock);
+  oop new_mem_name = JNIHandles::resolve(mem_name_wref);
+
+  // Find matching member name in the list.
+  // This is linear because these are short lists.
+  int len = this->length();
+  int new_index = len;
+  for (int idx = 0; idx < len; idx++) {
+    oop mname = JNIHandles::resolve(this->at(idx));
+    if (mname == NULL) {
+      new_index = idx;
+      continue;
+    }
+    if (java_lang_invoke_MemberName::equals(new_mem_name, mname)) {
+      JNIHandles::destroy_weak_global(mem_name_wref);
+      return mname;
+    }
+  }
+  // Not found, push the new one, or reuse empty slot
+  this->at_put_grow(new_index, mem_name_wref);
+  return new_mem_name;
 }
 
 #if INCLUDE_JVMTI
diff --git a/hotspot/src/share/vm/prims/methodHandles.hpp b/hotspot/src/share/vm/prims/methodHandles.hpp
index c28d294..9d33768 100644
--- a/hotspot/src/share/vm/prims/methodHandles.hpp
+++ b/hotspot/src/share/vm/prims/methodHandles.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2017, 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
@@ -60,7 +60,7 @@
   static Handle new_MemberName(TRAPS);  // must be followed by init_MemberName
   static oop init_MemberName(Handle mname_h, Handle target_h); // compute vmtarget/vmindex from target
   static oop init_field_MemberName(Handle mname_h, fieldDescriptor& fd, bool is_setter = false);
-  static oop init_method_MemberName(Handle mname_h, CallInfo& info);
+  static oop init_method_MemberName(Handle mname_h, CallInfo& info, bool intern = true);
   static int method_ref_kind(Method* m, bool do_dispatch_if_possible = true);
   static int find_MemberNames(KlassHandle k, Symbol* name, Symbol* sig,
                               int mflags, KlassHandle caller,
@@ -236,7 +236,8 @@
  public:
   MemberNameTable(int methods_cnt);
   ~MemberNameTable();
-  void add_member_name(jweak mem_name_ref);
+  oop add_member_name(jweak mem_name_ref);
+  oop find_or_add_member_name(jweak mem_name_ref);
 
 #if INCLUDE_JVMTI
   // RedefineClasses() API support:
diff --git a/hotspot/src/share/vm/prims/nativeLookup.cpp b/hotspot/src/share/vm/prims/nativeLookup.cpp
index 188e7fc..bfb4672 100644
--- a/hotspot/src/share/vm/prims/nativeLookup.cpp
+++ b/hotspot/src/share/vm/prims/nativeLookup.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -408,7 +408,7 @@
 
   // Find method and invoke standard lookup
   methodHandle method (THREAD,
-                       klass->uncached_lookup_method(m_name, s_name, Klass::normal));
+                       klass->uncached_lookup_method(m_name, s_name, Klass::find_overpass));
   address result = lookup(method, in_base_library, CATCH);
   assert(in_base_library, "must be in basic library");
   guarantee(result != NULL, "must be non NULL");
diff --git a/hotspot/src/share/vm/prims/unsafe.cpp b/hotspot/src/share/vm/prims/unsafe.cpp
index 0846b20..5e39b38 100644
--- a/hotspot/src/share/vm/prims/unsafe.cpp
+++ b/hotspot/src/share/vm/prims/unsafe.cpp
@@ -985,14 +985,6 @@
   }
 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");
@@ -1001,7 +993,7 @@
 
     int depthFromDefineClass0 = 1;
     jclass  caller = JVM_GetCallerClass(env, depthFromDefineClass0);
-    jobject loader = (caller == NULL) ? NULL : get_class_loader(env, caller);
+    jobject loader = (caller == NULL) ? NULL : JVM_GetClassLoader(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/fieldDescriptor.hpp b/hotspot/src/share/vm/runtime/fieldDescriptor.hpp
index 9c3101b..1810a16 100644
--- a/hotspot/src/share/vm/runtime/fieldDescriptor.hpp
+++ b/hotspot/src/share/vm/runtime/fieldDescriptor.hpp
@@ -106,6 +106,7 @@
   bool is_field_access_watched()  const    { return access_flags().is_field_access_watched(); }
   bool is_field_modification_watched() const
                                            { return access_flags().is_field_modification_watched(); }
+  bool has_initialized_final_update() const { return access_flags().has_field_initialized_final_update(); }
   bool has_generic_signature()    const    { return access_flags().field_has_generic_signature(); }
 
   void set_is_field_access_watched(const bool value) {
@@ -118,6 +119,11 @@
     update_klass_field_access_flag();
   }
 
+  void set_has_initialized_final_update(const bool value) {
+    _access_flags.set_has_field_initialized_final_update(value);
+    update_klass_field_access_flag();
+  }
+
   // Initialization
   void reinitialize(InstanceKlass* ik, int index);
 
diff --git a/hotspot/src/share/vm/runtime/objectMonitor.cpp b/hotspot/src/share/vm/runtime/objectMonitor.cpp
index 31f899b..94f4492 100644
--- a/hotspot/src/share/vm/runtime/objectMonitor.cpp
+++ b/hotspot/src/share/vm/runtime/objectMonitor.cpp
@@ -2529,6 +2529,10 @@
   SETKNOB(FastHSSEC) ;
   #undef SETKNOB
 
+  if (Knob_Verbose) {
+    sanity_checks();
+  }
+
   if (os::is_MP()) {
      BackOffMask = (1 << Knob_SpinBackOff) - 1 ;
      if (Knob_ReportSettings) ::printf ("BackOffMask=%X\n", BackOffMask) ;
@@ -2549,6 +2553,66 @@
   InitDone = 1 ;
 }
 
+void ObjectMonitor::sanity_checks() {
+  int error_cnt = 0;
+  int warning_cnt = 0;
+  bool verbose = Knob_Verbose != 0 NOT_PRODUCT(|| VerboseInternalVMTests);
+
+  if (verbose) {
+    tty->print_cr("INFO: sizeof(ObjectMonitor)=" SIZE_FORMAT,
+                  sizeof(ObjectMonitor));
+  }
+
+  uint cache_line_size = VM_Version::L1_data_cache_line_size();
+  if (verbose) {
+    tty->print_cr("INFO: L1_data_cache_line_size=%u", cache_line_size);
+  }
+
+  ObjectMonitor dummy;
+  u_char *addr_begin  = (u_char*)&dummy;
+  u_char *addr_header = (u_char*)&dummy._header;
+  u_char *addr_owner  = (u_char*)&dummy._owner;
+
+  uint offset_header = (uint)(addr_header - addr_begin);
+  if (verbose) tty->print_cr("INFO: offset(_header)=%u", offset_header);
+
+  uint offset_owner = (uint)(addr_owner - addr_begin);
+  if (verbose) tty->print_cr("INFO: offset(_owner)=%u", offset_owner);
+
+  if ((uint)(addr_header - addr_begin) != 0) {
+    tty->print_cr("ERROR: offset(_header) must be zero (0).");
+    error_cnt++;
+  }
+
+  if (cache_line_size != 0) {
+    // We were able to determine the L1 data cache line size so
+    // do some cache line specific sanity checks
+
+    if ((offset_owner - offset_header) < cache_line_size) {
+      tty->print_cr("WARNING: the _header and _owner fields are closer "
+                    "than a cache line which permits false sharing.");
+      warning_cnt++;
+    }
+
+    if ((sizeof(ObjectMonitor) % cache_line_size) != 0) {
+      tty->print_cr("WARNING: ObjectMonitor size is not a multiple of "
+                    "a cache line which permits false sharing.");
+      warning_cnt++;
+    }
+  }
+
+  ObjectSynchronizer::sanity_checks(verbose, cache_line_size, &error_cnt,
+                                    &warning_cnt);
+
+  if (verbose || error_cnt != 0 || warning_cnt != 0) {
+    tty->print_cr("INFO: error_cnt=%d", error_cnt);
+    tty->print_cr("INFO: warning_cnt=%d", warning_cnt);
+  }
+
+  guarantee(error_cnt == 0,
+            "Fatal error(s) found in ObjectMonitor::sanity_checks()");
+}
+
 #ifndef PRODUCT
 void ObjectMonitor::verify() {
 }
diff --git a/hotspot/src/share/vm/runtime/objectMonitor.hpp b/hotspot/src/share/vm/runtime/objectMonitor.hpp
index 10b3609..09180cf 100644
--- a/hotspot/src/share/vm/runtime/objectMonitor.hpp
+++ b/hotspot/src/share/vm/runtime/objectMonitor.hpp
@@ -189,6 +189,8 @@
   bool      check(TRAPS);       // true if the thread owns the monitor.
   void      check_slow(TRAPS);
   void      clear();
+  static void sanity_checks();  // public for -XX:+ExecuteInternalVMTests
+                                // in PRODUCT for -XX:SyncKnobs=Verbose=1
 #ifndef PRODUCT
   void      verify();
   void      print();
@@ -234,8 +236,6 @@
 
   // WARNING: this must be the very first word of ObjectMonitor
   // This means this class can't use any virtual member functions.
-  // TODO-FIXME: assert that offsetof(_header) is 0 or get rid of the
-  // implicit 0 offset in emitted code.
 
   volatile markOop   _header;       // displaced object header word - mark
   void*     volatile _object;       // backward object pointer - strong root
diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.cpp b/hotspot/src/share/vm/runtime/sharedRuntime.cpp
index e510042..8ffa8ab 100644
--- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp
@@ -546,7 +546,7 @@
   CodeBlob *cb = CodeCache::find_blob(pc);
 
   // Should be an nmethod
-  assert( cb && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod" );
+  guarantee(cb != NULL && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod");
 
   // Look up the relocation information
   assert( ((nmethod*)cb)->is_at_poll_or_poll_return(pc),
@@ -1709,7 +1709,7 @@
   // ask me how I know this...
 
   CodeBlob* cb = CodeCache::find_blob(caller_pc);
-  if (!cb->is_nmethod() || entry_point == moop->get_c2i_entry()) {
+  if (cb == NULL || !cb->is_nmethod() || entry_point == moop->get_c2i_entry()) {
     return;
   }
 
@@ -1760,7 +1760,7 @@
       if (destination != entry_point) {
         CodeBlob* callee = CodeCache::find_blob(destination);
         // callee == cb seems weird. It means calling interpreter thru stub.
-        if (callee == cb || callee->is_adapter_blob()) {
+        if (callee != NULL && (callee == cb || callee->is_adapter_blob())) {
           // static call or optimized virtual
           if (TraceCallFixup) {
             tty->print("fixup callsite           at " INTPTR_FORMAT " to compiled code for", caller_pc);
diff --git a/hotspot/src/share/vm/runtime/sweeper.cpp b/hotspot/src/share/vm/runtime/sweeper.cpp
index b4954ff..ba4ce2d 100644
--- a/hotspot/src/share/vm/runtime/sweeper.cpp
+++ b/hotspot/src/share/vm/runtime/sweeper.cpp
@@ -319,6 +319,7 @@
 }
 
 void NMethodSweeper::sweep_code_cache() {
+  ResourceMark rm;
   Ticks sweep_start_counter = Ticks::now();
 
   _flushed_count                = 0;
@@ -626,6 +627,7 @@
 // state of the code cache if it's requested.
 void NMethodSweeper::log_sweep(const char* msg, const char* format, ...) {
   if (PrintMethodFlushing) {
+    ResourceMark rm;
     stringStream s;
     // Dump code cache state into a buffer before locking the tty,
     // because log_state() will use locks causing lock conflicts.
@@ -643,6 +645,7 @@
   }
 
   if (LogCompilation && (xtty != NULL)) {
+    ResourceMark rm;
     stringStream s;
     // Dump code cache state into a buffer before locking the tty,
     // because log_state() will use locks causing lock conflicts.
diff --git a/hotspot/src/share/vm/runtime/synchronizer.cpp b/hotspot/src/share/vm/runtime/synchronizer.cpp
index b35f86f..6bd9233 100644
--- a/hotspot/src/share/vm/runtime/synchronizer.cpp
+++ b/hotspot/src/share/vm/runtime/synchronizer.cpp
@@ -437,19 +437,22 @@
 // Hash Code handling
 //
 // Performance concern:
-// OrderAccess::storestore() calls release() which STs 0 into the global volatile
-// OrderAccess::Dummy variable.  This store is unnecessary for correctness.
-// Many threads STing into a common location causes considerable cache migration
-// or "sloshing" on large SMP system.  As such, I avoid using OrderAccess::storestore()
-// until it's repaired.  In some cases OrderAccess::fence() -- which incurs local
-// latency on the executing processor -- is a better choice as it scales on SMP
-// systems.  See http://blogs.sun.com/dave/entry/biased_locking_in_hotspot for a
-// discussion of coherency costs.  Note that all our current reference platforms
-// provide strong ST-ST order, so the issue is moot on IA32, x64, and SPARC.
+// OrderAccess::storestore() calls release() which at one time stored 0
+// into the global volatile OrderAccess::dummy variable. This store was
+// unnecessary for correctness. Many threads storing into a common location
+// causes considerable cache migration or "sloshing" on large SMP systems.
+// As such, I avoided using OrderAccess::storestore(). In some cases
+// OrderAccess::fence() -- which incurs local latency on the executing
+// processor -- is a better choice as it scales on SMP systems.
+//
+// See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
+// a discussion of coherency costs. Note that all our current reference
+// platforms provide strong ST-ST order, so the issue is moot on IA32,
+// x64, and SPARC.
 //
 // As a general policy we use "volatile" to control compiler-based reordering
-// and explicit fences (barriers) to control for architectural reordering performed
-// by the CPU(s) or platform.
+// and explicit fences (barriers) to control for architectural reordering
+// performed by the CPU(s) or platform.
 
 struct SharedGlobals {
     // These are highly shared mostly-read variables.
@@ -1636,7 +1639,55 @@
 }
 
 //------------------------------------------------------------------------------
-// Non-product code
+// Debugging code
+
+void ObjectSynchronizer::sanity_checks(const bool verbose,
+                                       const uint cache_line_size,
+                                       int *error_cnt_ptr,
+                                       int *warning_cnt_ptr) {
+  u_char *addr_begin      = (u_char*)&GVars;
+  u_char *addr_stwRandom  = (u_char*)&GVars.stwRandom;
+  u_char *addr_hcSequence = (u_char*)&GVars.hcSequence;
+
+  if (verbose) {
+    tty->print_cr("INFO: sizeof(SharedGlobals)=" SIZE_FORMAT,
+                  sizeof(SharedGlobals));
+  }
+
+  uint offset_stwRandom = (uint)(addr_stwRandom - addr_begin);
+  if (verbose) tty->print_cr("INFO: offset(stwRandom)=%u", offset_stwRandom);
+
+  uint offset_hcSequence = (uint)(addr_hcSequence - addr_begin);
+  if (verbose) {
+    tty->print_cr("INFO: offset(_hcSequence)=%u", offset_hcSequence);
+  }
+
+  if (cache_line_size != 0) {
+    // We were able to determine the L1 data cache line size so
+    // do some cache line specific sanity checks
+
+    if (offset_stwRandom < cache_line_size) {
+      tty->print_cr("WARNING: the SharedGlobals.stwRandom field is closer "
+                    "to the struct beginning than a cache line which permits "
+                    "false sharing.");
+      (*warning_cnt_ptr)++;
+    }
+
+    if ((offset_hcSequence - offset_stwRandom) < cache_line_size) {
+      tty->print_cr("WARNING: the SharedGlobals.stwRandom and "
+                    "SharedGlobals.hcSequence fields are closer than a cache "
+                    "line which permits false sharing.");
+      (*warning_cnt_ptr)++;
+    }
+
+    if ((sizeof(SharedGlobals) - offset_hcSequence) < cache_line_size) {
+      tty->print_cr("WARNING: the SharedGlobals.hcSequence field is closer "
+                    "to the struct end than a cache line which permits false "
+                    "sharing.");
+      (*warning_cnt_ptr)++;
+    }
+  }
+}
 
 #ifndef PRODUCT
 
diff --git a/hotspot/src/share/vm/runtime/synchronizer.hpp b/hotspot/src/share/vm/runtime/synchronizer.hpp
index af8df33..3b2597d 100644
--- a/hotspot/src/share/vm/runtime/synchronizer.hpp
+++ b/hotspot/src/share/vm/runtime/synchronizer.hpp
@@ -121,6 +121,9 @@
   static void oops_do(OopClosure* f);
 
   // debugging
+  static void sanity_checks(const bool verbose,
+                            const unsigned int cache_line_size,
+                            int *error_cnt_ptr, int *warning_cnt_ptr);
   static void verify() PRODUCT_RETURN;
   static int  verify_objmon_isinpool(ObjectMonitor *addr) PRODUCT_RETURN0;
 
diff --git a/hotspot/src/share/vm/runtime/vmStructs.cpp b/hotspot/src/share/vm/runtime/vmStructs.cpp
index 50fc13e..3447b7c 100644
--- a/hotspot/src/share/vm/runtime/vmStructs.cpp
+++ b/hotspot/src/share/vm/runtime/vmStructs.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -704,7 +704,7 @@
                                                                                                                                      \
   nonstatic_field(BasicHashtable<mtInternal>, _table_size,                                   int)                                   \
   nonstatic_field(BasicHashtable<mtInternal>, _buckets,                                      HashtableBucket<mtInternal>*)          \
-  nonstatic_field(BasicHashtable<mtInternal>, _free_list,                                    BasicHashtableEntry<mtInternal>*)      \
+  volatile_nonstatic_field(BasicHashtable<mtInternal>,  _free_list,                          BasicHashtableEntry<mtInternal>*)      \
   nonstatic_field(BasicHashtable<mtInternal>, _first_free_entry,                             char*)                                 \
   nonstatic_field(BasicHashtable<mtInternal>, _end_block,                                    char*)                                 \
   nonstatic_field(BasicHashtable<mtInternal>, _entry_size,                                   int)                                   \
@@ -879,7 +879,7 @@
   nonstatic_field(nmethod,             _stack_traversal_mark,                         long)                                  \
   nonstatic_field(nmethod,             _compile_id,                                   int)                                   \
   nonstatic_field(nmethod,             _comp_level,                                   int)                                   \
-  nonstatic_field(nmethod,             _exception_cache,                              ExceptionCache*)                       \
+  volatile_nonstatic_field(nmethod,    _exception_cache,                              ExceptionCache*)                       \
   nonstatic_field(nmethod,             _marked_for_deoptimization,                    bool)                                  \
                                                                                                                              \
   unchecked_c2_static_field(Deoptimization,         _trap_reason_name,                   void*)                              \
diff --git a/hotspot/src/share/vm/runtime/vm_operations.hpp b/hotspot/src/share/vm/runtime/vm_operations.hpp
index 71118be..fb99be9 100644
--- a/hotspot/src/share/vm/runtime/vm_operations.hpp
+++ b/hotspot/src/share/vm/runtime/vm_operations.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -183,7 +183,7 @@
   static const char* mode_to_string(Mode mode);
 
   // Debugging
-  void print_on_error(outputStream* st) const;
+  virtual void print_on_error(outputStream* st) const;
   const char* name() const { return _names[type()]; }
   static const char* name(int type) {
     assert(type >= 0 && type < VMOp_Terminating, "invalid VM operation type");
diff --git a/hotspot/src/share/vm/runtime/vm_version.cpp b/hotspot/src/share/vm/runtime/vm_version.cpp
index d95e3a9..50063e6 100644
--- a/hotspot/src/share/vm/runtime/vm_version.cpp
+++ b/hotspot/src/share/vm/runtime/vm_version.cpp
@@ -50,6 +50,7 @@
 bool Abstract_VM_Version::_supports_atomic_getadd4 = false;
 bool Abstract_VM_Version::_supports_atomic_getadd8 = false;
 unsigned int Abstract_VM_Version::_logical_processors_per_package = 1U;
+unsigned int Abstract_VM_Version::_L1_data_cache_line_size = 0;
 int Abstract_VM_Version::_reserve_for_allocation_prefetch = 0;
 
 #ifndef HOTSPOT_RELEASE_VERSION
diff --git a/hotspot/src/share/vm/runtime/vm_version.hpp b/hotspot/src/share/vm/runtime/vm_version.hpp
index feabadf..5c40405 100644
--- a/hotspot/src/share/vm/runtime/vm_version.hpp
+++ b/hotspot/src/share/vm/runtime/vm_version.hpp
@@ -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
@@ -42,6 +42,7 @@
   static bool         _supports_atomic_getadd4;
   static bool         _supports_atomic_getadd8;
   static unsigned int _logical_processors_per_package;
+  static unsigned int _L1_data_cache_line_size;
   static int          _vm_major_version;
   static int          _vm_minor_version;
   static int          _vm_build_number;
@@ -114,6 +115,10 @@
     return _logical_processors_per_package;
   }
 
+  static unsigned int L1_data_cache_line_size() {
+    return _L1_data_cache_line_size;
+  }
+
   // Need a space at the end of TLAB for prefetch instructions
   // which may fault when accessing memory outside of heap.
   static int reserve_for_allocation_prefetch() {
diff --git a/hotspot/src/share/vm/services/attachListener.cpp b/hotspot/src/share/vm/services/attachListener.cpp
index 5df54c8..45d930d 100644
--- a/hotspot/src/share/vm/services/attachListener.cpp
+++ b/hotspot/src/share/vm/services/attachListener.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -271,13 +271,17 @@
 // set a uintx global flag using value from AttachOperation
 static jint set_uintx_flag(const char* name, AttachOperation* op, outputStream* out) {
   uintx value;
-  const char* arg1;
-  if ((arg1 = op->arg(1)) != NULL) {
-    int n = sscanf(arg1, UINTX_FORMAT, &value);
-    if (n != 1) {
-      out->print_cr("flag value must be an unsigned integer");
-      return JNI_ERR;
-    }
+
+  const char* arg1 = op->arg(1);
+  if (arg1 == NULL) {
+    out->print_cr("flag value must be specified");
+    return JNI_ERR;
+  }
+
+  int n = sscanf(arg1, UINTX_FORMAT, &value);
+  if (n != 1) {
+    out->print_cr("flag value must be an unsigned integer");
+    return JNI_ERR;
   }
 
   if (strncmp(name, "MaxHeapFreeRatio", 17) == 0) {
diff --git a/hotspot/src/share/vm/utilities/accessFlags.hpp b/hotspot/src/share/vm/utilities/accessFlags.hpp
index a66bc9e..bc56262 100644
--- a/hotspot/src/share/vm/utilities/accessFlags.hpp
+++ b/hotspot/src/share/vm/utilities/accessFlags.hpp
@@ -76,11 +76,12 @@
   // These bits must not conflict with any other field-related access flags
   // (e.g., ACC_ENUM).
   // Note that the class-related ACC_ANNOTATION bit conflicts with these flags.
-  JVM_ACC_FIELD_ACCESS_WATCHED       = 0x00002000,  // field access is watched by JVMTI
-  JVM_ACC_FIELD_MODIFICATION_WATCHED = 0x00008000,  // field modification is watched by JVMTI
-  JVM_ACC_FIELD_INTERNAL             = 0x00000400,  // internal field, same as JVM_ACC_ABSTRACT
-  JVM_ACC_FIELD_STABLE               = 0x00000020,  // @Stable field, same as JVM_ACC_SYNCHRONIZED
-  JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE = 0x00000800, // field has generic signature
+  JVM_ACC_FIELD_ACCESS_WATCHED            = 0x00002000, // field access is watched by JVMTI
+  JVM_ACC_FIELD_MODIFICATION_WATCHED      = 0x00008000, // field modification is watched by JVMTI
+  JVM_ACC_FIELD_INTERNAL                  = 0x00000400, // internal field, same as JVM_ACC_ABSTRACT
+  JVM_ACC_FIELD_STABLE                    = 0x00000020, // @Stable field, same as JVM_ACC_SYNCHRONIZED and JVM_ACC_SUPER
+  JVM_ACC_FIELD_INITIALIZED_FINAL_UPDATE  = 0x00000100, // (static) final field updated outside (class) initializer, same as JVM_ACC_NATIVE
+  JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE     = 0x00000800, // field has generic signature
 
   JVM_ACC_FIELD_INTERNAL_FLAGS       = JVM_ACC_FIELD_ACCESS_WATCHED |
                                        JVM_ACC_FIELD_MODIFICATION_WATCHED |
@@ -150,6 +151,8 @@
   bool is_field_access_watched() const  { return (_flags & JVM_ACC_FIELD_ACCESS_WATCHED) != 0; }
   bool is_field_modification_watched() const
                                         { return (_flags & JVM_ACC_FIELD_MODIFICATION_WATCHED) != 0; }
+  bool has_field_initialized_final_update() const
+                                        { return (_flags & JVM_ACC_FIELD_INITIALIZED_FINAL_UPDATE) != 0; }
   bool on_stack() const                 { return (_flags & JVM_ACC_ON_STACK) != 0; }
   bool is_internal() const              { return (_flags & JVM_ACC_FIELD_INTERNAL) != 0; }
   bool is_stable() const                { return (_flags & JVM_ACC_FIELD_STABLE) != 0; }
@@ -229,6 +232,15 @@
                                            atomic_clear_bits(JVM_ACC_FIELD_MODIFICATION_WATCHED);
                                          }
                                        }
+
+  void set_has_field_initialized_final_update(const bool value) {
+    if (value) {
+      atomic_set_bits(JVM_ACC_FIELD_INITIALIZED_FINAL_UPDATE);
+    } else {
+      atomic_clear_bits(JVM_ACC_FIELD_INITIALIZED_FINAL_UPDATE);
+    }
+  }
+
   void set_field_has_generic_signature()
                                        {
                                          atomic_set_bits(JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE);
diff --git a/hotspot/src/share/vm/utilities/events.cpp b/hotspot/src/share/vm/utilities/events.cpp
index 4d17c9b..45a11ef 100644
--- a/hotspot/src/share/vm/utilities/events.cpp
+++ b/hotspot/src/share/vm/utilities/events.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -36,6 +36,7 @@
 EventLog* Events::_logs = NULL;
 StringEventLog* Events::_messages = NULL;
 StringEventLog* Events::_exceptions = NULL;
+StringEventLog* Events::_redefinitions = NULL;
 StringEventLog* Events::_deopt_messages = NULL;
 
 EventLog::EventLog() {
@@ -65,6 +66,7 @@
   if (LogEvents) {
     _messages = new StringEventLog("Events");
     _exceptions = new StringEventLog("Internal exceptions");
+    _redefinitions = new StringEventLog("Classes redefined");
     _deopt_messages = new StringEventLog("Deoptimization events");
   }
 }
diff --git a/hotspot/src/share/vm/utilities/events.hpp b/hotspot/src/share/vm/utilities/events.hpp
index 71a4a43..855b8bc 100644
--- a/hotspot/src/share/vm/utilities/events.hpp
+++ b/hotspot/src/share/vm/utilities/events.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -186,6 +186,9 @@
   // Deoptization related messages
   static StringEventLog* _deopt_messages;
 
+  // Redefinition related messages
+  static StringEventLog* _redefinitions;
+
  public:
   static void print_all(outputStream* out);
 
@@ -198,6 +201,8 @@
   // Log exception related message
   static void log_exception(Thread* thread, const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
 
+  static void log_redefinition(Thread* thread, const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
+
   static void log_deopt_message(Thread* thread, const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
 
   // Register default loggers
@@ -222,6 +227,15 @@
   }
 }
 
+inline void Events::log_redefinition(Thread* thread, const char* format, ...) {
+  if (LogEvents) {
+    va_list ap;
+    va_start(ap, format);
+    _redefinitions->logv(thread, format, ap);
+    va_end(ap);
+  }
+}
+
 inline void Events::log_deopt_message(Thread* thread, const char* format, ...) {
   if (LogEvents) {
     va_list ap;
diff --git a/hotspot/src/share/vm/utilities/hashtable.cpp b/hotspot/src/share/vm/utilities/hashtable.cpp
index a60fe76..ec260e9 100644
--- a/hotspot/src/share/vm/utilities/hashtable.cpp
+++ b/hotspot/src/share/vm/utilities/hashtable.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -172,6 +172,35 @@
   }
 }
 
+template <MEMFLAGS F> void BasicHashtable<F>::BucketUnlinkContext::free_entry(BasicHashtableEntry<F>* entry) {
+  entry->set_next(_removed_head);
+  _removed_head = entry;
+  if (_removed_tail == NULL) {
+    _removed_tail = entry;
+  }
+  _num_removed++;
+}
+
+template <MEMFLAGS F> void BasicHashtable<F>::bulk_free_entries(BucketUnlinkContext* context) {
+  if (context->_num_removed == 0) {
+    assert(context->_removed_head == NULL && context->_removed_tail == NULL,
+           err_msg("Zero entries in the unlink context, but elements linked from " PTR_FORMAT " to " PTR_FORMAT,
+                   p2i(context->_removed_head), p2i(context->_removed_tail)));
+    return;
+  }
+
+  // MT-safe add of the list of BasicHashTableEntrys from the context to the free list.
+  BasicHashtableEntry<F>* current = _free_list;
+  while (true) {
+    context->_removed_tail->set_next(current);
+    BasicHashtableEntry<F>* old = (BasicHashtableEntry<F>*)Atomic::cmpxchg_ptr(context->_removed_head, &_free_list, current);
+    if (old == current) {
+      break;
+    }
+    current = old;
+  }
+  Atomic::add(-context->_num_removed, &_number_of_entries);
+}
 
 // Copy the table to the shared space.
 
diff --git a/hotspot/src/share/vm/utilities/hashtable.hpp b/hotspot/src/share/vm/utilities/hashtable.hpp
index 6244c4c..d08deff 100644
--- a/hotspot/src/share/vm/utilities/hashtable.hpp
+++ b/hotspot/src/share/vm/utilities/hashtable.hpp
@@ -164,11 +164,11 @@
   // Instance variables
   int               _table_size;
   HashtableBucket<F>*     _buckets;
-  BasicHashtableEntry<F>* _free_list;
+  BasicHashtableEntry<F>* volatile _free_list;
   char*             _first_free_entry;
   char*             _end_block;
   int               _entry_size;
-  int               _number_of_entries;
+  volatile int      _number_of_entries;
 
 protected:
 
@@ -215,6 +215,24 @@
   // Free the buckets in this hashtable
   void free_buckets();
 
+  // Helper data structure containing context for the bucket entry unlink process,
+  // storing the unlinked buckets in a linked list.
+  // Also avoids the need to pass around these four members as parameters everywhere.
+  struct BucketUnlinkContext {
+    int _num_processed;
+    int _num_removed;
+    // Head and tail pointers for the linked list of removed entries.
+    BasicHashtableEntry<F>* _removed_head;
+    BasicHashtableEntry<F>* _removed_tail;
+
+    BucketUnlinkContext() : _num_processed(0), _num_removed(0), _removed_head(NULL), _removed_tail(NULL) {
+    }
+
+    void free_entry(BasicHashtableEntry<F>* entry);
+  };
+  // Add of bucket entries linked together in the given context to the global free list. This method
+  // is mt-safe wrt. to other calls of this method.
+  void bulk_free_entries(BucketUnlinkContext* context);
 public:
   int table_size() { return _table_size; }
   void set_entry(int index, BasicHashtableEntry<F>* entry);
diff --git a/hotspot/test/compiler/c1/TestUnresolvedField.jasm b/hotspot/test/compiler/c1/TestUnresolvedField.jasm
new file mode 100644
index 0000000..e6c2ae4
--- /dev/null
+++ b/hotspot/test/compiler/c1/TestUnresolvedField.jasm
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2017, 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.
+ *
+ */
+
+public class compiler/c1/TestUnresolvedField version 52:0 {
+    public static Method testGetField:"()V" stack 1 locals 1 {
+        aconst_null;
+        getfield Field T.f:I; // T does not exist
+        return;
+    }
+
+    public static Method testPutField:"()V" stack 2 locals 1 {
+        aconst_null;
+        iconst_0;
+        putfield Field T.f:I; // T does not exist
+        return;
+    }
+}
diff --git a/hotspot/test/compiler/c1/TestUnresolvedFieldMain.java b/hotspot/test/compiler/c1/TestUnresolvedFieldMain.java
new file mode 100644
index 0000000..040f1b1
--- /dev/null
+++ b/hotspot/test/compiler/c1/TestUnresolvedFieldMain.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2017, 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 8173373
+ * @compile TestUnresolvedField.jasm
+ * @run main/othervm -XX:TieredStopAtLevel=1 -Xcomp
+ *                   -XX:CompileCommand=compileonly,compiler.c1.TestUnresolvedField::test*
+ *                   compiler.c1.TestUnresolvedFieldMain
+ */
+
+package compiler.c1;
+
+public class TestUnresolvedFieldMain {
+    public static void main(String[] args) {
+        try {
+          TestUnresolvedField.testGetField();
+        } catch (java.lang.NoClassDefFoundError error) {
+          // Expected
+        }
+        try {
+          TestUnresolvedField.testPutField();
+        } catch (java.lang.NoClassDefFoundError error) {
+          // Expected
+        }
+    }
+}
diff --git a/hotspot/test/compiler/c1/UnsafeVolatileGuardTest.java b/hotspot/test/compiler/c1/UnsafeVolatileGuardTest.java
new file mode 100644
index 0000000..69d7c91
--- /dev/null
+++ b/hotspot/test/compiler/c1/UnsafeVolatileGuardTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2017, Red Hat Inc. 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;
+
+/**
+ * @test
+ * @bug 8175887
+ * @summary C1 value numbering handling of Unsafe.get*Volatile is incorrect
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:TieredStopAtLevel=1 UnsafeVolatileGuardTest
+ */
+public class UnsafeVolatileGuardTest {
+    volatile static private int a;
+    static private int b;
+
+    static final sun.misc.Unsafe UNSAFE;
+
+    static final Object BASE;
+    static final long OFFSET;
+
+    static {
+        try {
+            Field uf = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
+            uf.setAccessible(true);
+            UNSAFE = (sun.misc.Unsafe)uf.get(null);
+
+            Field f = UnsafeVolatileGuardTest.class.getDeclaredField("a");
+            BASE = UNSAFE.staticFieldBase(f);
+            OFFSET = UNSAFE.staticFieldOffset(f);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    static void test() {
+        int tt = b; // makes the JVM CSE the value of b
+
+        while (UNSAFE.getIntVolatile(BASE, OFFSET) == 0) {} // burn
+        if (b == 0) {
+            System.err.println("wrong value of b");
+            System.exit(1); // fail hard to report the error
+        }
+    }
+
+    public static void main(String [] args) throws Exception {
+        for (int i = 0; i < 10; i++) {
+            new Thread(UnsafeVolatileGuardTest::test).start();
+        }
+        b = 1;
+        a = 1;
+    }
+}
diff --git a/hotspot/test/compiler/c1/VolatileGuardTest.java b/hotspot/test/compiler/c1/VolatileGuardTest.java
new file mode 100644
index 0000000..44b6031
--- /dev/null
+++ b/hotspot/test/compiler/c1/VolatileGuardTest.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2017, Red Hat Inc. 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 8175887
+ * @summary C1 doesn't respect the JMM with volatile field loads
+ *
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:TieredStopAtLevel=1 VolatileGuardTest
+ */
+public class VolatileGuardTest {
+    volatile static private int a;
+    static private int b;
+
+    static void test() {
+        int tt = b; // makes the JVM CSE the value of b
+
+        while (a == 0) {} // burn
+        if (b == 0) {
+            System.err.println("wrong value of b");
+            System.exit(1); // fail hard to report the error
+        }
+    }
+
+    public static void main(String [] args) throws Exception {
+        for (int i = 0; i < 10; i++) {
+            new Thread(VolatileGuardTest::test).start();
+        }
+        b = 1;
+        a = 1;
+    }
+}
diff --git a/hotspot/test/compiler/dependencies/MonomorphicObjectCall/TestMonomorphicObjectCall.java b/hotspot/test/compiler/dependencies/MonomorphicObjectCall/TestMonomorphicObjectCall.java
index 9325990..8884ce4 100644
--- a/hotspot/test/compiler/dependencies/MonomorphicObjectCall/TestMonomorphicObjectCall.java
+++ b/hotspot/test/compiler/dependencies/MonomorphicObjectCall/TestMonomorphicObjectCall.java
@@ -61,6 +61,7 @@
         String[] vmOpts = new String[] {
                 "-Xbootclasspath/p:" + testClasses,
                 "-Xcomp",
+                "-XX:+IgnoreUnrecognizedVMOptions",
                 "-XX:-VerifyDependencies",
                 "-XX:CompileOnly=TestMonomorphicObjectCall::callFinalize",
                 "-XX:CompileOnly=Object::finalizeObject",
diff --git a/hotspot/test/compiler/jsr292/NullConstantReceiver.java b/hotspot/test/compiler/jsr292/NullConstantReceiver.java
index 067c620..c1592e1 100644
--- a/hotspot/test/compiler/jsr292/NullConstantReceiver.java
+++ b/hotspot/test/compiler/jsr292/NullConstantReceiver.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,8 +23,11 @@
 
 /**
  * @test
- * @bug 8059556
+ * @bug 8059556 8158639 8164508
+ *
  * @run main/othervm -Xbatch NullConstantReceiver
+ * @run main/othervm -Xbatch -XX:CompileCommand=exclude,*::run NullConstantReceiver
+ * @run main/othervm -Xbatch -XX:CompileCommand=compileonly,*::run NullConstantReceiver
  */
 
 import java.lang.invoke.MethodHandle;
diff --git a/hotspot/test/compiler/loopopts/TestCountedLoopSafepointBackedge.java b/hotspot/test/compiler/loopopts/TestCountedLoopSafepointBackedge.java
index d570967..31c32f2 100644
--- a/hotspot/test/compiler/loopopts/TestCountedLoopSafepointBackedge.java
+++ b/hotspot/test/compiler/loopopts/TestCountedLoopSafepointBackedge.java
@@ -24,6 +24,7 @@
 /**
  * @test
  * @bug 8161147
+ * @requires vm.flavor == "server"
  * @summary Safepoint on backedge breaks UseCountedLoopSafepoints
  * @run main/othervm -XX:-BackgroundCompilation -XX:-UseOnStackReplacement -XX:+UseCountedLoopSafepoints TestCountedLoopSafepointBackedge
  *
diff --git a/hotspot/test/compiler/loopopts/TestLoopPeeling.java b/hotspot/test/compiler/loopopts/TestLoopPeeling.java
index d2d2e3d..a32f3cb 100644
--- a/hotspot/test/compiler/loopopts/TestLoopPeeling.java
+++ b/hotspot/test/compiler/loopopts/TestLoopPeeling.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 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,10 +23,16 @@
 
 /*
  * @test
- * @bug 8078262
+ * @bug 8078262 8177095
  * @summary Tests correct dominator information after loop peeling.
- * @run main/othervm -Xcomp -XX:CompileCommand=compileonly,TestLoopPeeling::test* TestLoopPeeling
+ *
+ * @run main/othervm -Xcomp
+ *      -XX:CompileCommand=compileonly,compiler.loopopts.TestLoopPeeling::test*
+ *      compiler.loopopts.TestLoopPeeling
  */
+
+package compiler.loopopts;
+
 public class TestLoopPeeling {
 
     public int[] array = new int[100];
@@ -34,14 +40,16 @@
     public static void main(String args[]) {
         TestLoopPeeling test = new TestLoopPeeling();
         try {
-            test.testArrayAccess(0, 1);
+            test.testArrayAccess1(0, 1);
+            test.testArrayAccess2(0);
+            test.testArrayAccess3(0, false);
             test.testArrayAllocation(0, 1);
         } catch (Exception e) {
             // Ignore exceptions
         }
     }
 
-    public void testArrayAccess(int index, int inc) {
+    public void testArrayAccess1(int index, int inc) {
         int storeIndex = -1;
 
         for (; index < 10; index += inc) {
@@ -57,7 +65,7 @@
 
             if (index == 42) {
                 // This store and the corresponding range check are moved out of the
-                // loop and both used after old loop and the peeled iteration exit.
+                // loop and both used after main loop and the peeled iteration exit.
                 // For the peeled iteration, storeIndex is always -1 and the ConvI2L
                 // is replaced by TOP. However, the range check is not folded because
                 // we don't do the split if optimization in PhaseIdealLoop2.
@@ -71,6 +79,44 @@
         }
     }
 
+    public int testArrayAccess2(int index) {
+        // Load1 and the corresponding range check are moved out of the loop
+        // and both are used after the main loop and the peeled iteration exit.
+        // For the peeled iteration, storeIndex is always Integer.MIN_VALUE and
+        // for the main loop it is 0. Hence, the merging phi has type int:<=0.
+        // Load1 reads the array at index ConvI2L(CastII(AddI(storeIndex, -1)))
+        // where the CastII is range check dependent and has type int:>=0.
+        // The CastII gets pushed through the AddI and its type is changed to int:>=1
+        // which does not overlap with the input type of storeIndex (int:<=0).
+        // The CastII is replaced by TOP causing a cascade of other eliminations.
+        // Since the control path through the range check CmpU(AddI(storeIndex, -1))
+        // is not eliminated, the graph is in a corrupted state. We fail once we merge
+        // with the result of Load2 because we get data from a non-dominating region.
+        int storeIndex = Integer.MIN_VALUE;
+        for (; index < 10; ++index) {
+            if (index == 42) {
+                return array[storeIndex-1]; // Load1
+            }
+            storeIndex = 0;
+        }
+        return array[42]; // Load2
+    }
+
+    public int testArrayAccess3(int index, boolean b) {
+        // Same as testArrayAccess2 but manifests as crash in register allocator.
+        int storeIndex = Integer.MIN_VALUE;
+        for (; index < 10; ++index) {
+            if (b) {
+                return 0;
+            }
+            if (index == 42) {
+                return array[storeIndex-1]; // Load1
+            }
+            storeIndex = 0;
+        }
+        return array[42]; // Load2
+    }
+
     public byte[] testArrayAllocation(int index, int inc) {
         int allocationCount = -1;
         byte[] result;
@@ -82,7 +128,7 @@
 
             if (index == 42) {
                 // This allocation and the corresponding size check are moved out of the
-                // loop and both used after old loop and the peeled iteration exit.
+                // loop and both used after main loop and the peeled iteration exit.
                 // For the peeled iteration, allocationCount is always -1 and the ConvI2L
                 // is replaced by TOP. However, the size check is not folded because
                 // we don't do the split if optimization in PhaseIdealLoop2.
diff --git a/hotspot/test/compiler/profiling/UnsafeAccess.java b/hotspot/test/compiler/profiling/UnsafeAccess.java
new file mode 100644
index 0000000..5251e5c
--- /dev/null
+++ b/hotspot/test/compiler/profiling/UnsafeAccess.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8134918
+ * @modules java.base/jdk.internal.misc
+ * @run main/bootclasspath/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:TypeProfileLevel=222 -XX:+UseTypeSpeculation -Xbatch
+ *                         -XX:CompileCommand=dontinline,UnsafeAccess::test*
+ *                         UnsafeAccess
+ */
+import sun.misc.Unsafe;
+
+public class UnsafeAccess {
+    private static final Unsafe U = Unsafe.getUnsafe();
+
+    static Class cls = Object.class;
+    static long off = U.ARRAY_OBJECT_BASE_OFFSET;
+
+    static Object testUnsafeAccess(Object o, boolean isObjArray) {
+        if (o != null && cls.isInstance(o)) { // speculates "o" type to int[]
+            return helperUnsafeAccess(o, isObjArray);
+        }
+        return null;
+    }
+
+    static Object helperUnsafeAccess(Object o, boolean isObjArray) {
+        if (isObjArray) {
+            U.putObject(o, off, new Object());
+        }
+        return o;
+    }
+
+    static Object testUnsafeLoadStore(Object o, boolean isObjArray) {
+        if (o != null && cls.isInstance(o)) { // speculates "o" type to int[]
+            return helperUnsafeLoadStore(o, isObjArray);
+        }
+        return null;
+    }
+
+    static Object helperUnsafeLoadStore(Object o, boolean isObjArray) {
+        if (isObjArray) {
+            Object o1 = U.getObject(o, off);
+            U.compareAndSwapObject(o, off, o1, new Object());
+        }
+        return o;
+    }
+
+    public static void main(String[] args) {
+        Object[] objArray = new Object[10];
+        int[]    intArray = new    int[10];
+
+        for (int i = 0; i < 20_000; i++) {
+            helperUnsafeAccess(objArray, true);
+        }
+        for (int i = 0; i < 20_000; i++) {
+            testUnsafeAccess(intArray, false);
+        }
+
+        for (int i = 0; i < 20_000; i++) {
+            helperUnsafeLoadStore(objArray, true);
+        }
+        for (int i = 0; i < 20_000; i++) {
+            testUnsafeLoadStore(intArray, false);
+        }
+
+        System.out.println("TEST PASSED");
+    }
+}
diff --git a/hotspot/test/compiler/unsafe/OpaqueAccesses.java b/hotspot/test/compiler/unsafe/OpaqueAccesses.java
new file mode 100644
index 0000000..ba31f96
--- /dev/null
+++ b/hotspot/test/compiler/unsafe/OpaqueAccesses.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  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.
+ */
+
+/*
+ * @test
+ * @bug 8155781
+ * @modules java.base/jdk.internal.misc
+ *
+ * @run main/bootclasspath/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions
+ *                                 -XX:-TieredCompilation -Xbatch
+ *                                 -XX:+UseCompressedOops -XX:+UseCompressedClassPointers
+ *                                 -XX:CompileCommand=dontinline,compiler.unsafe.OpaqueAccesses::test*
+ *                                 compiler.unsafe.OpaqueAccesses
+ * @run main/bootclasspath/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions
+ *                                 -XX:-TieredCompilation -Xbatch
+ *                                 -XX:+UseCompressedOops -XX:-UseCompressedClassPointers
+ *                                 -XX:CompileCommand=dontinline,compiler.unsafe.OpaqueAccesses::test*
+ *                                 compiler.unsafe.OpaqueAccesses
+ * @run main/bootclasspath/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions
+ *                                 -XX:-TieredCompilation -Xbatch
+ *                                 -XX:-UseCompressedOops -XX:+UseCompressedClassPointers
+ *                                 -XX:CompileCommand=dontinline,compiler.unsafe.OpaqueAccesses::test*
+ *                                 compiler.unsafe.OpaqueAccesses
+ * @run main/bootclasspath/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions
+ *                                 -XX:-TieredCompilation -Xbatch
+ *                                 -XX:-UseCompressedOops -XX:-UseCompressedClassPointers
+ *                                 -XX:CompileCommand=dontinline,compiler.unsafe.OpaqueAccesses::test*
+ *                                 compiler.unsafe.OpaqueAccesses
+ */
+package compiler.unsafe;
+
+import sun.misc.Unsafe;
+
+import java.lang.reflect.Field;
+
+public class OpaqueAccesses {
+    private static final Unsafe UNSAFE = Unsafe.getUnsafe();
+
+    private static final Object INSTANCE = new OpaqueAccesses();
+
+    private static final Object[] ARRAY = new Object[10];
+
+    private static final long F_OFFSET;
+    private static final long E_OFFSET;
+
+    static {
+        try {
+            Field field = OpaqueAccesses.class.getDeclaredField("f");
+            F_OFFSET = UNSAFE.objectFieldOffset(field);
+
+            E_OFFSET = UNSAFE.arrayBaseOffset(ARRAY.getClass());
+        } catch (NoSuchFieldException e) {
+            throw new Error(e);
+        }
+    }
+
+    private Object f = new Object();
+    private long l1, l2;
+
+    static Object testFixedOffsetField(Object o) {
+        return UNSAFE.getObject(o, F_OFFSET);
+    }
+
+    static int testFixedOffsetHeader0(Object o) {
+        return UNSAFE.getInt(o, 0);
+    }
+
+    static int testFixedOffsetHeader4(Object o) {
+        return UNSAFE.getInt(o, 4);
+    }
+
+    static int testFixedOffsetHeader8(Object o) {
+        return UNSAFE.getInt(o, 8);
+    }
+
+    static int testFixedOffsetHeader12(Object o) {
+        return UNSAFE.getInt(o, 12);
+    }
+
+    static int testFixedOffsetHeader16(Object o) {
+        return UNSAFE.getInt(o, 16);
+    }
+
+    static Object testFixedBase(long off) {
+        return UNSAFE.getObject(INSTANCE, off);
+    }
+
+    static Object testOpaque(Object o, long off) {
+        return UNSAFE.getObject(o, off);
+    }
+
+    static int testFixedOffsetHeaderArray0(Object[] arr) {
+        return UNSAFE.getInt(arr, 0);
+    }
+
+    static int testFixedOffsetHeaderArray4(Object[] arr) {
+        return UNSAFE.getInt(arr, 4);
+    }
+
+    static int testFixedOffsetHeaderArray8(Object[] arr) {
+        return UNSAFE.getInt(arr, 8);
+    }
+
+    static int testFixedOffsetHeaderArray12(Object[] arr) {
+        return UNSAFE.getInt(arr, 12);
+    }
+
+    static int testFixedOffsetHeaderArray16(Object[] arr) {
+        return UNSAFE.getInt(arr, 16);
+    }
+
+    static Object testFixedOffsetArray(Object[] arr) {
+        return UNSAFE.getObject(arr, E_OFFSET);
+    }
+
+    static Object testFixedBaseArray(long off) {
+        return UNSAFE.getObject(ARRAY, off);
+    }
+
+    static Object testOpaqueArray(Object[] o, long off) {
+        return UNSAFE.getObject(o, off);
+    }
+
+    static final long ADDR = UNSAFE.allocateMemory(10);
+    static boolean flag;
+
+    static int testMixedAccess() {
+        flag = !flag;
+        Object o = (flag ? INSTANCE : null);
+        long off = (flag ? F_OFFSET : ADDR);
+        return UNSAFE.getInt(o, off);
+    }
+
+    public static void main(String[] args) {
+        for (int i = 0; i < 20_000; i++) {
+            // Instance
+            testFixedOffsetField(INSTANCE);
+            testFixedOffsetHeader0(INSTANCE);
+            testFixedOffsetHeader4(INSTANCE);
+            testFixedOffsetHeader8(INSTANCE);
+            testFixedOffsetHeader12(INSTANCE);
+            testFixedOffsetHeader16(INSTANCE);
+            testFixedBase(F_OFFSET);
+            testOpaque(INSTANCE, F_OFFSET);
+            testMixedAccess();
+
+            // Array
+            testFixedOffsetHeaderArray0(ARRAY);
+            testFixedOffsetHeaderArray4(ARRAY);
+            testFixedOffsetHeaderArray8(ARRAY);
+            testFixedOffsetHeaderArray12(ARRAY);
+            testFixedOffsetHeaderArray16(ARRAY);
+            testFixedOffsetArray(ARRAY);
+            testFixedBaseArray(E_OFFSET);
+            testOpaqueArray(ARRAY, E_OFFSET);
+        }
+        System.out.println("TEST PASSED");
+    }
+}
diff --git a/hotspot/test/gc/TestSoftReferencesBehaviorOnOOME.java b/hotspot/test/gc/TestSoftReferencesBehaviorOnOOME.java
index 55fa598..87e5616 100644
--- a/hotspot/test/gc/TestSoftReferencesBehaviorOnOOME.java
+++ b/hotspot/test/gc/TestSoftReferencesBehaviorOnOOME.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014 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
diff --git a/hotspot/test/runtime/Final/Bad.jasm b/hotspot/test/runtime/Final/Bad.jasm
new file mode 100644
index 0000000..b96e6f4
--- /dev/null
+++ b/hotspot/test/runtime/Final/Bad.jasm
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* Recoded in jasm to provoke an ICCE assigning a non-static final field with putstatic.
+class Bad {
+  public static final int i; //rewritten
+  //rewritten to: public final int i;
+  static { i = 5; } // putstatic instruction
+}
+*/
+
+super class Bad
+	version 52:0
+{
+
+// Remove 'static' keyword
+public final Field i:I;
+
+Method "<init>":"()V"
+	stack 1 locals 1
+{
+		aload_0;
+		invokespecial	Method java/lang/Object."<init>":"()V";
+		return;
+}
+
+static Method "<clinit>":"()V"
+	stack 1 locals 0
+{
+		iconst_5;
+		putstatic	Field i:"I";
+		return;
+}
+
+} // end Class Bad
diff --git a/hotspot/test/runtime/Final/PutfieldError.java b/hotspot/test/runtime/Final/PutfieldError.java
new file mode 100644
index 0000000..9669a1b
--- /dev/null
+++ b/hotspot/test/runtime/Final/PutfieldError.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test PutfieldError
+ * @bug 8160551
+ * @summary Throw ICCE rather than crashing for nonstatic final field in static initializer
+ * @compile Bad.jasm
+ * @run main PutfieldError
+ */
+
+public class PutfieldError {
+  public static void main(java.lang.String[] unused) {
+    try {
+      Bad b = new Bad();
+      System.out.println("Bad.i = " + 5);
+      throw new RuntimeException("ICCE NOT thrown as expected");
+    } catch (IncompatibleClassChangeError icce) {
+      System.out.println("ICCE thrown as expected");
+    }
+  }
+}
diff --git a/hotspot/test/runtime/lambda-features/TestInterfaceInit.java b/hotspot/test/runtime/lambda-features/TestInterfaceInit.java
index 0493a60..a6f057c 100644
--- a/hotspot/test/runtime/lambda-features/TestInterfaceInit.java
+++ b/hotspot/test/runtime/lambda-features/TestInterfaceInit.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,8 @@
 /*
  * @test
  * @bug 8034275
- * @summary [JDK 8u40] Test interface initialization: only for interfaces declaring default methods
+ * @bug 8163969
+ * @summary [JDK 8u40] Test interface init: only for interfaces declaring default methods, when subclass inits
  * @run main TestInterfaceInit
  */
 import java.util.List;
@@ -39,43 +40,59 @@
    // Declares a default method and initializes
    interface I {
        boolean v = TestInterfaceInit.out(I.class);
-        default void x() {}
+        default void ix() {}
    }
 
    // Declares a default method and initializes
    interface J extends I {
        boolean v = TestInterfaceInit.out(J.class);
-       default void x() {}
+       default void jx() {}
    }
-   // No default method, does not initialize
+   // No default method, has an abstract method, does not initialize
    interface JN extends J {
        boolean v = TestInterfaceInit.out(JN.class);
+       public abstract void jnx();
    }
 
    // Declares a default method and initializes
    interface K extends I {
        boolean v = TestInterfaceInit.out(K.class);
-        default void x() {}
+        default void kx() {}
    }
 
-   // No default method, does not initialize
+   // No default method, has a static method, does not initialize
    interface KN extends K {
        boolean v = TestInterfaceInit.out(KN.class);
+       static void knx() {}
    }
 
    interface L extends JN, KN {
        boolean v = TestInterfaceInit.out(L.class);
-        default void x() {}
+        default void lx() {}
+   }
+
+   static class ChildClass implements JN, KN {
+       boolean v = TestInterfaceInit.out(ChildClass.class);
+       public void jnx() {}
    }
 
    public static void main(String[] args) {
        // Trigger initialization
        boolean v = L.v;
 
-       List<Class<?>> expectedCInitOrder = Arrays.asList(I.class,J.class,K.class,L.class);
+       List<Class<?>> expectedCInitOrder = Arrays.asList(L.class);
        if (!cInitOrder.equals(expectedCInitOrder)) {
          throw new RuntimeException(String.format("Class initialization array %s not equal to expected array %s", cInitOrder, expectedCInitOrder));
        }
+
+       ChildClass myC = new ChildClass();
+       boolean w = myC.v;
+
+       expectedCInitOrder = Arrays.asList(L.class,I.class,J.class,K.class,ChildClass.class);
+       if (!cInitOrder.equals(expectedCInitOrder)) {
+         throw new RuntimeException(String.format("Class initialization array %s not equal to expected array %s", cInitOrder, expectedCInitOrder));
+       }
+
    }
 
    static boolean out(Class c) {
diff --git a/hotspot/test/runtime/lambda-features/TestStaticandInstance.java b/hotspot/test/runtime/lambda-features/TestStaticandInstance.java
new file mode 100644
index 0000000..9c584d8
--- /dev/null
+++ b/hotspot/test/runtime/lambda-features/TestStaticandInstance.java
@@ -0,0 +1,272 @@
+/*
+ * Copyright (c) 2015, 2017, 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 8087342
+ * @summary Test linkresolver search static, instance and overpass duplicates
+ * @run main/othervm -Xverify:none TestStaticandInstance
+ */
+
+
+import java.util.*;
+import jdk.internal.org.objectweb.asm.*;
+import static jdk.internal.org.objectweb.asm.Opcodes.*;
+
+public class TestStaticandInstance {
+  static final String stringC = "C";
+  static final String stringD = "D";
+  static final String stringI = "I";
+
+  public static void main(String args[]) throws Throwable {
+    ClassLoader cl = new ClassLoader() {
+      public Class<?> loadClass(String name) throws ClassNotFoundException {
+        Class retClass;
+        if ((retClass = findLoadedClass(name)) != null) {
+           return retClass;
+        }
+        if (stringC.equals(name)) {
+            byte[] classFile=dumpC();
+            return defineClass(stringC, classFile, 0, classFile.length);
+        }
+        if (stringD.equals(name)) {
+            byte[] classFile=dumpD();
+            return defineClass(stringD, classFile, 0, classFile.length);
+        }
+        if (stringI.equals(name)) {
+            byte[] classFile=dumpI();
+            return defineClass(stringI, classFile, 0, classFile.length);
+        }
+        return super.loadClass(name);
+      }
+    };
+
+    Class classC = cl.loadClass(stringC);
+    Class classI = cl.loadClass(stringI);
+
+    try {
+      int staticret = (Integer)cl.loadClass(stringD).getDeclaredMethod("CallStatic").invoke(null);
+      if (staticret != 1) {
+        throw new RuntimeException("invokestatic failed to call correct method");
+      }
+      System.out.println("staticret: " + staticret); // should be 1
+
+      int invokeinterfaceret = (Integer)cl.loadClass(stringD).getDeclaredMethod("CallInterface").invoke(null);
+      if (invokeinterfaceret != 0) {
+        throw new RuntimeException(String.format("Expected java.lang.AbstractMethodError, got %d", invokeinterfaceret));
+      }
+      System.out.println("invokeinterfaceret: AbstractMethodError");
+
+      int invokevirtualret = (Integer)cl.loadClass(stringD).getDeclaredMethod("CallVirtual").invoke(null);
+      if (invokevirtualret != 0) {
+        throw new RuntimeException(String.format("Expected java.lang.IncompatibleClassChangeError, got %d", invokevirtualret));
+      }
+      System.out.println("invokevirtualret: IncompatibleClassChangeError");
+    } catch (java.lang.Throwable e) {
+      throw new RuntimeException("Unexpected exception: " + e.getMessage());
+    }
+  }
+
+/*
+interface I {
+  public int m(); // abstract
+  default int q() { return 3; } // trigger defmeth processing: C gets AME overpass
+}
+
+// C gets static, private and AME overpass m()I with -Xverify:none
+class C implements I {
+  static int m() { return 1;}  // javac with "n()" and patch to "m()"
+  private int m() { return 2;} // javac with public and patch to private
+}
+
+public class D {
+  public static int CallStatic() {
+    int staticret = C.m();    // javac with "C.n" and patch to "C.m"
+    return staticret;
+  }
+  public static int CallInterface() throws AbstractMethodError{
+    try {
+      I myI = new C();
+      return myI.m();
+    } catch (java.lang.AbstractMethodError e) {
+      return 0; // for success
+    }
+  }
+  public static int CallVirtual() {
+    try {
+      C myC = new C();
+      return myC.m();
+    } catch (java.lang.IncompatibleClassChangeError e) {
+      return 0; // for success
+    }
+  }
+}
+*/
+
+  public static byte[] dumpC() {
+
+    ClassWriter cw = new ClassWriter(0);
+    FieldVisitor fv;
+    MethodVisitor mv;
+    AnnotationVisitor av0;
+
+    cw.visit(52, ACC_SUPER, "C", null, "java/lang/Object", new String[] { "I" });
+
+    {
+      mv = cw.visitMethod(0, "<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();
+    }
+    {
+      mv = cw.visitMethod(ACC_STATIC, "m", "()I", null, null);
+      mv.visitCode();
+      mv.visitInsn(ICONST_1);
+      mv.visitInsn(IRETURN);
+      mv.visitMaxs(1, 0);
+      mv.visitEnd();
+    }
+    {
+      mv = cw.visitMethod(ACC_PRIVATE, "m", "()I", null, null);
+      mv.visitCode();
+      mv.visitInsn(ICONST_2);
+      mv.visitInsn(IRETURN);
+      mv.visitMaxs(1, 1);
+      mv.visitEnd();
+    }
+    cw.visitEnd();
+
+    return cw.toByteArray();
+  }
+
+  public static byte[] dumpD () {
+
+    ClassWriter cw = new ClassWriter(0);
+    FieldVisitor fv;
+    MethodVisitor mv;
+    AnnotationVisitor av0;
+
+    cw.visit(52, ACC_PUBLIC + ACC_SUPER, "D", 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();
+    }
+    {
+      mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "CallStatic", "()I", null, null);
+      mv.visitCode();
+      mv.visitMethodInsn(INVOKESTATIC, "C", "m", "()I", false);
+      mv.visitVarInsn(ISTORE, 0);
+      mv.visitVarInsn(ILOAD, 0);
+      mv.visitInsn(IRETURN);
+      mv.visitMaxs(1, 1);
+      mv.visitEnd();
+    }
+    {
+      mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "CallInterface", "()I", null, new String[] { "java/lang/AbstractMethodError" });
+      mv.visitCode();
+      Label l0 = new Label();
+      Label l1 = new Label();
+      Label l2 = new Label();
+      mv.visitTryCatchBlock(l0, l1, l2, "java/lang/AbstractMethodError");
+      mv.visitLabel(l0);
+      mv.visitTypeInsn(NEW, "C");
+      mv.visitInsn(DUP);
+      mv.visitMethodInsn(INVOKESPECIAL, "C", "<init>", "()V", false);
+      mv.visitVarInsn(ASTORE, 0);
+      mv.visitVarInsn(ALOAD, 0);
+      mv.visitMethodInsn(INVOKEINTERFACE, "I", "m", "()I", true);
+      mv.visitLabel(l1);
+      mv.visitInsn(IRETURN);
+      mv.visitLabel(l2);
+      mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] {"java/lang/AbstractMethodError"});
+      mv.visitVarInsn(ASTORE, 0);
+      mv.visitInsn(ICONST_0);
+      mv.visitInsn(IRETURN);
+      mv.visitMaxs(2, 1);
+      mv.visitEnd();
+    }
+    {
+      mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "CallVirtual", "()I", null, null);
+      mv.visitCode();
+      Label l0 = new Label();
+      Label l1 = new Label();
+      Label l2 = new Label();
+      mv.visitTryCatchBlock(l0, l1, l2, "java/lang/IncompatibleClassChangeError");
+      mv.visitLabel(l0);
+      mv.visitTypeInsn(NEW, "C");
+      mv.visitInsn(DUP);
+      mv.visitMethodInsn(INVOKESPECIAL, "C", "<init>", "()V", false);
+      mv.visitVarInsn(ASTORE, 0);
+      mv.visitVarInsn(ALOAD, 0);
+      mv.visitMethodInsn(INVOKEVIRTUAL, "C", "m", "()I", false);
+      mv.visitLabel(l1);
+      mv.visitInsn(IRETURN);
+      mv.visitLabel(l2);
+      mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] {"java/lang/IncompatibleClassChangeError"});
+      mv.visitVarInsn(ASTORE, 0);
+      mv.visitInsn(ICONST_0);
+      mv.visitInsn(IRETURN);
+      mv.visitMaxs(2, 1);
+      mv.visitEnd();
+    }
+    cw.visitEnd();
+
+    return cw.toByteArray();
+  }
+
+  public static byte[] dumpI() {
+
+    ClassWriter cw = new ClassWriter(0);
+    FieldVisitor fv;
+    MethodVisitor mv;
+    AnnotationVisitor av0;
+
+    cw.visit(52, ACC_ABSTRACT + ACC_INTERFACE, "I", null, "java/lang/Object", null);
+
+    {
+      mv = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "m", "()I", null, null);
+      mv.visitEnd();
+    }
+    {
+      mv = cw.visitMethod(ACC_PUBLIC, "q", "()I", null, null);
+      mv.visitCode();
+      mv.visitInsn(ICONST_3);
+      mv.visitInsn(IRETURN);
+      mv.visitMaxs(1, 1);
+      mv.visitEnd();
+    }
+    cw.visitEnd();
+
+    return cw.toByteArray();
+  }
+}
diff --git a/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java b/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java
index 8421519..b332c1e 100644
--- a/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -260,8 +260,8 @@
             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
             output.shouldHaveExitValue(0);
 
-            // Search for a line starting with numbers (pid), follwed by the key.
-            Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
+            // Search for a line starting with numbers (pid), followed by the key.
+            Pattern pattern = Pattern.compile("^([0-9]+)\\s.*(" + key + ")", Pattern.MULTILINE);
             Matcher matcher = pattern.matcher(output.getStdout());
 
             int pid = -1;
diff --git a/jaxp/.hgtags b/jaxp/.hgtags
index 4e174da..348cc8e 100644
--- a/jaxp/.hgtags
+++ b/jaxp/.hgtags
@@ -723,3 +723,25 @@
 202d9386f011016b0c83bcc98e78966a42eec284 jdk8u151-b05
 67150ea02ae49888b0300ef8baf2dcf90beb45ff jdk8u151-b06
 838cb61b03b84ec86dd2685a40d7d278236946f5 jdk8u151-b07
+4e43afdbc6017a6dd7be40e7a41cd0dd38a499a0 jdk8u151-b08
+2e5a470691f23ebf8d1f0f0dea8ef7de9a70a943 jdk8u122-b00
+cbb8efe139275a4e7c541f9e45eb410c27a5ea61 jdk8u122-b01
+e279f24557d43d8edfe313cb1a53add7ac6ceb2c jdk8u122-b02
+4d0371f160495cc61e3b57ca2d57884c2b9f9068 jdk8u122-b03
+4d0371f160495cc61e3b57ca2d57884c2b9f9068 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+95728234c69f848fda20c3d107a2a14405e8e8bd jdk8u122-b03
+540ca507f5e33ad46c85750f5df110522454cb2d jdk8u122-b04
+7f6d0e9a119670bb83ab2961503471d73f8a5f7e jdk8u132-b00
+4203c092a35355406709027827e9130f79dd96ca jdk8u152-b00
+bedfdbc290ac3c771c107a644250c1985f26fb2f jdk8u152-b01
+519a2d274fd0e2f83317e08b6d891c25d56d7405 jdk8u152-b02
+a7f773d06b75f04b44166316bbb4a0244d127d14 jdk8u152-b03
+65ec92c434b62ad9b1dd0a5280ac0030dd275775 jdk8u152-b04
+3a66a08564badcbef3e60d050647437416bce068 jdk8u152-b05
+acb6450dffcf8cfbe72fef501d0d287adbf8dd43 jdk8u152-b06
+5487838dba527fe94e197bfccb9bca58e7563b0b jdk8u152-b07
+d36b0186befa153f155302f394797ddcacbcaf70 jdk8u152-b08
+3e9d12fac1d0737a0726ec10c1abb4b8fa75a56c jdk8u152-b09
+9a4e0d4984a41d7413fbd4cbf12b53a3631a1132 jdk8u152-b10
diff --git a/jaxp/ASSEMBLY_EXCEPTION b/jaxp/ASSEMBLY_EXCEPTION
index 8b7ac1d..065b8d9 100644
--- a/jaxp/ASSEMBLY_EXCEPTION
+++ b/jaxp/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Sun at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Sun gives you permission to link this
-    OpenJDK Code with certain code licensed by Sun as indicated at
+    As a special exception, Oracle gives you permission to link this
+    OpenJDK Code with certain code licensed by Oracle as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Sun.
+    governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Sun
-could not provide under GPL2 (or that Sun has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
index e136357..c392cbe 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -9,7 +9,7 @@
  * (the "License"); you may not use this file except in compliance with
  * the License.  You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: LiteralElement.java,v 1.2.4.1 2005/09/13 12:38:33 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -58,8 +55,6 @@
     // names are not known at compile time.
     private boolean _allAttributesUnique = false;
 
-    private final static String XMLNS_STRING = "xmlns";
-
     /**
      * Returns the QName for this literal element
      */
@@ -140,8 +135,8 @@
         // Treat default namespace as "" and not null
         if (prefix == null)
             prefix = Constants.EMPTYSTRING;
-        else if (prefix.equals(XMLNS_STRING))
-            return(XMLNS_STRING);
+        else if (prefix.equals(XMLNS_PREFIX))
+            return(XMLNS_PREFIX);
 
         // Check if we must translate the prefix
         final String alternative = stable.lookupPrefixAlias(prefix);
@@ -266,7 +261,7 @@
                 // Ignore special attributes (e.g. xmlns:prefix and xmlns)
                 final String prefix = qname.getPrefix();
                 if (prefix != null && prefix.equals(XMLNS_PREFIX) ||
-                    prefix == null && qname.getLocalPart().equals("xmlns") ||
+                    prefix == null && qname.getLocalPart().equals(XMLNS_PREFIX) ||
                     uri != null && uri.equals(XSLT_URI))
                 {
                     continue;
@@ -339,9 +334,9 @@
         il.append(methodGen.startElement());
 
         // The value of an attribute may depend on a (sibling) variable
-        int j=0;
+        int j = 0;
         while (j < elementCount())  {
-            final SyntaxTreeNode item = (SyntaxTreeNode) elementAt(j);
+            final SyntaxTreeNode item = elementAt(j);
             if (item instanceof Variable) {
                 item.translate(classGen, methodGen);
             }
@@ -350,35 +345,12 @@
 
         // Compile code to emit namespace attributes
         if (_accessedPrefixes != null) {
-            boolean declaresDefaultNS = false;
-
             for (Map.Entry<String, String> entry : _accessedPrefixes.entrySet()) {
                 final String prefix = entry.getKey();
                 final String uri = entry.getValue();
-
-                if (uri != Constants.EMPTYSTRING ||
-                        prefix != Constants.EMPTYSTRING)
-                {
-                    if (prefix == Constants.EMPTYSTRING) {
-                        declaresDefaultNS = true;
-                    }
-                    il.append(methodGen.loadHandler());
-                    il.append(new PUSH(cpg,prefix));
-                    il.append(new PUSH(cpg,uri));
-                    il.append(methodGen.namespace());
-                }
-            }
-
-            /*
-             * If our XslElement parent redeclares the default NS, and this
-             * element doesn't, it must be redeclared one more time.
-             */
-            if (!declaresDefaultNS && (_parent instanceof XslElement)
-                    && ((XslElement) _parent).declaresDefaultNS())
-            {
                 il.append(methodGen.loadHandler());
-                il.append(new PUSH(cpg, Constants.EMPTYSTRING));
-                il.append(new PUSH(cpg, Constants.EMPTYSTRING));
+                il.append(new PUSH(cpg, prefix));
+                il.append(new PUSH(cpg, uri));
                 il.append(methodGen.namespace());
             }
         }
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
index d15d90e..7088850 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: Parser.java,v 1.2.4.1 2005/09/13 12:14:32 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -37,6 +34,7 @@
 import java.io.File;
 import java.io.IOException;
 import java.io.StringReader;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -44,7 +42,6 @@
 import java.util.Properties;
 import java.util.Stack;
 import java.util.StringTokenizer;
-import java.util.Vector;
 import javax.xml.XMLConstants;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
@@ -68,20 +65,20 @@
  */
 public class Parser implements Constants, ContentHandler {
 
-    private static final String XSL = "xsl";            // standard prefix
+    private static final String XSL = "xsl";           // standard prefix
     private static final String TRANSLET = "translet"; // extension prefix
 
     private Locator _locator = null;
 
-    private XSLTC _xsltc;             // Reference to the compiler object.
-    private XPathParser _xpathParser; // Reference to the XPath parser.
-    private Vector _errors;           // Contains all compilation errors
-    private Vector _warnings;         // Contains all compilation errors
+    private XSLTC _xsltc;                  // Reference to the compiler object.
+    private XPathParser _xpathParser;      // Reference to the XPath parser.
+    private ArrayList<ErrorMsg> _errors;   // Contains all compilation errors
+    private ArrayList<ErrorMsg> _warnings; // Contains all compilation warnings
 
     private Map<String, String>   _instructionClasses; // Maps instructions to classes
     private Map<String, String[]> _instructionAttrs;  // reqd and opt attrs
-    private Map<String, QName>   _qNames;
-    private Map<String, Map>     _namespaces;
+    private Map<String, QName>    _qNames;
+    private Map<String, Map<String, QName>> _namespaces;
     private QName       _useAttributeSets;
     private QName       _excludeResultPrefixes;
     private QName       _extensionElementPrefixes;
@@ -113,8 +110,8 @@
         _instructionAttrs    = new HashMap<>();
         _variableScope       = new HashMap<>();
         _template            = null;
-        _errors              = new Vector();
-        _warnings            = new Vector();
+        _errors              = new ArrayList<>();
+        _warnings            = new ArrayList<>();
         _symbolTable         = new SymbolTable();
         _xpathParser         = new XPathParser(this);
         _currentStylesheet   = null;
@@ -139,7 +136,6 @@
     public void setOutput(Output output) {
         if (_output != null) {
             if (_output.getImportPrecedence() <= output.getImportPrecedence()) {
-                String cdata = _output.getCdata();
                 output.mergeOutput(_output);
                 _output.disable();
                 _output = output;
@@ -173,12 +169,13 @@
         Object existing = _variableScope.get(var.getName().getStringRep());
         if (existing != null) {
             if (existing instanceof Stack) {
-                Stack stack = (Stack)existing;
+                @SuppressWarnings("unchecked")
+                Stack<VariableBase> stack = (Stack<VariableBase>)existing;
                 stack.push(var);
             }
             else if (existing instanceof VariableBase) {
-                Stack stack = new Stack();
-                stack.push(existing);
+                Stack<VariableBase> stack = new Stack<>();
+                stack.push((VariableBase)existing);
                 stack.push(var);
                 _variableScope.put(var.getName().getStringRep(), stack);
             }
@@ -191,7 +188,8 @@
     public void removeVariable(QName name) {
         Object existing = _variableScope.get(name.getStringRep());
         if (existing instanceof Stack) {
-            Stack stack = (Stack)existing;
+            @SuppressWarnings("unchecked")
+            Stack<VariableBase> stack = (Stack<VariableBase>)existing;
             if (!stack.isEmpty()) stack.pop();
             if (!stack.isEmpty()) return;
         }
@@ -201,13 +199,14 @@
     public VariableBase lookupVariable(QName name) {
         Object existing = _variableScope.get(name.getStringRep());
         if (existing instanceof VariableBase) {
-            return((VariableBase)existing);
+            return (VariableBase)existing;
         }
         else if (existing instanceof Stack) {
-            Stack stack = (Stack)existing;
-            return((VariableBase)stack.peek());
+            @SuppressWarnings("unchecked")
+            Stack<VariableBase> stack = (Stack<VariableBase>)existing;
+            return stack.peek();
         }
-        return(null);
+        return null;
     }
 
     public void setXSLTC(XSLTC xsltc) {
@@ -397,7 +396,6 @@
         try {
             if (stylesheet != null) {
                 stylesheet.parseContents(this);
-                final int precedence = stylesheet.getImportPrecedence();
                 final Iterator<SyntaxTreeNode> elements = stylesheet.elements();
                 while (elements.hasNext()) {
                     SyntaxTreeNode child = elements.next();
@@ -704,8 +702,6 @@
            new String[] {"stylesheet-prefix", "result-prefix"});
     }
 
-
-
     /**
      * Initialize the _instructionClasses map, which maps XSL element
      * names to Java classes in this package.
@@ -779,6 +775,7 @@
     /**
      * Add primops and base functions to the symbol table.
      */
+    @SuppressWarnings("unused")
     private void initSymbolTable() {
         MethodType I_V  = new MethodType(Type.Int, Type.Void);
         MethodType I_R  = new MethodType(Type.Int, Type.Real);
@@ -971,12 +968,12 @@
         String local, Attributes attributes)
     {
         SyntaxTreeNode node = null;
-        QName  qname = getQName(uri, prefix, local);
+        QName qname = getQName(uri, prefix, local);
         String className = _instructionClasses.get(qname.getStringRep());
 
         if (className != null) {
             try {
-                final Class clazz = ObjectFactory.findProviderClass(className, true);
+                final Class<?> clazz = ObjectFactory.findProviderClass(className, true);
                 node = (SyntaxTreeNode)clazz.newInstance();
                 node.setQName(qname);
                 node.setParser(this);
@@ -1023,7 +1020,7 @@
                 else {
                     Stylesheet sheet = _xsltc.getStylesheet();
                     if ((sheet != null) && (sheet.isExtension(uri))) {
-                        if (sheet != (SyntaxTreeNode)_parentStack.peek()) {
+                        if (sheet != _parentStack.peek()) {
                             node = new UnsupportedElement(uri, prefix, local, true);
                             UnsupportedElement elem = (UnsupportedElement)node;
                             ErrorMsg msg =
@@ -1156,7 +1153,6 @@
                     node.setParser(this);
                     node.setParent(parent);
                     node.setLineNumber(line);
-// System.out.println("e = " + text + " " + node);
                     return node;
                 }
             }
@@ -1191,7 +1187,7 @@
         if (size > 0) {
             System.err.println(new ErrorMsg(ErrorMsg.COMPILER_ERROR_KEY));
             for (int i = 0; i < size; i++) {
-                System.err.println("  " + _errors.elementAt(i));
+                System.err.println("  " + _errors.get(i));
             }
         }
     }
@@ -1204,7 +1200,7 @@
         if (size > 0) {
             System.err.println(new ErrorMsg(ErrorMsg.COMPILER_WARNING_KEY));
             for (int i = 0; i < size; i++) {
-                System.err.println("  " + _warnings.elementAt(i));
+                System.err.println("  " + _warnings.get(i));
             }
         }
     }
@@ -1217,42 +1213,42 @@
         case Constants.INTERNAL:
             // Unexpected internal errors, such as null-ptr exceptions, etc.
             // Immediately terminates compilation, no translet produced
-            _errors.addElement(error);
+            _errors.add(error);
             break;
         case Constants.UNSUPPORTED:
             // XSLT elements that are not implemented and unsupported ext.
             // Immediately terminates compilation, no translet produced
-            _errors.addElement(error);
+            _errors.add(error);
             break;
         case Constants.FATAL:
             // Fatal error in the stylesheet input (parsing or content)
             // Immediately terminates compilation, no translet produced
-            _errors.addElement(error);
+            _errors.add(error);
             break;
         case Constants.ERROR:
             // Other error in the stylesheet input (parsing or content)
             // Does not terminate compilation, no translet produced
-            _errors.addElement(error);
+            _errors.add(error);
             break;
         case Constants.WARNING:
             // Other error in the stylesheet input (content errors only)
             // Does not terminate compilation, a translet is produced
-            _warnings.addElement(error);
+            _warnings.add(error);
             break;
         }
     }
 
-    public Vector getErrors() {
+    public ArrayList<ErrorMsg> getErrors() {
         return _errors;
     }
 
-    public Vector getWarnings() {
+    public ArrayList<ErrorMsg> getWarnings() {
         return _warnings;
     }
 
     /************************ SAX2 ContentHandler INTERFACE *****************/
 
-    private Stack _parentStack = null;
+    private Stack<SyntaxTreeNode> _parentStack = null;
     private Map<String, String> _prefixMapping = null;
 
     /**
@@ -1262,7 +1258,7 @@
         _root = null;
         _target = null;
         _prefixMapping = null;
-        _parentStack = new Stack();
+        _parentStack = new Stack<>();
     }
 
     /**
@@ -1318,7 +1314,7 @@
             _root = element;
         }
         else {
-            SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek();
+            SyntaxTreeNode parent = _parentStack.peek();
             parent.addElement(element);
             element.setParent(parent);
         }
@@ -1349,7 +1345,7 @@
      */
     public void characters(char[] ch, int start, int length) {
         String string = new String(ch, start, length);
-        SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek();
+        SyntaxTreeNode parent = _parentStack.peek();
 
         if (string.length() == 0) return;
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
index 1e8ad86..01ef38b 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
@@ -73,7 +73,7 @@
     protected QName _qname;                    // The element QName
     private int _line;                         // Source file line number
     protected AttributesImpl _attributes = null;   // Attributes of this element
-    private   Map<String, String> _prefixMapping = null; // Namespace declarations
+    private Map<String, String> _prefixMapping = null; // Namespace declarations
 
     // Sentinel - used to denote unrecognised syntaxt tree nodes.
     protected static final SyntaxTreeNode Dummy = new AbsolutePathPattern(null);
@@ -829,7 +829,7 @@
      * @param pos The child node's position.
      * @return The child node.
      */
-    protected final Object elementAt(int pos) {
+    protected final SyntaxTreeNode elementAt(int pos) {
         return _contents.get(pos);
     }
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/WithParam.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/WithParam.java
index fc2b202..37d4cf9 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/WithParam.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/WithParam.java
@@ -128,8 +128,7 @@
                 parser.reportError(Constants.ERROR, err);
             }
             setName(parser.getQNameIgnoreDefaultNs(name));
-        }
-        else {
+        } else {
             reportError(this, parser, ErrorMsg.REQUIRED_ATTR_ERR, "name");
         }
 
@@ -151,8 +150,7 @@
             if (tselect instanceof ReferenceType == false) {
                 _select = new CastExpr(_select, Type.Reference);
             }
-        }
-        else {
+        } else {
             typeCheckContents(stable);
         }
         return Type.Void;
@@ -163,23 +161,24 @@
      * a 'select' attribute, or in the with-param element's body
      */
     public void translateValue(ClassGenerator classGen,
-                               MethodGenerator methodGen) {
+                               MethodGenerator methodGen)
+    {
         // Compile expression is 'select' attribute if present
         if (_select != null) {
             _select.translate(classGen, methodGen);
             _select.startIterator(classGen, methodGen);
-        }
         // If not, compile result tree from parameter body if present.
         // Store result tree into local variable for releasing it later
-        else if (hasContents()) {
+        } else if (hasContents()) {
             final InstructionList il = methodGen.getInstructionList();
             compileResultTree(classGen, methodGen);
-            _domAdapter = methodGen.addLocalVariable2("@" + _escapedName, Type.ResultTree.toJCType(), il.getEnd());
+            _domAdapter = methodGen.addLocalVariable2("@" + _escapedName,
+                                                      Type.ResultTree.toJCType(),
+                                                      il.getEnd());
             il.append(DUP);
             il.append(new ASTORE(_domAdapter.getIndex()));
-        }
         // If neither are present then store empty string in parameter slot
-        else {
+        } else {
             final ConstantPoolGen cpg = classGen.getConstantPool();
             final InstructionList il = methodGen.getInstructionList();
             il.append(new PUSH(cpg, Constants.EMPTYSTRING));
@@ -223,22 +222,31 @@
     /**
      * Release the compiled result tree.
      */
-    public void releaseResultTree(ClassGenerator classGen, MethodGenerator methodGen) {
+    public void releaseResultTree(ClassGenerator classGen,
+                                  MethodGenerator methodGen)
+    {
         if (_domAdapter != null) {
             final ConstantPoolGen cpg = classGen.getConstantPool();
             final InstructionList il = methodGen.getInstructionList();
-            if (classGen.getStylesheet().callsNodeset() && classGen.getDOMClass().equals(MULTI_DOM_CLASS)) {
-                final int removeDA = cpg.addMethodref(MULTI_DOM_CLASS, "removeDOMAdapter", "(" + DOM_ADAPTER_SIG + ")V");
+            if (classGen.getStylesheet().callsNodeset() &&
+                classGen.getDOMClass().equals(MULTI_DOM_CLASS))
+            {
+                final int removeDA =
+                    cpg.addMethodref(MULTI_DOM_CLASS, "removeDOMAdapter",
+                                     "(" + DOM_ADAPTER_SIG + ")V");
                 il.append(methodGen.loadDOM());
                 il.append(new CHECKCAST(cpg.addClass(MULTI_DOM_CLASS)));
                 il.append(new ALOAD(_domAdapter.getIndex()));
                 il.append(new CHECKCAST(cpg.addClass(DOM_ADAPTER_CLASS)));
                 il.append(new INVOKEVIRTUAL(removeDA));
             }
-            final int release = cpg.addInterfaceMethodref(DOM_IMPL_CLASS, "release", "()V");
+            final int release =
+                cpg.addInterfaceMethodref(DOM_IMPL_CLASS, "release", "()V");
             il.append(new ALOAD(_domAdapter.getIndex()));
             il.append(new INVOKEINTERFACE(release, 1));
+            _domAdapter.setEnd(il.getEnd());
+            methodGen.removeLocalVariable(_domAdapter);
             _domAdapter = null;
-         }
-     }
+        }
+    }
 }
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
index 3218181..631edbd 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: XSLTC.java,v 1.2.4.1 2005/09/05 09:51:38 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -39,6 +36,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Date;
 import java.util.Enumeration;
@@ -283,7 +281,7 @@
     }
 
     /*
-     * Function loads an external extension functions.
+     * Function loads an external extension function.
      * The filtering of function types (external,internal) takes place in FunctionCall class
      *
      */
@@ -598,18 +596,18 @@
     }
 
     /**
-     * Get a Vector containing all compile error messages
-     * @return A Vector containing all compile error messages
+     * Get a list of all compile error messages
+     * @return A List containing all compile error messages
      */
-    public Vector getErrors() {
+    public ArrayList<ErrorMsg> getErrors() {
         return _parser.getErrors();
     }
 
     /**
-     * Get a Vector containing all compile warning messages
-     * @return A Vector containing all compile error messages
+     * Get a list of all compile warning messages
+     * @return A List containing all compile error messages
      */
-    public Vector getWarnings() {
+    public ArrayList<ErrorMsg> getWarnings() {
         return _parser.getWarnings();
     }
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
index e04bab7..e94ebb1 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: XslElement.java,v 1.2.4.1 2005/09/12 11:39:55 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -60,14 +57,6 @@
         displayContents(indent + IndentIncrement);
     }
 
-    /**
-     * This method is now deprecated. The new implemation of this class
-     * never declares the default NS.
-     */
-    public boolean declaresDefaultNS() {
-        return false;
-    }
-
     public void parseContents(Parser parser) {
         final SymbolTable stable = parser.getSymbolTable();
 
@@ -210,7 +199,6 @@
      * on the handler (vii) evaluates the contents (viii) calls endElement().
      */
     public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
-        LocalVariableGen local = null;
         final ConstantPoolGen cpg = classGen.getConstantPool();
         final InstructionList il = methodGen.getInstructionList();
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
index 8bbc541..bce2c3a 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * Copyright 2001-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -17,18 +17,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: TemplatesHandlerImpl.java,v 1.2.4.1 2005/09/06 12:09:03 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
-import javax.xml.XMLConstants;
-import javax.xml.transform.Source;
-import javax.xml.transform.Templates;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.URIResolver;
-import javax.xml.transform.sax.TemplatesHandler;
 import com.sun.org.apache.xalan.internal.XalanConstants;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.CompilerException;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.Parser;
@@ -37,15 +28,19 @@
 import com.sun.org.apache.xalan.internal.xsltc.compiler.SyntaxTreeNode;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
-
+import java.util.ArrayList;
+import javax.xml.XMLConstants;
+import javax.xml.transform.Source;
+import javax.xml.transform.Templates;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.sax.TemplatesHandler;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.InputSource;
 import org.xml.sax.Locator;
 import org.xml.sax.SAXException;
 import org.xml.sax.Attributes;
 
-import java.util.Vector;
-
 /**
  * Implementation of a JAXP1.1 TemplatesHandler
  * @author Morten Jorgensen
@@ -268,13 +263,13 @@
                 }
             }
             else {
-                StringBuffer errorMessage = new StringBuffer();
-                Vector errors = _parser.getErrors();
+                StringBuilder errorMessage = new StringBuilder();
+                ArrayList<ErrorMsg> errors = _parser.getErrors();
                 final int count = errors.size();
                 for (int i = 0; i < count; i++) {
                     if (errorMessage.length() > 0)
                         errorMessage.append('\n');
-                    errorMessage.append(errors.elementAt(i).toString());
+                    errorMessage.append(errors.get(i).toString());
                 }
                 throw new SAXException(ErrorMsg.JAXP_COMPILE_ERR, new TransformerException(errorMessage.toString()));
             }
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
index b37c8f4..e30fffd 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: TransformerFactoryImpl.java,v 1.8 2007/04/09 21:30:41 joehw Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
@@ -48,6 +45,7 @@
 import java.io.InputStream;
 import java.net.MalformedURLException;
 import java.net.URL;
+import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.Map;
 import java.util.Properties;
@@ -592,7 +590,7 @@
         }
 
         // Inefficient, but array is small
-        for (int i =0; i < features.length; i++) {
+        for (int i = 0; i < features.length; i++) {
             if (name.equals(features[i])) {
                 return true;
             }
@@ -799,7 +797,7 @@
     /**
      * Pass warning messages from the compiler to the error listener
      */
-    private void passWarningsToListener(Vector messages)
+    private void passWarningsToListener(ArrayList<ErrorMsg> messages)
         throws TransformerException
     {
         if (_errorListener == null || messages == null) {
@@ -808,7 +806,7 @@
         // Pass messages to listener, one by one
         final int count = messages.size();
         for (int pos = 0; pos < count; pos++) {
-            ErrorMsg msg = (ErrorMsg)messages.elementAt(pos);
+            ErrorMsg msg = messages.get(pos);
             // Workaround for the TCK failure ErrorListener.errorTests.error001.
             if (msg.isWarningError())
                 _errorListener.error(
@@ -822,7 +820,7 @@
     /**
      * Pass error messages from the compiler to the error listener
      */
-    private void passErrorsToListener(Vector messages) {
+    private void passErrorsToListener(ArrayList<ErrorMsg> messages) {
         try {
             if (_errorListener == null || messages == null) {
                 return;
@@ -830,7 +828,7 @@
             // Pass messages to listener, one by one
             final int count = messages.size();
             for (int pos = 0; pos < count; pos++) {
-                String message = messages.elementAt(pos).toString();
+                String message = messages.get(pos).toString();
                 _errorListener.error(new TransformerException(message));
             }
         }
@@ -1004,40 +1002,39 @@
         }
 
         // Check that the transformation went well before returning
-    if (bytecodes == null) {
-        Vector errs = xsltc.getErrors();
-        ErrorMsg err;
-        if (errs != null) {
-            err = (ErrorMsg)errs.elementAt(errs.size()-1);
-        } else {
-            err = new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR);
-        }
-        Throwable cause = err.getCause();
-        TransformerConfigurationException exc;
-        if (cause != null) {
-            exc =  new TransformerConfigurationException(cause.getMessage(), cause);
-        } else {
-            exc =  new TransformerConfigurationException(err.toString());
-        }
-
-        // Pass compiler errors to the error listener
-        if (_errorListener != null) {
-            passErrorsToListener(xsltc.getErrors());
-
-            // As required by TCK 1.2, send a fatalError to the
-            // error listener because compilation of the stylesheet
-            // failed and no further processing will be possible.
-            try {
-                _errorListener.fatalError(exc);
-            } catch (TransformerException te) {
-                // well, we tried.
+        if (bytecodes == null) {
+            ArrayList<ErrorMsg> errs = xsltc.getErrors();
+            ErrorMsg err;
+            if (errs != null) {
+                err = errs.get(errs.size() - 1);
+            } else {
+                err = new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR);
             }
+            Throwable cause = err.getCause();
+            TransformerConfigurationException exc;
+            if (cause != null) {
+                exc =  new TransformerConfigurationException(cause.getMessage(), cause);
+            } else {
+                exc =  new TransformerConfigurationException(err.toString());
+            }
+
+            // Pass compiler errors to the error listener
+            if (_errorListener != null) {
+                passErrorsToListener(xsltc.getErrors());
+
+                // As required by TCK 1.2, send a fatalError to the
+                // error listener because compilation of the stylesheet
+                // failed and no further processing will be possible.
+                try {
+                    _errorListener.fatalError(exc);
+                } catch (TransformerException te) {
+                    // well, we tried.
+                }
+            } else {
+                xsltc.printErrors();
+            }
+            throw exc;
         }
-        else {
-            xsltc.printErrors();
-        }
-        throw exc;
-    }
 
         return new TemplatesImpl(bytecodes, transletName,
             xsltc.getOutputProperties(), _indentNumber, this);
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/dom/AbortException.java b/jaxp/src/com/sun/org/apache/xerces/internal/dom/AbortException.java
new file mode 100644
index 0000000..3e178dd
--- /dev/null
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/dom/AbortException.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  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 com.sun.org.apache.xerces.internal.dom;
+
+public class AbortException extends RuntimeException {
+
+        private static final long serialVersionUID = 2608302175475740417L;
+
+        /**
+         * Constructor AbortException
+         */
+        public AbortException() { super(null, null, false, false); }
+}
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java b/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
index 3758f39..c4268dc 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
@@ -26,6 +26,7 @@
 import java.io.StringReader;
 import java.util.Vector;
 
+import com.sun.org.apache.xerces.internal.dom.AbortException;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.RevalidationHandler;
 import com.sun.org.apache.xerces.internal.impl.dtd.DTDGrammar;
@@ -158,11 +159,6 @@
     // attribute value normalization
     final XMLString fNormalizedValue = new XMLString(new char[16], 0, 0);
 
-    /**
-     * If the user stops the process, this exception will be thrown.
-     */
-    public static final RuntimeException abort = new RuntimeException();
-
     //DTD validator
     private XMLDTDValidator fDTDValidator;
 
@@ -243,11 +239,10 @@
                                         XMLGrammarDescription.XML_SCHEMA, fValidationHandler);
                                 fValidationHandler = null;
                         }
-                }
-                catch (RuntimeException e) {
-            if( e==abort )
-                return; // processing aborted by the user
-            throw e;    // otherwise re-throw.
+                } catch (AbortException e) {
+                    return;
+                } catch (RuntimeException e) {
+                    throw e;    // otherwise re-throw.
                 }
 
         }
@@ -1372,10 +1367,10 @@
             error.fRelatedData = locator.fRelatedNode;
 
             if(!errorHandler.handleError(error))
-                throw abort;
+                throw new AbortException();
         }
         if( severity==DOMError.SEVERITY_FATAL_ERROR )
-            throw abort;
+            throw new AbortException();
     }
 
     protected final void updateQName (Node node, QName qname){
@@ -2044,5 +2039,4 @@
         return null;
     }
 
-
 }  // DOMNormalizer class
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
index dac7fbf..84543ec 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2671,6 +2671,9 @@
             customTimezoneId.append(sign);
             customTimezoneId.append(hour);
             if (minutes != 0) {
+                if (minutes < 10) {
+                    customTimezoneId.append('0');
+                }
                 customTimezoneId.append(minutes);
             }
             result = TimeZone.getTimeZone(customTimezoneId.toString());
diff --git a/jaxp/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java b/jaxp/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
index d17cf33..8f14d74 100644
--- a/jaxp/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
@@ -33,6 +33,7 @@
 import java.util.StringTokenizer;
 import java.util.Vector;
 
+import com.sun.org.apache.xerces.internal.dom.AbortException;
 import com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMErrorImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMLocatorImpl;
@@ -117,7 +118,6 @@
     private DOMErrorHandler fErrorHandler = null;
     private final DOMErrorImpl fError = new DOMErrorImpl();
     private final DOMLocatorImpl fLocator = new DOMLocatorImpl();
-    private static final RuntimeException abort = new RuntimeException();
 
     /**
      * Constructs a new LSSerializer.
@@ -539,11 +539,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return null;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort){
-                // stopped at user request
-                return null;
-            }
             throw (LSException) new LSException(LSException.SERIALIZE_ERR, e.toString()).initCause(e);
         } catch (IOException ioe) {
             // REVISIT: A generic IOException doesn't provide enough information
@@ -836,11 +834,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return false;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort){
-                // stopped at user request
-                return false;
-            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (Exception e) {
             if (ser.fDOMErrorHandler != null) {
@@ -992,11 +988,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return false;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort){
-                // stopped at user request
-                return false;
-            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (Exception e) {
             if (ser.fDOMErrorHandler != null) {
diff --git a/jaxws/.hgtags b/jaxws/.hgtags
index c13234c..30605fb 100644
--- a/jaxws/.hgtags
+++ b/jaxws/.hgtags
@@ -712,3 +712,25 @@
 730acb5d508e3cb852c2dae222717aa4593e6bb9 jdk8u151-b05
 2abea38c7ccedf1eabe9245ca9619cd006484a07 jdk8u151-b06
 4324e571f7fddf12b24fa8b9c4670ff1a3443b87 jdk8u151-b07
+1c0acbb50d5171b56c95b3abb2a92aee864beb35 jdk8u151-b08
+ea4b3e983ee708f9323d228044176e52526e9e13 jdk8u122-b00
+2e7f62568785adfe695e0c06f2e88c9d369c3b2c jdk8u122-b01
+b97e1b7f3c92b3e9f75e6aa590e0884c3c3ed33f jdk8u122-b02
+30b5b545a78c0c4fee837664f9c70ef6a2b4f0c1 jdk8u122-b03
+30b5b545a78c0c4fee837664f9c70ef6a2b4f0c1 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+a127c3268266ba1402343d94c7b19355c2dd1bd7 jdk8u122-b03
+c48501ec74b9b03870b473e5bde656fce230fc36 jdk8u122-b04
+f3b3163dda3c6da9339dba99a2ee74645ad2edc6 jdk8u132-b00
+55cb39946f2f163085ca80413b8cd3b3e196e533 jdk8u152-b00
+cf960a33b0e3093abcb48bfe304d471e3b092dc4 jdk8u152-b01
+0b4a7ce47e597b8d33e590857384a478c69a9e6f jdk8u152-b02
+98c698b1b09b6a31d5090a25aff8b7a6edb8d6ba jdk8u152-b03
+bcf7fc55388e4c9d771cd2ad38351a66bfcf27d9 jdk8u152-b04
+388cd26b19dbf7d3102653dd82c27027cd722066 jdk8u152-b05
+199a8d03dde0da505f04c87ff72aabdd7022eec5 jdk8u152-b06
+488a01f4ba30dc2eb7205a2800a37ade74cc3ad1 jdk8u152-b07
+86c8e64c0df3e7f18cc98e820b08dde3b67ffabb jdk8u152-b08
+bedae7043858b1e2cdef09d5dd68f4585320b5df jdk8u152-b09
+e2061fccf2caaab7c4dea3fb5b0a34d883821ce4 jdk8u152-b10
diff --git a/jaxws/ASSEMBLY_EXCEPTION b/jaxws/ASSEMBLY_EXCEPTION
index 8b7ac1d..065b8d9 100644
--- a/jaxws/ASSEMBLY_EXCEPTION
+++ b/jaxws/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Sun at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Sun gives you permission to link this
-    OpenJDK Code with certain code licensed by Sun as indicated at
+    As a special exception, Oracle gives you permission to link this
+    OpenJDK Code with certain code licensed by Oracle as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Sun.
+    governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Sun
-could not provide under GPL2 (or that Sun has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/transport/http/server/ServerMgr.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/transport/http/server/ServerMgr.java
index a16ec36..a579a3c 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/transport/http/server/ServerMgr.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/transport/http/server/ServerMgr.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -81,24 +81,37 @@
             synchronized(servers) {
                 state = servers.get(inetAddress);
                 if (state == null) {
-                    logger.fine("Creating new HTTP Server at "+inetAddress);
-                    // Creates server with default socket backlog
-                    server = HttpServer.create(inetAddress, 0);
-                    server.setExecutor(Executors.newCachedThreadPool());
-                    String path = url.toURI().getPath();
-                    logger.fine("Creating HTTP Context at = "+path);
-                    HttpContext context = server.createContext(path);
-                    server.start();
+                    final int finalPortNum = port;
+                    for (ServerState s: servers.values()) {
+                        if (s.getServer()
+                             .getAddress()
+                             .getPort() == finalPortNum) {
+                            state = s;
+                            break;
+                        }
+                    }
 
-                    // we have to get actual inetAddress from server, which can differ from the original in some cases.
-                    // e.g. A port number of zero will let the system pick up an ephemeral port in a bind operation,
-                    // or IP: 0.0.0.0 - which is used to monitor network traffic from any valid IP address
-                    inetAddress = server.getAddress();
+                    if (!inetAddress.getAddress().isAnyLocalAddress() ||
+                        state == null) {
+                        logger.fine("Creating new HTTP Server at "+inetAddress);
+                        // Creates server with default socket backlog
+                        server = HttpServer.create(inetAddress, 0);
+                        server.setExecutor(Executors.newCachedThreadPool());
+                        String path = url.toURI().getPath();
+                        logger.fine("Creating HTTP Context at = "+path);
+                        HttpContext context = server.createContext(path);
+                        server.start();
 
-                    logger.fine("HTTP server started = "+inetAddress);
-                    state = new ServerState(server, path);
-                    servers.put(inetAddress, state);
-                    return context;
+                        // we have to get actual inetAddress from server, which can differ from the original in some cases.
+                        // e.g. A port number of zero will let the system pick up an ephemeral port in a bind operation,
+                        // or IP: 0.0.0.0 - which is used to monitor network traffic from any valid IP address
+                        inetAddress = server.getAddress();
+
+                        logger.fine("HTTP server started = "+inetAddress);
+                        state = new ServerState(server, path);
+                        servers.put(inetAddress, state);
+                        return context;
+                    }
                 }
             }
             server = state.getServer();
diff --git a/jdk/.hgtags b/jdk/.hgtags
index f651dc4..a45fa82 100644
--- a/jdk/.hgtags
+++ b/jdk/.hgtags
@@ -720,3 +720,25 @@
 0efdf2c7a21464e5f3d89474ffdfe81db61031fd jdk8u151-b05
 c6c870e267de694bc85dc4af23a648824063f95b jdk8u151-b06
 84b0fbbfb8d664031a9f5283f79b13b98714cc7f jdk8u151-b07
+8fd79358682edc86abaac1c839486834410be74b jdk8u151-b08
+1442bc728814af451e2dd1a6719a64485d27e3a0 jdk8u122-b00
+f6030acfa5aec0e64d45adfac69b9e7e5c12bc74 jdk8u122-b01
+6b072c3a6db7ab06804c91aab77431799dfb5d47 jdk8u122-b02
+141beb4d854d213c1aefcc4406f09aa6b0809e43 jdk8u122-b03
+141beb4d854d213c1aefcc4406f09aa6b0809e43 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+d8c1eb38a23286991238eed87ab04c331700839b jdk8u122-b03
+774f11d707e0ff685c131cd625d96e1f58527990 jdk8u122-b04
+000711011f8ab7ab5ea88e02086c48181b42ab8f jdk8u132-b00
+f7be58eb30bc2cdea8a8e0fb254f52f176f5b57d jdk8u152-b00
+072df97b6e2af59f5e2433ae6b2dbecb16b03cd8 jdk8u152-b01
+dbf817e782805bffcb9a0d84f452349926329d62 jdk8u152-b02
+824988d089dde02e15f04c3b994115f78b9408c9 jdk8u152-b03
+4c95cacb8ec77cbda2ae1d4e070b39ec6b527769 jdk8u152-b04
+9c692f8574178a5505efe39cdff1ea92d4f95cbd jdk8u152-b05
+636043375508d667052c84691c55d4c633376dbe jdk8u152-b06
+83998ef9e0b96e1f5f9d4667575a81e8aa06b981 jdk8u152-b07
+e62e091df75fd92bf9d8c573f6224132c99b33ea jdk8u152-b08
+eb71140d49732a226340c0e0a2224c0215fc161a jdk8u152-b09
+db0d193ce92bb6bad9878a98b049afee46260513 jdk8u152-b10
diff --git a/jdk/ASSEMBLY_EXCEPTION b/jdk/ASSEMBLY_EXCEPTION
index 8b7ac1d..065b8d9 100644
--- a/jdk/ASSEMBLY_EXCEPTION
+++ b/jdk/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Sun at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Sun gives you permission to link this
-    OpenJDK Code with certain code licensed by Sun as indicated at
+    As a special exception, Oracle gives you permission to link this
+    OpenJDK Code with certain code licensed by Oracle as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Sun.
+    governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Sun
-could not provide under GPL2 (or that Sun has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/jdk/make/CopyFiles.gmk b/jdk/make/CopyFiles.gmk
index 9c7e7bc..bc070f0 100644
--- a/jdk/make/CopyFiles.gmk
+++ b/jdk/make/CopyFiles.gmk
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -357,18 +357,21 @@
 RESTRICTED_PKGS_SRC := $(JDK_TOPDIR)/src/closed/share/lib/security/restricted.pkgs
 RESTRICTED_PKGS := $(shell $(CAT) $(RESTRICTED_PKGS_SRC) | $(TR) "\n" " ")
 
+endif
+
 $(PROPS_DST): $(PROPS_SRC)
 	$(MKDIR) -p $(@D)
-	$(TOOL_ADDTORESTRICTEDPKGS) $^ $@.tmp $(RESTRICTED_PKGS)
+        ifndef OPENJDK
+	  $(TOOL_ADDTORESTRICTEDPKGS) $^ $@.tmp $(RESTRICTED_PKGS)
+        else
+	  $(CP) $^ $@.tmp
+        endif
+        ifeq ($(UNLIMITED_CRYPTO), true)
+	  $(TOOL_CRYPTOLEVEL) $@.tmp $@.tmp2 unlimited
+	  $(MV) $@.tmp2 $@.tmp
+        endif
 	$(MV) $@.tmp $@
 
-else
-
-$(PROPS_DST): $(PROPS_SRC)
-	$(call install-file)
-
-endif
-
 COPY_FILES += $(PROPS_DST)
 
 ##########################################################################################
diff --git a/jdk/make/CreateSecurityJars.gmk b/jdk/make/CreateSecurityJars.gmk
index d5b3b8e..da9cc20 100644
--- a/jdk/make/CreateSecurityJars.gmk
+++ b/jdk/make/CreateSecurityJars.gmk
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -178,7 +178,10 @@
 
 ##########################################################################################
 
-US_EXPORT_POLICY_JAR_DST := $(JDK_OUTPUTDIR)/lib/security/US_export_policy.jar
+US_EXPORT_POLICY_JAR_UNLIMITED_DST := \
+    $(JDK_OUTPUTDIR)/lib/security/policy/unlimited/US_export_policy.jar
+US_EXPORT_POLICY_JAR_LIMITED_DST := \
+    $(JDK_OUTPUTDIR)/lib/security/policy/limited/US_export_policy.jar
 
 ifneq ($(BUILD_CRYPTO), no)
 
@@ -220,27 +223,29 @@
 endif
 
 ifndef OPENJDK
-  ifeq ($(UNLIMITED_CRYPTO), true)
-    $(error No prebuilt unlimited crypto jars available)
-  endif
-  $(US_EXPORT_POLICY_JAR_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/US_export_policy.jar
+  $(US_EXPORT_POLICY_JAR_UNLIMITED_DST): \
+    $(JDK_TOPDIR)/make/closed/tools/crypto/jce/unlimited/US_export_policy.jar
+	$(ECHO) $(LOG_INFO) Copying prebuilt $(@F)
+	$(install-file)
+  $(US_EXPORT_POLICY_JAR_LIMITED_DST): \
+    $(JDK_TOPDIR)/make/closed/tools/crypto/jce/limited/US_export_policy.jar
 	$(ECHO) $(LOG_INFO) Copying prebuilt $(@F)
 	$(install-file)
 else
-  ifeq ($(UNLIMITED_CRYPTO), true)
-    $(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_UNLIMITED_UNSIGNED)
+  $(US_EXPORT_POLICY_JAR_UNLIMITED_DST): $(US_EXPORT_POLICY_JAR_UNLIMITED_UNSIGNED)
 	$(install-file)
-  else
-    $(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_LIMITED_UNSIGNED)
+  $(US_EXPORT_POLICY_JAR_LIMITED_DST): $(US_EXPORT_POLICY_JAR_LIMITED_UNSIGNED)
 	$(install-file)
   endif
-endif
 
-TARGETS += $(US_EXPORT_POLICY_JAR_DST)
+TARGETS += $(US_EXPORT_POLICY_JAR_UNLIMITED_DST) $(US_EXPORT_POLICY_JAR_LIMITED_DST)
 
 ##########################################################################################
 
-LOCAL_POLICY_JAR_DST := $(JDK_OUTPUTDIR)/lib/security/local_policy.jar
+LOCAL_POLICY_JAR_LIMITED_DST := \
+    $(JDK_OUTPUTDIR)/lib/security/policy/limited/local_policy.jar
+LOCAL_POLICY_JAR_UNLIMITED_DST := \
+    $(JDK_OUTPUTDIR)/lib/security/policy/unlimited/local_policy.jar
 
 ifneq ($(BUILD_CRYPTO), no)
 
@@ -293,20 +298,20 @@
 endif
 
 ifndef OPENJDK
-  $(LOCAL_POLICY_JAR_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/local_policy.jar
+  $(LOCAL_POLICY_JAR_UNLIMITED_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/unlimited/local_policy.jar
+	$(ECHO) $(LOG_INFO) Copying prebuilt $(@F)
+	$(install-file)
+  $(LOCAL_POLICY_JAR_LIMITED_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/limited/local_policy.jar
 	$(ECHO) $(LOG_INFO) Copying prebuilt $(@F)
 	$(install-file)
 else
-  ifeq ($(UNLIMITED_CRYPTO), true)
-    $(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_UNLIMITED_UNSIGNED)
+  $(LOCAL_POLICY_JAR_UNLIMITED_DST): $(LOCAL_POLICY_JAR_UNLIMITED_UNSIGNED)
 	$(install-file)
-  else
-    $(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_LIMITED_UNSIGNED)
+  $(LOCAL_POLICY_JAR_LIMITED_DST): $(LOCAL_POLICY_JAR_LIMITED_UNSIGNED)
 	$(install-file)
   endif
-endif
 
-TARGETS += $(LOCAL_POLICY_JAR_DST)
+TARGETS += $(LOCAL_POLICY_JAR_UNLIMITED_DST) $(LOCAL_POLICY_JAR_LIMITED_DST)
 
 ##########################################################################################
 
diff --git a/jdk/make/Tools.gmk b/jdk/make/Tools.gmk
index b45d5dc..afb9f86 100644
--- a/jdk/make/Tools.gmk
+++ b/jdk/make/Tools.gmk
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -132,7 +132,10 @@
     build.tools.deps.CheckDeps
 
 TOOL_ADDTORESTRICTEDPKGS=$(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
-    build.tools.addtorestrictedpkgs.AddToRestrictedPkgs
+    build.tools.customizesecurityfile.AddToRestrictedPkgs
+
+TOOL_CRYPTOLEVEL=$(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
+    build.tools.customizesecurityfile.CryptoLevel
 
 ##########################################################################################
 
diff --git a/jdk/make/lib/CoreLibraries.gmk b/jdk/make/lib/CoreLibraries.gmk
index 066a4bf..b8f1d67 100644
--- a/jdk/make/lib/CoreLibraries.gmk
+++ b/jdk/make/lib/CoreLibraries.gmk
@@ -23,17 +23,33 @@
 # questions.
 #
 
+# Include custom extensions if available.
+-include $(CUSTOM_MAKE_DIR)/lib/CoreLibraries.gmk
+
 WIN_VERIFY_LIB := $(JDK_OUTPUTDIR)/objs/libverify/verify.lib
 
 ##########################################################################################
 
-BUILD_LIBFDLIBM_OPTIMIZATION := HIGH
+BUILD_LIBFDLIBM_OPTIMIZATION := NONE
 
-ifneq ($(OPENJDK_TARGET_OS), solaris)
-  BUILD_LIBFDLIBM_OPTIMIZATION := NONE
+ifeq ($(OPENJDK_TARGET_OS), solaris)
+  BUILD_LIBFDLIBM_OPTIMIZATION := HIGH
+endif
+
+ifeq ($(OPENJDK_TARGET_OS), linux)
+  ifeq ($(OPENJDK_TARGET_CPU), ppc64)
+    BUILD_LIBFDLIBM_OPTIMIZATION := HIGH
+  else ifeq ($(OPENJDK_TARGET_CPU), ppc64le)
+    BUILD_LIBFDLIBM_OPTIMIZATION := HIGH
+  endif
 endif
 
 ifneq ($(OPENJDK_TARGET_OS), macosx)
+  # Unfortunately, '-ffp-contract' is only available since gcc 4.6. For ppc64le
+  # that's no problem since ppc64le support only appeared in gcc 4.8.3. But on
+  # ppc64 (big endian) we traditionally compiled with gcc 4.3 which only knows
+  # '-mno-fused-madd'. However, that's still not enough to get the float
+  # computations right - we additionally have to supply '-fno-strict-aliasing'.
   $(eval $(call SetupNativeCompilation,BUILD_LIBFDLIBM, \
       STATIC_LIBRARY := fdlibm, \
       OUTPUT_DIR := $(JDK_OUTPUTDIR)/objs, \
@@ -44,6 +60,8 @@
           -I$(JDK_TOPDIR)/src/share/native/java/lang/fdlibm/include, \
       CFLAGS_windows_debug := -DLOGGING, \
       CFLAGS_aix := -qfloat=nomaf, \
+      CFLAGS_linux_ppc64 := -mno-fused-madd -fno-strict-aliasing, \
+      CFLAGS_linux_ppc64le := -ffp-contract=off, \
       ARFLAGS := $(ARFLAGS), \
       OBJECT_DIR := $(JDK_OUTPUTDIR)/objs/libfdlibm, \
       DEBUG_SYMBOLS := $(DEBUG_ALL_BINARIES)))
@@ -114,7 +132,8 @@
 
 ##########################################################################################
 
-LIBJAVA_SRC_DIRS := $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/java/lang \
+# Allow a custom makefile to add extra src dirs
+LIBJAVA_SRC_DIRS += $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/java/lang \
     $(JDK_TOPDIR)/src/share/native/java/lang \
     $(JDK_TOPDIR)/src/share/native/java/lang/reflect \
     $(JDK_TOPDIR)/src/share/native/java/io \
@@ -140,6 +159,9 @@
       $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/io
 endif
 
+# Make it possible to override this variable
+LIBJAVA_MAPFILE ?= $(JDK_TOPDIR)/make/mapfiles/libjava/mapfile-vers
+
 LIBJAVA_CFLAGS := $(foreach dir, $(LIBJAVA_SRC_DIRS), -I$(dir)) \
     -I$(JDK_TOPDIR)/src/share/native/java/lang/fdlibm/include \
     -DARCHPROPNAME='"$(OPENJDK_TARGET_CPU_OSARCH)"'
@@ -193,7 +215,7 @@
     OPTIMIZATION := HIGH, \
     CFLAGS := $(CFLAGS_JDKLIB) \
         $(LIBJAVA_CFLAGS), \
-    MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjava/mapfile-vers, \
+    MAPFILE := $(LIBJAVA_MAPFILE), \
     LDFLAGS := $(LDFLAGS_JDKLIB) \
         $(call SET_SHARED_LIBRARY_ORIGIN), \
     LDFLAGS_SUFFIX_posix := -ljvm -lverify, \
diff --git a/jdk/make/mapfiles/libawt/mapfile-mawt-vers b/jdk/make/mapfiles/libawt/mapfile-mawt-vers
index 28ad353..94e66a7 100644
--- a/jdk/make/mapfiles/libawt/mapfile-mawt-vers
+++ b/jdk/make/mapfiles/libawt/mapfile-mawt-vers
@@ -201,6 +201,7 @@
                 Java_sun_print_CUPSPrinter_initIDs;
                 Java_sun_print_CUPSPrinter_getCupsServer;
                 Java_sun_print_CUPSPrinter_getCupsPort;
+                Java_sun_print_CUPSPrinter_getCupsDefaultPrinter;
                 Java_sun_print_CUPSPrinter_canConnect;
                 Java_sun_print_CUPSPrinter_getMedia;
                 Java_sun_print_CUPSPrinter_getPageSizes;
diff --git a/jdk/make/mapfiles/libawt_headless/mapfile-vers b/jdk/make/mapfiles/libawt_headless/mapfile-vers
index 44efc29..0ce2867 100644
--- a/jdk/make/mapfiles/libawt_headless/mapfile-vers
+++ b/jdk/make/mapfiles/libawt_headless/mapfile-vers
@@ -73,6 +73,7 @@
 		Java_sun_print_CUPSPrinter_initIDs;
 		Java_sun_print_CUPSPrinter_getCupsServer;
 		Java_sun_print_CUPSPrinter_getCupsPort;
+		Java_sun_print_CUPSPrinter_getCupsDefaultPrinter;
 		Java_sun_print_CUPSPrinter_canConnect;
 		Java_sun_print_CUPSPrinter_getMedia;
 		Java_sun_print_CUPSPrinter_getPageSizes;
diff --git a/jdk/make/mapfiles/libawt_xawt/mapfile-vers b/jdk/make/mapfiles/libawt_xawt/mapfile-vers
index d24a527..101c288 100644
--- a/jdk/make/mapfiles/libawt_xawt/mapfile-vers
+++ b/jdk/make/mapfiles/libawt_xawt/mapfile-vers
@@ -439,6 +439,7 @@
 	Java_sun_print_CUPSPrinter_initIDs;
 	Java_sun_print_CUPSPrinter_getCupsServer;
 	Java_sun_print_CUPSPrinter_getCupsPort;
+	Java_sun_print_CUPSPrinter_getCupsDefaultPrinter;
 	Java_sun_print_CUPSPrinter_canConnect;
 	Java_sun_print_CUPSPrinter_getMedia;
 	Java_sun_print_CUPSPrinter_getPageSizes;
diff --git a/jdk/make/mapfiles/libjava/mapfile-vers b/jdk/make/mapfiles/libjava/mapfile-vers
index 1b371a2..0d3e9e0 100644
--- a/jdk/make/mapfiles/libjava/mapfile-vers
+++ b/jdk/make/mapfiles/libjava/mapfile-vers
@@ -76,13 +76,13 @@
 
 		Java_java_io_FileDescriptor_initIDs;
 		Java_java_io_FileDescriptor_sync;
-		Java_java_io_FileInputStream_available;
+		Java_java_io_FileInputStream_available0;
 		Java_java_io_FileInputStream_close0;
 		Java_java_io_FileInputStream_initIDs;
 		Java_java_io_FileInputStream_open0;
 		Java_java_io_FileInputStream_read0;
 		Java_java_io_FileInputStream_readBytes;
-		Java_java_io_FileInputStream_skip;
+		Java_java_io_FileInputStream_skip0;
 		Java_java_io_FileOutputStream_close0;
 		Java_java_io_FileOutputStream_initIDs;
 		Java_java_io_FileOutputStream_open0;
diff --git a/jdk/make/mapfiles/libjava/reorder-sparc b/jdk/make/mapfiles/libjava/reorder-sparc
index d100376..96f8e73 100644
--- a/jdk/make/mapfiles/libjava/reorder-sparc
+++ b/jdk/make/mapfiles/libjava/reorder-sparc
@@ -48,7 +48,7 @@
 text: .text%fileOpen;
 text: .text%Java_java_io_FileInputStream_readBytes;
 text: .text%readBytes;
-text: .text%Java_java_io_FileInputStream_available;
+text: .text%Java_java_io_FileInputStream_available0;
 text: .text%Java_java_io_FileInputStream_close0;
 text: .text%Java_java_lang_System_mapLibraryName;
 text: .text%Java_java_io_UnixFileSystem_getBooleanAttributes0;
diff --git a/jdk/make/mapfiles/libjava/reorder-sparcv9 b/jdk/make/mapfiles/libjava/reorder-sparcv9
index 2609711..c10007b 100644
--- a/jdk/make/mapfiles/libjava/reorder-sparcv9
+++ b/jdk/make/mapfiles/libjava/reorder-sparcv9
@@ -51,7 +51,7 @@
 text: .text%fileOpen;
 text: .text%Java_java_io_FileInputStream_readBytes;
 text: .text%readBytes;
-text: .text%Java_java_io_FileInputStream_available;
+text: .text%Java_java_io_FileInputStream_available0;
 text: .text%Java_java_io_FileInputStream_close0;
 text: .text%Java_java_lang_Compiler_registerNatives;
 text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2;
diff --git a/jdk/make/mapfiles/libjava/reorder-x86 b/jdk/make/mapfiles/libjava/reorder-x86
index b8ea2d4..e0566b3 100644
--- a/jdk/make/mapfiles/libjava/reorder-x86
+++ b/jdk/make/mapfiles/libjava/reorder-x86
@@ -78,7 +78,7 @@
 text: .text%JNU_GetEnv;
 text: .text%Java_java_io_UnixFileSystem_checkAccess;
 text: .text%Java_sun_reflect_NativeMethodAccessorImpl_invoke0;
-text: .text%Java_java_io_FileInputStream_available;
+text: .text%Java_java_io_FileInputStream_available0;
 text: .text%Java_java_lang_reflect_Array_newArray;
 text: .text%Java_java_lang_Throwable_getStackTraceDepth;
 text: .text%Java_java_lang_Throwable_getStackTraceElement;
diff --git a/jdk/make/mapfiles/libnet/mapfile-vers b/jdk/make/mapfiles/libnet/mapfile-vers
index 0e432d3..a37668a 100644
--- a/jdk/make/mapfiles/libnet/mapfile-vers
+++ b/jdk/make/mapfiles/libnet/mapfile-vers
@@ -112,6 +112,7 @@
 		NET_EnableFastTcpLoopback;
 		NET_ThrowNew;
                 ipv6_available;
+                initInetAddressIDs;
 
 	local:
 		*;
diff --git a/jdk/make/profile-includes.txt b/jdk/make/profile-includes.txt
index 3014a71..e6de98e 100644
--- a/jdk/make/profile-includes.txt
+++ b/jdk/make/profile-includes.txt
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -183,13 +183,15 @@
     net.properties \
     resources.jar \
     rt.jar \
-    security/US_export_policy.jar \
+    security/policy/limited/US_export_policy.jar \
+    security/policy/unlimited/US_export_policy.jar \
     security/blacklist \
     security/blacklisted.certs \
     security/cacerts \
     security/java.policy \
     security/java.security \
-    security/local_policy.jar \
+    security/policy/limited/local_policy.jar \
+    security/policy/unlimited/local_policy.jar \
     security/trusted.libraries \
     tzdb.dat
 
@@ -218,8 +220,10 @@
     jsse.jar \
     resources.jar \
     rt.jar \
-    security/US_export_policy.jar \
-    security/local_policy.jar
+    security/policy/limited/US_export_policy.jar \
+    security/policy/unlimited/US_export_policy.jar \
+    security/policy/limited/local_policy.jar \
+    security/policy/unlimited/local_policy.jar
 
 
 PROFILE_2_JRE_BIN_FILES := \
diff --git a/jdk/make/profile-rtjar-includes.txt b/jdk/make/profile-rtjar-includes.txt
index bda322f..84c6a0f 100644
--- a/jdk/make/profile-rtjar-includes.txt
+++ b/jdk/make/profile-rtjar-includes.txt
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -119,6 +119,7 @@
     com/sun/tracing \
     jdk/management \
     jdk/internal/cmm \
+    jdk/internal/instrumentation \
     java/lang/instrument \
     java/lang/management \
     java/security/acl \
@@ -207,7 +208,6 @@
     javax/xml/bind \
     javax/xml/soap \
     javax/xml/ws \
-    jdk/internal/instrumentation \
     jdk/management/resource \
     org/omg \
     sun/applet \
diff --git a/jdk/make/src/classes/build/tools/addtorestrictedpkgs/AddToRestrictedPkgs.java b/jdk/make/src/classes/build/tools/customizesecurityfile/AddToRestrictedPkgs.java
similarity index 96%
rename from jdk/make/src/classes/build/tools/addtorestrictedpkgs/AddToRestrictedPkgs.java
rename to jdk/make/src/classes/build/tools/customizesecurityfile/AddToRestrictedPkgs.java
index ee9deb4..1211f46 100644
--- a/jdk/make/src/classes/build/tools/addtorestrictedpkgs/AddToRestrictedPkgs.java
+++ b/jdk/make/src/classes/build/tools/customizesecurityfile/AddToRestrictedPkgs.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
  * questions.
  */
 
-package build.tools.addtorestrictedpkgs;
+package build.tools.customizesecurityfile;
 
 import java.io.*;
 
diff --git a/jdk/make/src/classes/build/tools/customizesecurityfile/CryptoLevel.java b/jdk/make/src/classes/build/tools/customizesecurityfile/CryptoLevel.java
new file mode 100644
index 0000000..5ad47e9
--- /dev/null
+++ b/jdk/make/src/classes/build/tools/customizesecurityfile/CryptoLevel.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  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 build.tools.customizesecurityfile;
+
+import java.io.*;
+
+/**
+ * Alters the crypto.policy security property
+ * if --enable-unlimited-crypto is enabled.
+ */
+public class CryptoLevel {
+
+    private static final String PROP_NAME = "crypto.policy";
+
+    public static void main(String[] args) throws Exception {
+        boolean fileModified = false;
+
+        if (args.length < 3) {
+            System.err.println("Usage: java CryptoLevel" +
+                               "[input java.security file name] " +
+                               "[output java.security file name] " +
+                               "[unlimited|limited]");
+            System.exit(1);
+        }
+        if (!args[2].equals("unlimited") && !args[2].equals("limited")) {
+            System.err.println("CryptoLevel error: Unexpected " +
+                "input: " + args[2]);
+            System.exit(1);
+        }
+
+        try (FileReader fr = new FileReader(args[0]);
+             BufferedReader br = new BufferedReader(fr);
+             FileWriter fw = new FileWriter(args[1]);
+             BufferedWriter bw = new BufferedWriter(fw))
+        {
+            // parse the file line-by-line, looking for crypto.policy
+            String line = br.readLine();
+            while (line != null) {
+                if (line.startsWith('#' + PROP_NAME) ||
+                    line.startsWith(PROP_NAME)) {
+                    writeLine(bw, PROP_NAME + "=" + args[2]);
+                    fileModified = true;
+                } else {
+                    writeLine(bw, line);
+                }
+                line = br.readLine();
+            }
+            if (!fileModified) {
+                //no previous setting seen. Insert at end
+                writeLine(bw, PROP_NAME + "=" + args[2]);
+            }
+            bw.flush();
+        }
+    }
+
+    private static void writeLine(BufferedWriter bw, String line)
+        throws IOException
+    {
+        bw.write(line);
+        bw.newLine();
+    }
+}
diff --git a/jdk/src/macosx/bin/java_md_macosx.c b/jdk/src/macosx/bin/java_md_macosx.c
index 87e632b..eb20be7 100644
--- a/jdk/src/macosx/bin/java_md_macosx.c
+++ b/jdk/src/macosx/bin/java_md_macosx.c
@@ -1004,32 +1004,6 @@
     setenv(envVar, "1", 1);
 }
 
-/* This class is made for performSelectorOnMainThread when java main
- * should be launched on main thread.
- * We cannot use dispatch_sync here, because it blocks the main dispatch queue
- * which is used inside Cocoa
- */
-@interface JavaLaunchHelper : NSObject {
-    int _returnValue;
-}
-- (void) launchJava:(NSValue*)argsValue;
-- (int) getReturnValue;
-@end
-
-@implementation JavaLaunchHelper
-
-- (void) launchJava:(NSValue*)argsValue
-{
-    _returnValue = JavaMain([argsValue pointerValue]);
-}
-
-- (int) getReturnValue
-{
-    return _returnValue;
-}
-
-@end
-
 // MacOSX we may continue in the same thread
 int
 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
@@ -1039,20 +1013,26 @@
         JLI_TraceLauncher("In same thread\n");
         // need to block this thread against the main thread
         // so signals get caught correctly
-        JavaMainArgs args;
-        args.argc = argc;
-        args.argv = argv;
-        args.mode = mode;
-        args.what = what;
-        args.ifn  = *ifn;
-        int rslt;
+        __block int rslt = 0;
         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
         {
-            JavaLaunchHelper* launcher = [[[JavaLaunchHelper alloc] init] autorelease];
-            [launcher performSelectorOnMainThread:@selector(launchJava:)
-                                       withObject:[NSValue valueWithPointer:(void*)&args]
-                                    waitUntilDone:YES];
-            rslt = [launcher getReturnValue];
+            NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock: ^{
+                JavaMainArgs args;
+                args.argc = argc;
+                args.argv = argv;
+                args.mode = mode;
+                args.what = what;
+                args.ifn  = *ifn;
+                rslt = JavaMain(&args);
+            }];
+
+            /*
+             * We cannot use dispatch_sync here, because it blocks the main dispatch queue.
+             * Using the main NSRunLoop allows the dispatch queue to run properly once
+             * SWT (or whatever toolkit this is needed for) kicks off it's own NSRunLoop
+             * and starts running.
+             */
+            [op performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];
         }
         [pool drain];
         return rslt;
diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaProgressBarUI.java b/jdk/src/macosx/classes/com/apple/laf/AquaProgressBarUI.java
index 1ac16c3..80a5e36 100644
--- a/jdk/src/macosx/classes/com/apple/laf/AquaProgressBarUI.java
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaProgressBarUI.java
@@ -124,7 +124,9 @@
             if (!progressBar.isIndeterminate()) return;
             stopAnimationTimer();
             // start the animation thread
-            startAnimationTimer();
+            if (progressBar.isDisplayable()) {
+              startAnimationTimer();
+            }
         }
 
         if ("JProgressBar.style".equals(prop)) {
@@ -141,7 +143,9 @@
 
     public void ancestorAdded(final AncestorEvent e) {
         if (!progressBar.isIndeterminate()) return;
-        startAnimationTimer();
+        if (progressBar.isDisplayable()) {
+          startAnimationTimer();
+        }
     }
 
     public void ancestorMoved(final AncestorEvent e) { }
diff --git a/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java
index 8739340..bc8c0cc 100644
--- a/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java
+++ b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java
@@ -109,6 +109,7 @@
         final Component[] items = fInvoker.getMenuComponents();
         if (needsUpdate(items, childHashArray)) {
             removeAll();
+            fItems.clear();
             if (count <= 0) return;
 
             childHashArray = new int[count];
@@ -232,7 +233,7 @@
         synchronized (getTreeLock()) {
             super.addNotify();
             if (fModelPtr == 0) {
-                fInvoker.addContainerListener(this);
+                fInvoker.getPopupMenu().addContainerListener(this);
                 fInvoker.addComponentListener(this);
                 fPropertyListener = new ScreenMenuPropertyListener(this);
                 fInvoker.addPropertyChangeListener(fPropertyListener);
@@ -266,7 +267,7 @@
             if (fModelPtr != 0) {
                 removeMenuListeners(fModelPtr);
                 fModelPtr = 0;
-                fInvoker.removeContainerListener(this);
+                fInvoker.getPopupMenu().removeContainerListener(this);
                 fInvoker.removeComponentListener(this);
                 fInvoker.removePropertyChangeListener(fPropertyListener);
             }
@@ -287,11 +288,10 @@
     @Override
     public void componentRemoved(final ContainerEvent e) {
         final Component child = e.getChild();
-        final MenuItem sm = fItems.get(child);
+        final MenuItem sm = fItems.remove(child);
         if (sm == null) return;
 
         remove(sm);
-        fItems.remove(sm);
     }
 
     /**
diff --git a/jdk/src/macosx/classes/sun/font/CCharToGlyphMapper.java b/jdk/src/macosx/classes/sun/font/CCharToGlyphMapper.java
index d2f9a54..5a2cf76 100644
--- a/jdk/src/macosx/classes/sun/font/CCharToGlyphMapper.java
+++ b/jdk/src/macosx/classes/sun/font/CCharToGlyphMapper.java
@@ -75,37 +75,9 @@
                 }
             }
 
-            if (code < 0x0590) {
+            if (code < FontUtilities.MIN_LAYOUT_CHARCODE) {
                 continue;
-            } else if (code <= 0x05ff) {
-                // Hebrew 0x0590->0x05ff
-                return true;
-            } else if (code >= 0x0600 && code <= 0x06ff) {
-                // Arabic
-                return true;
-            } else if (code >= 0x0900 && code <= 0x0d7f) {
-                // if Indic, assume shaping for conjuncts, reordering:
-                // 0900 - 097F Devanagari
-                // 0980 - 09FF Bengali
-                // 0A00 - 0A7F Gurmukhi
-                // 0A80 - 0AFF Gujarati
-                // 0B00 - 0B7F Oriya
-                // 0B80 - 0BFF Tamil
-                // 0C00 - 0C7F Telugu
-                // 0C80 - 0CFF Kannada
-                // 0D00 - 0D7F Malayalam
-                return true;
-            } else if (code >= 0x0e00 && code <= 0x0e7f) {
-                // if Thai, assume shaping for vowel, tone marks
-                return true;
-            } else if (code >= 0x200c && code <= 0x200d) {
-                // zwj or zwnj
-                return true;
-            } else if (code >= 0x202a && code <= 0x202e) {
-                // directional control
-                return true;
-            } else if (code >= 0x206a && code <= 0x206f) {
-                // directional control
+            } else if (FontUtilities.isComplexCharCode(code)) {
                 return true;
             } else if (code >= 0x10000) {
                 i += 1; // Empty glyph slot after surrogate
diff --git a/jdk/src/macosx/classes/sun/java2d/OSXSurfaceData.java b/jdk/src/macosx/classes/sun/java2d/OSXSurfaceData.java
index 2592b65..59b0d7e 100644
--- a/jdk/src/macosx/classes/sun/java2d/OSXSurfaceData.java
+++ b/jdk/src/macosx/classes/sun/java2d/OSXSurfaceData.java
@@ -74,8 +74,13 @@
         this.fGraphicsStatesInt = this.fGraphicsStates.asIntBuffer();
         this.fGraphicsStatesFloat = this.fGraphicsStates.asFloatBuffer();
         this.fGraphicsStatesLong = this.fGraphicsStates.asLongBuffer();
-        this.fGraphicsStatesObject = new Object[6]; // clip coordinates + clip types + texture paint image + stroke dash
-                                                    // array + font + font paint
+        this.fGraphicsStatesObject = new Object[8]; // clip coordinates +
+                                                    // clip types +
+                                                    // texture paint image +
+                                                    // stroke dash array +
+                                                    // font + font paint +
+                                                    // linear/radial gradient color +
+                                                    // linear/radial gradient fractions
 
         // NOTE: All access to the DrawingQueue comes through this OSXSurfaceData instance. Therefore
         // every instance method of OSXSurfaceData that accesses the fDrawingQueue is synchronized.
@@ -292,10 +297,10 @@
     @Native static final int kHintsFractionalMetricsIndex = 46;
     @Native static final int kHintsRenderingIndex = 47;
     @Native static final int kHintsInterpolationIndex = 48;
-    // live resizing info
-    @Native static final int kCanDrawDuringLiveResizeIndex = 49;
+    //gradient info
+    @Native static final int kRadiusIndex = 49;
 
-    @Native static final int kSizeOfParameters = kCanDrawDuringLiveResizeIndex + 1;
+    @Native static final int kSizeOfParameters = kRadiusIndex + 1;
 
     // for objectParameters
     @Native static final int kClipCoordinatesIndex = 0;
@@ -304,6 +309,8 @@
     @Native static final int kStrokeDashArrayIndex = 3;
     @Native static final int kFontIndex = 4;
     @Native static final int kFontPaintIndex = 5;
+    @Native static final int kColorArrayIndex = 6;
+    @Native static final int kFractionsArrayIndex = 7;
 
     // possible state changes
     @Native static final int kBoundsChangedBit = 1 << 0;
@@ -329,6 +336,8 @@
     @Native static final int kColorSystem = 1;
     @Native static final int kColorGradient = 2;
     @Native static final int kColorTexture = 3;
+    @Native static final int kColorLinearGradient = 4;
+    @Native static final int kColorRadialGradient = 5;
 
     // possible gradient color states
     @Native static final int kColorNonCyclic = 0;
@@ -522,6 +531,28 @@
     int lastPaintIndex = 0;
     BufferedImage texturePaintImage = null;
 
+    void setGradientViaRasterPath(SunGraphics2D sg2d) {
+        if ((this.fGraphicsStatesInt.get(kColorStateIndex) != kColorTexture) || (lastPaint != sg2d.paint) || ((this.fChangeFlag & kBoundsChangedBit) != 0)) {
+            PaintContext context = sg2d.paint.createContext(sg2d.getDeviceColorModel(), userBounds, userBounds, sIdentityMatrix, sg2d.getRenderingHints());
+            WritableRaster raster = (WritableRaster) (context.getRaster(userBounds.x, userBounds.y, userBounds.width, userBounds.height));
+            ColorModel cm = context.getColorModel();
+            texturePaintImage = new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null);
+
+            this.fGraphicsStatesInt.put(kColorStateIndex, kColorTexture);
+            this.fGraphicsStatesInt.put(kColorWidthIndex, texturePaintImage.getWidth());
+            this.fGraphicsStatesInt.put(kColorHeightIndex, texturePaintImage.getHeight());
+            this.fGraphicsStatesFloat.put(kColortxIndex, (float) userBounds.getX());
+            this.fGraphicsStatesFloat.put(kColortyIndex, (float) userBounds.getY());
+            this.fGraphicsStatesFloat.put(kColorsxIndex, 1.0f);
+            this.fGraphicsStatesFloat.put(kColorsyIndex, 1.0f);
+            this.fGraphicsStatesObject[kTextureImageIndex] = OSXOffScreenSurfaceData.createNewSurface(texturePaintImage);
+
+            this.fChangeFlag = (this.fChangeFlag | kColorChangedBit);
+        } else {
+            this.fChangeFlag = (this.fChangeFlag & kColorNotChangedBit);
+        }
+    }
+
     void setupPaint(SunGraphics2D sg2d, int x, int y, int w, int h) {
         if (sg2d.paint instanceof SystemColor) {
             SystemColor color = (SystemColor) sg2d.paint;
@@ -567,12 +598,79 @@
             } else {
                 this.fChangeFlag = (this.fChangeFlag & kColorNotChangedBit);
             }
+        } else if (sg2d.paint instanceof LinearGradientPaint) {
+            LinearGradientPaint color = (LinearGradientPaint) sg2d.paint;
+            if (color.getCycleMethod() == LinearGradientPaint.CycleMethod.NO_CYCLE) {
+                if ((this.fGraphicsStatesInt.get(kColorStateIndex) != kColorLinearGradient) || (lastPaint != sg2d.paint)) {
+
+                    this.fGraphicsStatesInt.put(kColorStateIndex, kColorLinearGradient);
+                    int numColor = color.getColors().length;
+                    int colorArray[] = new int[numColor];
+                    for (int i = 0; i < numColor; i++) {
+                        colorArray[i] = color.getColors()[i].getRGB();
+                    }
+                    this.fGraphicsStatesObject[kColorArrayIndex] = colorArray;
+
+                    int numFractions = color.getFractions().length;
+                    float fractionArray[] = new float[numFractions];
+                    for (int i = 0; i < numFractions; i++) {
+                        fractionArray[i] = color.getFractions()[i];
+                    }
+                    this.fGraphicsStatesObject[kFractionsArrayIndex] = color.getFractions();
+                    Point2D p = color.getStartPoint();
+                    this.fGraphicsStatesFloat.put(kColorx1Index, (float) p.getX());
+                    this.fGraphicsStatesFloat.put(kColory1Index, (float) p.getY());
+                    p = color.getEndPoint();
+                    this.fGraphicsStatesFloat.put(kColorx2Index, (float) p.getX());
+                    this.fGraphicsStatesFloat.put(kColory2Index, (float) p.getY());
+
+                    this.fChangeFlag = (this.fChangeFlag | kColorChangedBit);
+                } else {
+                    this.fChangeFlag = (this.fChangeFlag & kColorNotChangedBit);
+                }
+            } else {
+                setGradientViaRasterPath(sg2d);
+            }
+        } else if (sg2d.paint instanceof RadialGradientPaint) {
+            RadialGradientPaint color = (RadialGradientPaint) sg2d.paint;
+            if (color.getCycleMethod() == RadialGradientPaint.CycleMethod.NO_CYCLE) {
+                if ((this.fGraphicsStatesInt.get(kColorStateIndex) != kColorRadialGradient) || (lastPaint != sg2d.paint)) {
+
+                    this.fGraphicsStatesInt.put(kColorStateIndex, kColorRadialGradient);
+                    int numColor = color.getColors().length;
+                    int colorArray[] = new int[numColor];
+                    for (int i = 0; i < numColor; i++) {
+                        colorArray[i] = color.getColors()[i].getRGB();
+                    }
+                    this.fGraphicsStatesObject[kColorArrayIndex] = colorArray;
+
+                    int numStops = color.getFractions().length;
+                    float stopsArray[] = new float[numStops];
+                    for (int i = 0; i < numStops; i++) {
+                        stopsArray[i] = color.getFractions()[i];
+                    }
+                    this.fGraphicsStatesObject[kFractionsArrayIndex] = color.getFractions();
+                    Point2D p = color.getFocusPoint();
+                    this.fGraphicsStatesFloat.put(kColorx1Index, (float) p.getX());
+                    this.fGraphicsStatesFloat.put(kColory1Index, (float) p.getY());
+                    p = color.getCenterPoint();
+                    this.fGraphicsStatesFloat.put(kColorx2Index, (float) p.getX());
+                    this.fGraphicsStatesFloat.put(kColory2Index, (float) p.getY());
+                    this.fGraphicsStatesFloat.put(kRadiusIndex,     color.getRadius());
+
+                    this.fChangeFlag = (this.fChangeFlag | kColorChangedBit);
+                } else {
+                    this.fChangeFlag = (this.fChangeFlag & kColorNotChangedBit);
+                }
+            } else {
+                setGradientViaRasterPath(sg2d);
+            }
         } else if (sg2d.paint instanceof TexturePaint) {
             if ((this.fGraphicsStatesInt.get(kColorStateIndex) != kColorTexture) || (lastPaint != sg2d.paint)) {
                 TexturePaint color = (TexturePaint) sg2d.paint;
                 this.fGraphicsStatesInt.put(kColorStateIndex, kColorTexture);
                 texturePaintImage = color.getImage();
-                SurfaceData textureSurfaceData = BufImgSurfaceData.createData(texturePaintImage);
+                SurfaceData textureSurfaceData = OSXOffScreenSurfaceData.createNewSurface(texturePaintImage);
                 this.fGraphicsStatesInt.put(kColorWidthIndex, texturePaintImage.getWidth());
                 this.fGraphicsStatesInt.put(kColorHeightIndex, texturePaintImage.getHeight());
                 Rectangle2D anchor = color.getAnchorRect();
@@ -587,27 +685,7 @@
                 this.fChangeFlag = (this.fChangeFlag & kColorNotChangedBit);
             }
         } else {
-            if ((this.fGraphicsStatesInt.get(kColorStateIndex) != kColorTexture) || (lastPaint != sg2d.paint) || ((this.fChangeFlag & kBoundsChangedBit) != 0)) {
-                PaintContext context = sg2d.paint.createContext(sg2d.getDeviceColorModel(), userBounds, userBounds, sIdentityMatrix, sg2d.getRenderingHints());
-                WritableRaster raster = (WritableRaster) (context.getRaster(userBounds.x, userBounds.y, userBounds.width, userBounds.height));
-                ColorModel cm = context.getColorModel();
-                texturePaintImage = new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null);
-
-                this.fGraphicsStatesInt.put(kColorStateIndex, kColorTexture);
-                this.fGraphicsStatesInt.put(kColorWidthIndex, texturePaintImage.getWidth());
-                this.fGraphicsStatesInt.put(kColorHeightIndex, texturePaintImage.getHeight());
-                this.fGraphicsStatesFloat.put(kColortxIndex, (float) userBounds.getX());
-                this.fGraphicsStatesFloat.put(kColortyIndex, (float) userBounds.getY());
-                this.fGraphicsStatesFloat.put(kColorsxIndex, 1.0f);
-                this.fGraphicsStatesFloat.put(kColorsyIndex, 1.0f);
-                this.fGraphicsStatesObject[kTextureImageIndex] = sun.awt.image.BufImgSurfaceData.createData(texturePaintImage);
-
-                context.dispose();
-
-                this.fChangeFlag = (this.fChangeFlag | kColorChangedBit);
-            } else {
-                this.fChangeFlag = (this.fChangeFlag & kColorNotChangedBit);
-            }
+            setGradientViaRasterPath(sg2d);
         }
         lastPaint = sg2d.paint;
     }
diff --git a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java
index 33511fb..db5a4f5 100644
--- a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java
+++ b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java
@@ -183,6 +183,7 @@
 
         updateAlwaysOnTopState();
         updateMinimumSize();
+        updateFocusableWindowState();
 
         final Shape shape = getTarget().getShape();
         if (shape != null) {
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java
index 59d0a74..00879ac 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java
@@ -71,8 +71,20 @@
     }
 
     public void propertyChange(final PropertyChangeEvent evt) {
-        if (evt.getNewValue() == null) return;
-        focusChanged();
+        Object newValue = evt.getNewValue();
+        if (newValue == null) return;
+        // Don't post focus on things that don't matter, i.e. alert, colorchooser,
+        // desktoppane, dialog, directorypane, filechooser, filler, fontchoose,
+        // frame, glasspane, layeredpane, optionpane, panel, rootpane, separator,
+        // tooltip, viewport, window.
+        // List taken from initializeRoles() in JavaComponentUtilities.m.
+        if (newValue instanceof Accessible) {
+            AccessibleContext nvAC = ((Accessible) newValue).getAccessibleContext();
+            AccessibleRole nvRole = nvAC.getAccessibleRole();
+            if (!ignoredRoles.contains(roleKey(nvRole))) {
+                focusChanged();
+            }
+        }
     }
 
     private native void focusChanged();
@@ -84,6 +96,15 @@
         return null;
     }
 
+    static <T> T invokeAndWait(final Callable<T> callable, final Component c, final T defValue) {
+        T value = null;
+        try {
+            value = LWCToolkit.invokeAndWait(callable, c);
+        } catch (final Exception e) { e.printStackTrace(); }
+
+        return value != null ? value : defValue;
+    }
+
     static void invokeLater(final Runnable runnable, final Component c) {
         try {
             LWCToolkit.invokeLater(runnable, c);
@@ -179,7 +200,7 @@
 
                 return new Boolean(as.isAccessibleChildSelected(index));
             }
-        }, c);
+        }, c, false);
     }
 
     public static AccessibleStateSet getAccessibleStateSet(final AccessibleContext ac, final Component c) {
@@ -201,7 +222,7 @@
                 if (ass == null) return null;
                 return ass.contains(as);
             }
-        }, c);
+        }, c, false);
     }
 
     static Field getAccessibleBundleKeyFieldWithReflection() {
@@ -267,7 +288,7 @@
             public Integer call() throws Exception {
                 return at.getCharCount();
             }
-        }, c);
+        }, c, 0);
     }
 
     // Accessibility Threadsafety for JavaComponentAccessibility.m
@@ -284,7 +305,7 @@
     }
 
     public static int getAccessibleIndexInParent(final Accessible a, final Component c) {
-        if (a == null) return 0;
+        if (a == null) return -1;
 
         return invokeAndWait(new Callable<Integer>() {
             public Integer call() throws Exception {
@@ -292,7 +313,7 @@
                 if (ac == null) return null;
                 return ac.getAccessibleIndexInParent();
             }
-        }, c);
+        }, c, -1);
     }
 
     public static AccessibleComponent getAccessibleComponent(final Accessible a, final Component c) {
@@ -388,7 +409,7 @@
 
                 return aComp.isFocusTraversable();
             }
-        }, c);
+        }, c, false);
     }
 
     public static Accessible accessibilityHitTest(final Container parent, final float hitPointX, final float hitPointY) {
@@ -447,7 +468,7 @@
 
                 return aComp.isEnabled();
             }
-        }, c);
+        }, c, false);
     }
 
     // KCH - can we make this a postEvent instead?
@@ -467,6 +488,24 @@
         }, c);
     }
 
+    public static void requestSelection(final Accessible a, final Component c) {
+        if (a == null) return;
+        invokeLater(new Runnable() {
+            public void run() {
+                AccessibleContext ac = a.getAccessibleContext();
+                if (ac == null) return;
+                int i = ac.getAccessibleIndexInParent();
+                if (i == -1) return;
+                Accessible parent = ac.getAccessibleParent();
+                AccessibleContext pac = parent.getAccessibleContext();
+                if (pac == null) return;
+                AccessibleSelection as = pac.getAccessibleSelection();
+                if (as == null) return;
+                as.addAccessibleSelection(i);
+            }
+        }, c);
+    }
+
     public static Number getMaximumAccessibleValue(final Accessible a, final Component c) {
         if (a == null) return null;
 
@@ -571,9 +610,57 @@
         if (a == null) return null;
         return invokeAndWait(new Callable<Object[]>() {
             public Object[] call() throws Exception {
-                final ArrayList<Object> childrenAndRoles = new ArrayList<Object>();
+                ArrayList<Object> childrenAndRoles = new ArrayList<Object>();
                 _addChildren(a, whichChildren, allowIgnored, childrenAndRoles);
 
+                /* In the case of fetching a selection, need to check to see if
+                 * the active descendant is at the beginning of the list.  If it
+                 * is not it needs to be moved to the beginning of the list so
+                 * VoiceOver will annouce it correctly.  The list returned
+                 * from Java is always in order from top to bottom, but when shift
+                 * selecting downward (extending the list) or multi-selecting using
+                 * the VO keys control+option+command+return the active descendant
+                 * is not at the top of the list in the shift select down case and
+                 * may not be in the multi select case.
+                 */
+                if (whichChildren == JAVA_AX_SELECTED_CHILDREN) {
+                    if (!childrenAndRoles.isEmpty()) {
+                        AccessibleContext activeDescendantAC =
+                            CAccessible.getActiveDescendant(a);
+                        if (activeDescendantAC != null) {
+                            String activeDescendantName =
+                                activeDescendantAC.getAccessibleName();
+                            AccessibleRole activeDescendantRole =
+                                activeDescendantAC.getAccessibleRole();
+                            // Move active descendant to front of list.
+                            // List contains pairs of each selected item's
+                            // Accessible and AccessibleRole.
+                            ArrayList<Object> newArray  = new ArrayList<Object>();
+                            int count = childrenAndRoles.size();
+                            Accessible currentAccessible = null;
+                            AccessibleContext currentAC = null;
+                            String currentName = null;
+                            AccessibleRole currentRole = null;
+                            for (int i = 0; i < count; i+=2) {
+                                // Is this the active descendant?
+                                currentAccessible = (Accessible)childrenAndRoles.get(i);
+                                currentAC = currentAccessible.getAccessibleContext();
+                                currentName = currentAC.getAccessibleName();
+                                currentRole = (AccessibleRole)childrenAndRoles.get(i+1);
+                                if ( currentName.equals(activeDescendantName) &&
+                                     currentRole.equals(activeDescendantRole) ) {
+                                    newArray.add(0, currentAccessible);
+                                    newArray.add(1, currentRole);
+                                } else {
+                                    newArray.add(currentAccessible);
+                                    newArray.add(currentRole);
+                                }
+                            }
+                            childrenAndRoles = newArray;
+                        }
+                    }
+                }
+
                 if ((whichChildren < 0) || (whichChildren * 2 >= childrenAndRoles.size())) {
                     return childrenAndRoles.toArray();
                 }
@@ -627,9 +714,15 @@
             if (context == null) continue;
 
             if (whichChildren == JAVA_AX_VISIBLE_CHILDREN) {
-                if (!context.getAccessibleComponent().isVisible()) continue;
+                AccessibleComponent acomp = context.getAccessibleComponent();
+                if (acomp == null || !acomp.isVisible()) {
+                    continue;
+                }
             } else if (whichChildren == JAVA_AX_SELECTED_CHILDREN) {
-                if (!ac.getAccessibleSelection().isAccessibleChildSelected(i)) continue;
+                AccessibleSelection sel = ac.getAccessibleSelection();
+                if (sel == null || !sel.isAccessibleChildSelected(i)) {
+                    continue;
+                }
             }
 
             if (!allowIgnored) {
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessible.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessible.java
index c5611c4..a1de15b 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessible.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessible.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,19 +26,24 @@
 package sun.lwawt.macosx;
 
 import java.awt.Component;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
 import java.lang.reflect.Field;
 
 import javax.accessibility.Accessible;
 import javax.accessibility.AccessibleContext;
 import javax.swing.JProgressBar;
 import javax.swing.JSlider;
-import javax.swing.event.CaretEvent;
-import javax.swing.event.CaretListener;
 import javax.swing.event.ChangeEvent;
 import javax.swing.event.ChangeListener;
-import javax.swing.event.DocumentEvent;
-import javax.swing.event.DocumentListener;
-import javax.swing.text.JTextComponent;
+
+import static javax.accessibility.AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY;
+import static javax.accessibility.AccessibleContext.ACCESSIBLE_CARET_PROPERTY;
+import static javax.accessibility.AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY;
+import static javax.accessibility.AccessibleContext.ACCESSIBLE_STATE_PROPERTY;
+import static javax.accessibility.AccessibleContext.ACCESSIBLE_TEXT_PROPERTY;
+import javax.accessibility.AccessibleRole;
+import javax.accessibility.AccessibleState;
 
 
 class CAccessible extends CFRetainedResource implements Accessible {
@@ -73,10 +78,16 @@
 
     private static native void unregisterFromCocoaAXSystem(long ptr);
     private static native void valueChanged(long ptr);
+    private static native void selectedTextChanged(long ptr);
     private static native void selectionChanged(long ptr);
+    private static native void menuOpened(long ptr);
+    private static native void menuClosed(long ptr);
+    private static native void menuItemSelected(long ptr);
 
     private Accessible accessible;
 
+    private AccessibleContext activeDescendant;
+
     private CAccessible(final Accessible accessible) {
         super(0L, true); // real pointer will be poked in by native
 
@@ -99,13 +110,10 @@
         return accessible.getAccessibleContext();
     }
 
-    // currently only supports text components
     public void addNotificationListeners(Component c) {
-        if (c instanceof JTextComponent) {
-            JTextComponent tc = (JTextComponent) c;
-            AXTextChangeNotifier listener = new AXTextChangeNotifier();
-            tc.getDocument().addDocumentListener(listener);
-            tc.addCaretListener(listener);
+        if (c instanceof Accessible) {
+            AccessibleContext ac = ((Accessible)c).getAccessibleContext();
+            ac.addPropertyChangeListener(new AXChangeNotifier());
         }
         if (c instanceof JProgressBar) {
             JProgressBar pb = (JProgressBar) c;
@@ -117,29 +125,59 @@
     }
 
 
-    private class AXTextChangeNotifier implements DocumentListener, CaretListener {
-        @Override
-        public void changedUpdate(DocumentEvent e) {
-            if (ptr != 0) valueChanged(ptr);
-        }
+    private class AXChangeNotifier implements PropertyChangeListener {
 
         @Override
-        public void insertUpdate(DocumentEvent e) {
-            if (ptr != 0) valueChanged(ptr);
-        }
-
-        @Override
-        public void removeUpdate(DocumentEvent e) {
-            if (ptr != 0) valueChanged(ptr);
-        }
-
-        @Override
-        public void caretUpdate(CaretEvent e) {
-            if (ptr != 0) selectionChanged(ptr);
+        public void propertyChange(PropertyChangeEvent e) {
+            String name = e.getPropertyName();
+            if ( ptr != 0 ) {
+                Object newValue = e.getNewValue();
+                Object oldValue = e.getOldValue();
+                if (name.compareTo(ACCESSIBLE_CARET_PROPERTY) == 0) {
+                    selectedTextChanged(ptr);
+                } else if (name.compareTo(ACCESSIBLE_TEXT_PROPERTY) == 0 ) {
+                    valueChanged(ptr);
+                } else if (name.compareTo(ACCESSIBLE_SELECTION_PROPERTY) == 0 ) {
+                    selectionChanged(ptr);
+                } else if (name.compareTo(ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY) == 0 ) {
+                    if (newValue instanceof AccessibleContext) {
+                        activeDescendant = (AccessibleContext)newValue;
+                    }
+                } else if (name.compareTo(ACCESSIBLE_STATE_PROPERTY) == 0) {
+                    AccessibleContext thisAC = accessible.getAccessibleContext();
+                    AccessibleRole thisRole = thisAC.getAccessibleRole();
+                    Accessible parentAccessible = thisAC.getAccessibleParent();
+                    AccessibleRole parentRole = null;
+                    if (parentAccessible != null) {
+                        parentRole = parentAccessible.getAccessibleContext().getAccessibleRole();
+                    }
+                    // At least for now don't handle combo box menu state changes.
+                    // This may change when later fixing issues which currently
+                    // exist for combo boxes, but for now the following is only
+                    // for JPopupMenus, not for combobox menus.
+                    if (parentRole != AccessibleRole.COMBO_BOX) {
+                        if (thisRole == AccessibleRole.POPUP_MENU) {
+                            if ( newValue != null &&
+                                 ((AccessibleState)newValue) == AccessibleState.VISIBLE ) {
+                                    menuOpened(ptr);
+                            } else if ( oldValue != null &&
+                                        ((AccessibleState)oldValue) == AccessibleState.VISIBLE ) {
+                                menuClosed(ptr);
+                            }
+                        } else if (thisRole == AccessibleRole.MENU_ITEM) {
+                            if ( newValue != null &&
+                                 ((AccessibleState)newValue) == AccessibleState.FOCUSED ) {
+                                menuItemSelected(ptr);
+                            }
+                        }
+                    }
+                }
+            }
         }
     }
 
     private class AXProgressChangeNotifier implements ChangeListener {
+        @Override
         public void stateChanged(ChangeEvent e) {
             if (ptr != 0) valueChanged(ptr);
         }
@@ -148,4 +186,9 @@
     static Accessible getSwingAccessible(final Accessible a) {
         return (a instanceof CAccessible) ? ((CAccessible)a).accessible : a;
     }
+
+    static AccessibleContext getActiveDescendant(final Accessible a) {
+        return (a instanceof CAccessible) ? ((CAccessible)a).activeDescendant : null;
+    }
+
 }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java
index 429a395..73a8875 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java
@@ -147,8 +147,7 @@
             String separator = System.getProperty("line.separator");
             StringBuilder sb = new StringBuilder();
             if(strings.length > 0) {
-                sb.append(strings[0]);
-                for(int i = 1; i < strings.length; i++) {
+                for(int i = 0; i < strings.length; i++) {
                     sb.append(strings[i]);
                     sb.append(separator);
                 }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CInputMethodDescriptor.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CInputMethodDescriptor.java
index d922d02..891972f 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CInputMethodDescriptor.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CInputMethodDescriptor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -57,15 +57,19 @@
     }
 
     static Object[] getAvailableLocalesInternal() {
-        List workList = nativeGetAvailableLocales();
+        List<Object> workList = nativeGetAvailableLocales();
+        Locale currentLocale = CInputMethod.getNativeLocale();
 
-        if (workList != null) {
+        if (workList == null || workList.isEmpty()) {
+            return new Object[] {
+                    currentLocale != null ? currentLocale : Locale.getDefault()
+            };
+        } else {
+            if (currentLocale != null && !workList.contains(currentLocale)) {
+                workList.add(currentLocale);
+            }
             return workList.toArray();
         }
-
-        return new Object[] {
-            Locale.getDefault()
-        };
     }
 
     /**
@@ -119,5 +123,5 @@
     }
 
     private static native void nativeInit();
-    private static native List nativeGetAvailableLocales();
+    private static native List<Object> nativeGetAvailableLocales();
 }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java
index 15c377f..3cccfa5 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java
@@ -262,9 +262,8 @@
 
     static class DeltaAccumulator {
 
-        static final double MIN_THRESHOLD = 0.1;
-        static final double MAX_THRESHOLD = 0.5;
         double accumulatedDelta;
+        boolean accumulate;
 
         int getRoundedDelta(double delta, int scrollPhase) {
 
@@ -275,25 +274,23 @@
                     roundDelta = delta > 0 ? 1 : -1;
                 }
             } else { // trackpad
-                boolean begin = scrollPhase == NSEvent.SCROLL_PHASE_BEGAN;
-                boolean end = scrollPhase == NSEvent.SCROLL_MASK_PHASE_ENDED
-                        || scrollPhase == NSEvent.SCROLL_MASK_PHASE_CANCELLED;
-
-                if (begin) {
+                if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
                     accumulatedDelta = 0;
+                    accumulate = true;
                 }
+                else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
+                    accumulate = true;
+                }
+                if (accumulate) {
 
-                accumulatedDelta += delta;
+                    accumulatedDelta += delta;
 
-                double absAccumulatedDelta = Math.abs(accumulatedDelta);
-                if (absAccumulatedDelta > MAX_THRESHOLD) {
                     roundDelta = (int) Math.round(accumulatedDelta);
-                    accumulatedDelta -= roundDelta;
-                }
 
-                if (end) {
-                    if (roundDelta == 0 && absAccumulatedDelta > MIN_THRESHOLD) {
-                        roundDelta = accumulatedDelta > 0 ? 1 : -1;
+                    accumulatedDelta -= roundDelta;
+
+                    if (scrollPhase == NSEvent.SCROLL_PHASE_ENDED) {
+                        accumulate = false;
                     }
                 }
             }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
index 32ef49d..b2b4c16 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, 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
@@ -68,6 +68,7 @@
     private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
     private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
     private static native void nativeSynthesizeMouseEnteredExitedEvents();
+    private static native void nativeSynthesizeMouseEnteredExitedEvents(long nsWindowPtr, int eventType);
     private static native void nativeDispose(long nsWindowPtr);
     private static native void nativeEnterFullScreenMode(long nsWindowPtr);
     private static native void nativeExitFullScreenMode(long nsWindowPtr);
@@ -213,6 +214,7 @@
     private boolean isFullScreenAnimationOn;
 
     private volatile boolean isIconifyAnimationActive;
+    private volatile boolean isZoomed;
 
     private Window target;
     private LWWindowPeer peer;
@@ -505,11 +507,7 @@
         if (undecorated) {
             return this.normalBounds != null;
         }
-        AtomicBoolean ref = new AtomicBoolean();
-        execute(ptr -> {
-            ref.set(CWrapper.NSWindow.isZoomed(ptr));
-        });
-        return ref.get();
+        return isZoomed;
     }
 
     private void maximize() {
@@ -875,6 +873,13 @@
             return;
         }
 
+        if (blocked) {
+            // We are going to show a modal window. Previously displayed window will be
+            // blocked/disabled. So we have to send mouse exited event to it now, since
+            // all mouse events are discarded for blocked/disabled windows.
+            execute(ptr -> nativeSynthesizeMouseEnteredExitedEvents(ptr, CocoaConstants.NSMouseExited));
+        }
+
         execute(ptr -> nativeSetEnabled(ptr, !blocked));
         checkBlockingAndOrder();
     }
@@ -975,6 +980,11 @@
 
     protected void deliverMoveResizeEvent(int x, int y, int width, int height,
                                         boolean byUser) {
+        AtomicBoolean ref = new AtomicBoolean();
+        execute(ptr -> {
+            ref.set(CWrapper.NSWindow.isZoomed(ptr));
+        });
+        isZoomed = ref.get();
         checkZoom();
 
         final Rectangle oldB = nativeBounds;
@@ -1039,6 +1049,11 @@
         return !peer.isSimpleWindow() && target.getFocusableWindowState();
     }
 
+    private boolean isBlocked() {
+        LWWindowPeer blocker = (peer != null) ? peer.getBlocker() : null;
+        return (blocker != null);
+    }
+
     /*
      * An utility method for the support of the auto request focus.
      * Updates the focusable state of the window under certain
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java
index 4de4d57..0a6bc23 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java
@@ -177,12 +177,6 @@
             return;
         }
 
-        // See if this has an NSPrintInfo in it.
-        NSPrintInfo nsPrintInfo = (NSPrintInfo)attributes.get(NSPrintInfo.class);
-        if (nsPrintInfo != null) {
-            fNSPrintInfo = nsPrintInfo.getValue();
-        }
-
         PageRanges pageRangesAttr =  (PageRanges)attributes.get(PageRanges.class);
         if (isSupportedValue(pageRangesAttr, attributes)) {
             SunPageSelection rangeSelect = (SunPageSelection)attributes.get(SunPageSelection.class);
@@ -535,8 +529,11 @@
 
     @Override
     protected void finalize() {
-        if (fNSPrintInfo != -1) {
-            dispose(fNSPrintInfo);
+        synchronized (fNSPrintInfoLock) {
+            if (fNSPrintInfo != -1) {
+                dispose(fNSPrintInfo);
+            }
+            fNSPrintInfo = -1;
         }
     }
 
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java
index eccc257..3a8508d 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java
@@ -36,8 +36,8 @@
     static final int SCROLL_PHASE_UNSUPPORTED = 1;
     static final int SCROLL_PHASE_BEGAN = 2;
     static final int SCROLL_PHASE_CONTINUED = 3;
-    static final int SCROLL_MASK_PHASE_CANCELLED = 4;
-    static final int SCROLL_MASK_PHASE_ENDED = 5;
+    static final int SCROLL_PHASE_MOMENTUM_BEGAN = 4;
+    static final int SCROLL_PHASE_ENDED = 5;
 
     private int type;
     private int modifierFlags;
diff --git a/jdk/src/macosx/native/sun/awt/AWTView.m b/jdk/src/macosx/native/sun/awt/AWTView.m
index 35c9440..74d685a 100644
--- a/jdk/src/macosx/native/sun/awt/AWTView.m
+++ b/jdk/src/macosx/native/sun/awt/AWTView.m
@@ -385,6 +385,13 @@
         clickCount = [event clickCount];
     }
 
+    jdouble deltaX = [event deltaX];
+    jdouble deltaY = [event deltaY];
+    if ([AWTToolkit hasPreciseScrollingDeltas: event]) {
+        deltaX = [event scrollingDeltaX] * 0.1;
+        deltaY = [event scrollingDeltaY] * 0.1;
+    }
+
     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDDI)V");
     jobject jEvent = JNFNewObject(env, jctor_NSEvent,
@@ -394,8 +401,8 @@
                                   [event buttonNumber],
                                   (jint)localPoint.x, (jint)localPoint.y,
                                   (jint)absP.x, (jint)absP.y,
-                                  [event deltaY],
-                                  [event deltaX],
+                                  deltaY,
+                                  deltaX,
                                   [AWTToolkit scrollStateWithEvent: event]);
     if (jEvent == nil) {
         // Unable to create event by some reason.
diff --git a/jdk/src/macosx/native/sun/awt/AWTWindow.m b/jdk/src/macosx/native/sun/awt/AWTWindow.m
index 43a10ab..41a7408 100644
--- a/jdk/src/macosx/native/sun/awt/AWTWindow.m
+++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, 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
@@ -330,7 +330,7 @@
 + (NSArray*) getWindowLayers {
     static NSArray *windowLayers;
     static dispatch_once_t token;
- 
+
     // Initialize the list of possible window layers
     dispatch_once(&token, ^{
         // The layers are ordered from front to back, (i.e. the toppest one is the first)
@@ -345,7 +345,6 @@
     return windowLayers;
 }
 
-
 // returns id for the topmost window under mouse
 + (NSInteger) getTopmostWindowUnderMouseID {
     NSInteger result = -1;
@@ -362,7 +361,7 @@
 }
 
 + (NSInteger) getTopmostWindowUnderMouseIDImpl:(NSInteger)windowLayer {
-    NSInteger result = -1;    
+    NSInteger result = -1;
 
     NSRect screenRect = [[NSScreen mainScreen] frame];
     NSPoint nsMouseLocation = [NSEvent mouseLocation];
@@ -463,7 +462,22 @@
     [super dealloc];
 }
 
-// Tests wheather the corresponding Java paltform window is visible or not
+// Tests whether window is blocked by modal dialog/window
+- (BOOL) isBlocked {
+    BOOL isBlocked = NO;
+    
+    JNIEnv *env = [ThreadUtilities getJNIEnv];
+    jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
+    if (platformWindow != NULL) {
+        static JNF_MEMBER_CACHE(jm_isBlocked, jc_CPlatformWindow, "isBlocked", "()Z");
+        isBlocked = JNFCallBooleanMethod(env, platformWindow, jm_isBlocked) == JNI_TRUE ? YES : NO;
+        (*env)->DeleteLocalRef(env, platformWindow);
+    }
+    
+    return isBlocked;
+}
+
+// Tests whether the corresponding Java platform window is visible or not
 + (BOOL) isJavaPlatformWindowVisible:(NSWindow *)window {
     BOOL isVisible = NO;
     
@@ -487,8 +501,9 @@
 - (void) orderChildWindows:(BOOL)focus {
 AWT_ASSERT_APPKIT_THREAD;
 
-    if (self.isMinimizing) {
+    if (self.isMinimizing || [self isBlocked]) {
         // Do not perform any ordering, if iconify is in progress
+        // or the window is blocked by a modal window
         return;
     }
 
@@ -842,18 +857,20 @@
 
 - (void)sendEvent:(NSEvent *)event {
         if ([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown) {
-            // Move parent windows to front and make sure that a child window is displayed
-            // in front of its nearest parent.
-            if (self.ownerWindow != nil) {
-                JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
-                jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
-                if (platformWindow != NULL) {
-                    static JNF_MEMBER_CACHE(jm_orderAboveSiblings, jc_CPlatformWindow, "orderAboveSiblings", "()V");
-                    JNFCallVoidMethod(env,platformWindow, jm_orderAboveSiblings);
-                    (*env)->DeleteLocalRef(env, platformWindow);
+            if ([self isBlocked]) {
+                // Move parent windows to front and make sure that a child window is displayed
+                // in front of its nearest parent.
+                if (self.ownerWindow != nil) {
+                    JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
+                    jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
+                    if (platformWindow != NULL) {
+                        static JNF_MEMBER_CACHE(jm_orderAboveSiblings, jc_CPlatformWindow, "orderAboveSiblings", "()V");
+                        JNFCallVoidMethod(env,platformWindow, jm_orderAboveSiblings);
+                        (*env)->DeleteLocalRef(env, platformWindow);
+                    }
                 }
+                [self orderChildWindows:YES];
             }
-            [self orderChildWindows:YES];
 
             NSPoint p = [NSEvent mouseLocation];
             NSRect frame = [self.nsWindow frame];
@@ -863,9 +880,12 @@
             if (p.y >= (frame.origin.y + contentRect.size.height)) {
                 JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
                 jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
-                // Currently, no need to deliver the whole NSEvent.
-                static JNF_MEMBER_CACHE(jm_deliverNCMouseDown, jc_CPlatformWindow, "deliverNCMouseDown", "()V");
-                JNFCallVoidMethod(env, platformWindow, jm_deliverNCMouseDown);
+                if (platformWindow != NULL) {
+                    // Currently, no need to deliver the whole NSEvent.
+                    static JNF_MEMBER_CACHE(jm_deliverNCMouseDown, jc_CPlatformWindow, "deliverNCMouseDown", "()V");
+                    JNFCallVoidMethod(env, platformWindow, jm_deliverNCMouseDown);
+                    (*env)->DeleteLocalRef(env, platformWindow);
+                }
             }
         }
 }
@@ -1316,9 +1336,9 @@
 /*
  * Class:     sun_lwawt_macosx_CPlatformWindow
  * Method:    nativeSynthesizeMouseEnteredExitedEvents
- * Signature: (J)V
+ * Signature: ()V
  */
-JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents__
 (JNIEnv *env, jclass clazz)
 {
     JNF_COCOA_ENTER(env);
@@ -1332,6 +1352,29 @@
 
 /*
  * Class:     sun_lwawt_macosx_CPlatformWindow
+ * Method:    nativeSynthesizeMouseEnteredExitedEvents
+ * Signature: (JI)V
+ */
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents__JI
+(JNIEnv *env, jclass clazz, jlong windowPtr, jint eventType)
+{
+JNF_COCOA_ENTER(env);
+
+    if (eventType == NSMouseEntered || eventType == NSMouseExited) {
+        NSWindow *nsWindow = OBJC(windowPtr);
+
+        [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
+            [AWTWindow synthesizeMouseEnteredExitedEvents:nsWindow withType:eventType];
+        }];
+    } else {
+        [JNFException raise:env as:kIllegalArgumentException reason:"unknown event type"];
+    }
+    
+JNF_COCOA_EXIT(env);
+}
+
+/*
+ * Class:     sun_lwawt_macosx_CPlatformWindow
  * Method:    _toggleFullScreenMode
  * Signature: (J)V
  */
diff --git a/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m b/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m
index ace6c8e..cc83026 100644
--- a/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m
+++ b/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m
@@ -146,6 +146,7 @@
                     jc_CGraphicsEnvironment, "_displayReconfiguration","(IZ)V");
             JNFCallVoidMethod(env, graphicsEnv, jm_displayReconfiguration,
                     (jint) display, (jboolean) flags & kCGDisplayRemoveFlag);
+            (*env)->DeleteLocalRef(env, graphicsEnv);
         });
     }];
 }
diff --git a/jdk/src/macosx/native/sun/awt/CPrinterJob.m b/jdk/src/macosx/native/sun/awt/CPrinterJob.m
index dfcbc1f..d9154fa 100644
--- a/jdk/src/macosx/native/sun/awt/CPrinterJob.m
+++ b/jdk/src/macosx/native/sun/awt/CPrinterJob.m
@@ -361,6 +361,8 @@
     static JNF_MEMBER_CACHE(jm_isCollated, sjc_CPrinterJob, "isCollated", "()Z");
     static JNF_MEMBER_CACHE(jm_getFromPage, sjc_CPrinterJob, "getFromPageAttrib", "()I");
     static JNF_MEMBER_CACHE(jm_getToPage, sjc_CPrinterJob, "getToPageAttrib", "()I");
+    static JNF_MEMBER_CACHE(jm_getMinPage, sjc_CPrinterJob, "getMinPageAttrib", "()I");
+    static JNF_MEMBER_CACHE(jm_getMaxPage, sjc_CPrinterJob, "getMaxPageAttrib", "()I");
     static JNF_MEMBER_CACHE(jm_getSelectAttrib, sjc_CPrinterJob, "getSelectAttrib", "()I");
     static JNF_MEMBER_CACHE(jm_getNumberOfPages, jc_Pageable, "getNumberOfPages", "()I");
     static JNF_MEMBER_CACHE(jm_getPageFormat, sjc_CPrinterJob, "getPageFormatFromAttributes", "()Ljava/awt/print/PageFormat;");
@@ -372,31 +374,33 @@
 
     jboolean collated = JNFCallBooleanMethod(env, srcPrinterJob, jm_isCollated); // AWT_THREADING Safe (known object)
     [printingDictionary setObject:[NSNumber numberWithBool:collated ? YES : NO] forKey:NSPrintMustCollate];
-    jint jNumPages = JNFCallIntMethod(env, srcPageable, jm_getNumberOfPages); // AWT_THREADING Safe (!appKit)
-    if (jNumPages != java_awt_print_Pageable_UNKNOWN_NUMBER_OF_PAGES)
-    {
-        jint selectID = JNFCallIntMethod(env, srcPrinterJob, jm_getSelectAttrib);
-        if (selectID ==0) {
-            [printingDictionary setObject:[NSNumber numberWithBool:YES] forKey:NSPrintAllPages];
-        } else if (selectID == 2) {
-            // In Mac 10.7,  Print ALL is deselected if PrintSelection is YES whether
-            // NSPrintAllPages is YES or NO
-            [printingDictionary setObject:[NSNumber numberWithBool:NO] forKey:NSPrintAllPages];
-            [printingDictionary setObject:[NSNumber numberWithBool:YES] forKey:NSPrintSelectionOnly];
-        } else {
-            [printingDictionary setObject:[NSNumber numberWithBool:NO] forKey:NSPrintAllPages];
-        }
-
-        jint fromPage = JNFCallIntMethod(env, srcPrinterJob, jm_getFromPage);
-        jint toPage = JNFCallIntMethod(env, srcPrinterJob, jm_getToPage);
-        // setting fromPage and toPage will not be shown in the dialog if printing All pages
-        [printingDictionary setObject:[NSNumber numberWithInteger:fromPage] forKey:NSPrintFirstPage];
-        [printingDictionary setObject:[NSNumber numberWithInteger:toPage] forKey:NSPrintLastPage];
-    }
-    else
-    {
+    jint selectID = JNFCallIntMethod(env, srcPrinterJob, jm_getSelectAttrib);
+    jint fromPage = JNFCallIntMethod(env, srcPrinterJob, jm_getFromPage);
+    jint toPage = JNFCallIntMethod(env, srcPrinterJob, jm_getToPage);
+    if (selectID ==0) {
         [printingDictionary setObject:[NSNumber numberWithBool:YES] forKey:NSPrintAllPages];
+    } else if (selectID == 2) {
+        // In Mac 10.7,  Print ALL is deselected if PrintSelection is YES whether
+        // NSPrintAllPages is YES or NO
+        [printingDictionary setObject:[NSNumber numberWithBool:NO] forKey:NSPrintAllPages];
+        [printingDictionary setObject:[NSNumber numberWithBool:YES] forKey:NSPrintSelectionOnly];
+    } else {
+        jint minPage = JNFCallIntMethod(env, srcPrinterJob, jm_getMinPage);
+        jint maxPage = JNFCallIntMethod(env, srcPrinterJob, jm_getMaxPage);
+
+        // for PD_SELECTION or PD_NOSELECTION, check from/to page
+        // to determine which radio button to select
+        if (fromPage > minPage || toPage < maxPage) {
+            [printingDictionary setObject:[NSNumber numberWithBool:NO] forKey:NSPrintAllPages];
+        } else {
+            [printingDictionary setObject:[NSNumber numberWithBool:YES] forKey:NSPrintAllPages];
+        }
     }
+
+    // setting fromPage and toPage will not be shown in the dialog if printing All pages
+    [printingDictionary setObject:[NSNumber numberWithInteger:fromPage] forKey:NSPrintFirstPage];
+    [printingDictionary setObject:[NSNumber numberWithInteger:toPage] forKey:NSPrintLastPage];
+
     jobject page = JNFCallObjectMethod(env, srcPrinterJob, jm_getPageFormat); 
     if (page != NULL) {
         javaPageFormatToNSPrintInfo(env, NULL, page, dst);
diff --git a/jdk/src/macosx/native/sun/awt/CTrayIcon.m b/jdk/src/macosx/native/sun/awt/CTrayIcon.m
index b3967df..bcf82cf 100644
--- a/jdk/src/macosx/native/sun/awt/CTrayIcon.m
+++ b/jdk/src/macosx/native/sun/awt/CTrayIcon.m
@@ -135,6 +135,13 @@
 
     clickCount = [event clickCount];
 
+    jdouble deltaX = [event deltaX];
+    jdouble deltaY = [event deltaY];
+    if ([AWTToolkit hasPreciseScrollingDeltas: event]) {
+        deltaX = [event scrollingDeltaX] * 0.1;
+        deltaY = [event scrollingDeltaY] * 0.1;
+    }
+
     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDDI)V");
     jobject jEvent = JNFNewObject(env, jctor_NSEvent,
@@ -144,8 +151,8 @@
                                   [event buttonNumber],
                                   (jint)localPoint.x, (jint)localPoint.y,
                                   (jint)absP.x, (jint)absP.y,
-                                  [event deltaY],
-                                  [event deltaX],
+                                  deltaY,
+                                  deltaX,
                                   [AWTToolkit scrollStateWithEvent: event]);
     if (jEvent == nil) {
         // Unable to create event by some reason.
diff --git a/jdk/src/macosx/native/sun/awt/JavaAccessibilityAction.m b/jdk/src/macosx/native/sun/awt/JavaAccessibilityAction.m
index ffdf8b5..e8b1bda 100644
--- a/jdk/src/macosx/native/sun/awt/JavaAccessibilityAction.m
+++ b/jdk/src/macosx/native/sun/awt/JavaAccessibilityAction.m
@@ -64,16 +64,20 @@
 
     jobject fCompLocal = (*env)->NewLocalRef(env, fComponent);
     if ((*env)->IsSameObject(env, fCompLocal, NULL)) {
-        return @"unknown";
+        return nil;
     }
     NSString *str = nil;
-    jobject jstr = JNFCallStaticObjectMethod(env, jm_getAccessibleActionDescription, fAccessibleAction, fIndex, fCompLocal);
+    jstring jstr = JNFCallStaticObjectMethod( env,
+                                              jm_getAccessibleActionDescription,
+                                              fAccessibleAction,
+                                              fIndex,
+                                              fCompLocal );
     if (jstr != NULL) {
-        NSString *str = JNFJavaToNSString(env, jstr); // AWT_THREADING Safe (AWTRunLoopMode)
+        str = JNFJavaToNSString(env, jstr); // AWT_THREADING Safe (AWTRunLoopMode)
         (*env)->DeleteLocalRef(env, jstr);
     }
     (*env)->DeleteLocalRef(env, fCompLocal);
-    return str == nil ? @"unknown" : str;
+    return str;
 }
 
 - (void)perform
diff --git a/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.h b/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.h
index 6325dce..b22db64 100644
--- a/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.h
+++ b/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,6 +55,7 @@
 BOOL isVertical(JNIEnv *env, jobject axContext, jobject component);
 BOOL isHorizontal(JNIEnv *env, jobject axContext, jobject component);
 BOOL isShowing(JNIEnv *env, jobject axContext, jobject component);
+BOOL isSelectable(JNIEnv *env, jobject axContext, jobject component);
 NSPoint getAxComponentLocationOnScreen(JNIEnv *env, jobject axComponent, jobject component);
 jint getAxTextCharCount(JNIEnv *env, jobject axText, jobject component);
 
diff --git a/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m b/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m
index 2b99936..41cd9b2 100644
--- a/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m
+++ b/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m
@@ -151,6 +151,18 @@
     return showing;
 }
 
+BOOL isSelectable(JNIEnv *env, jobject axContext, jobject component)
+{
+    static JNF_STATIC_MEMBER_CACHE( jm_SELECTABLE,
+                                    sjc_AccessibleState,
+                                    "SELECTABLE",
+                                    "Ljavax/accessibility/AccessibleState;" );
+    jobject axSelectableState = JNFGetStaticObjectField(env, jm_SELECTABLE);
+    BOOL selectable = containsAxState(env, axContext, axSelectableState, component);
+    (*env)->DeleteLocalRef(env, axSelectableState);
+    return selectable;
+}
+
 NSPoint getAxComponentLocationOnScreen(JNIEnv *env, jobject axComponent, jobject component)
 {
     static JNF_STATIC_MEMBER_CACHE(jm_getLocationOnScreen, sjc_CAccessibility, "getLocationOnScreen", "(Ljavax/accessibility/AccessibleComponent;Ljava/awt/Component;)Ljava/awt/Point;");
diff --git a/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.h b/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.h
index 392fd30..0284490 100644
--- a/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.h
+++ b/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,6 +50,7 @@
 - (id)initWithParent:(NSObject*)parent withEnv:(JNIEnv *)env withAccessible:(jobject)accessible withIndex:(jint)index withView:(NSView *)view withJavaRole:(NSString *)javaRole;
 - (void)unregisterFromCocoaAXSystem;
 - (void)postValueChanged;
+- (void)postSelectedTextChanged;
 - (void)postSelectionChanged;
 - (BOOL)isEqual:(id)anObject;
 - (BOOL)isAccessibleWithEnv:(JNIEnv *)env forAccessible:(jobject)accessible;
@@ -71,6 +72,7 @@
 - (NSString *)javaRole;
 - (BOOL)isMenu;
 - (BOOL)isSelected:(JNIEnv *)env;
+- (BOOL)isSelectable:(JNIEnv *)env;
 - (BOOL)isVisible:(JNIEnv *)env;
 
 // attribute names
@@ -85,6 +87,8 @@
 - (NSArray *)accessibilityChildrenAttribute;
 - (BOOL)accessibilityIsChildrenAttributeSettable;
 - (NSUInteger)accessibilityIndexOfChild:(id)child;
+- (NSArray *)accessibilityArrayAttributeValues:(NSString *)attribute
+    index:(NSUInteger)index maxCount:(NSUInteger)maxCount;
 - (NSNumber *)accessibilityEnabledAttribute;
 - (BOOL)accessibilityIsEnabledAttributeSettable;
 - (NSNumber *)accessibilityFocusedAttribute;
@@ -92,6 +96,8 @@
 - (void)accessibilitySetFocusedAttribute:(id)value;
 - (NSString *)accessibilityHelpAttribute;
 - (BOOL)accessibilityIsHelpAttributeSettable;
+- (NSValue *)accessibilityIndexAttribute;
+- (BOOL)accessibilityIsIndexAttributeSettable;
 - (id)accessibilityMaxValueAttribute;
 - (BOOL)accessibilityIsMaxValueAttributeSettable;
 - (id)accessibilityMinValueAttribute;
@@ -108,6 +114,9 @@
 - (BOOL)accessibilityIsRoleDescriptionAttributeSettable;
 - (NSArray *)accessibilitySelectedChildrenAttribute;
 - (BOOL)accessibilityIsSelectedChildrenAttributeSettable;
+- (NSNumber *)accessibilitySelectedAttribute;
+- (BOOL)accessibilityIsSelectedAttributeSettable;
+- (void)accessibilitySetSelectedAttribute:(id)value;
 - (NSValue *)accessibilitySizeAttribute;
 - (BOOL)accessibilityIsSizeAttributeSettable;
 - (NSString *)accessibilitySubroleAttribute;
diff --git a/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m b/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m
index b740d05..a5c43a6 100644
--- a/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m
+++ b/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m
@@ -66,7 +66,6 @@
 static JNF_MEMBER_CACHE(jf_ptr, sjc_CAccessible, "ptr", "J");
 static JNF_STATIC_MEMBER_CACHE(sjm_getCAccessible, sjc_CAccessible, "getCAccessible", "(Ljavax/accessibility/Accessible;)Lsun/lwawt/macosx/CAccessible;");
 
-
 static jobject sAccessibilityClass = NULL;
 
 // sAttributeNamesForRoleCache holds the names of the attributes to which each java
@@ -201,12 +200,36 @@
     NSAccessibilityPostNotification(self, NSAccessibilityValueChangedNotification);
 }
 
-- (void)postSelectionChanged
+- (void)postSelectedTextChanged
 {
     AWT_ASSERT_APPKIT_THREAD;
     NSAccessibilityPostNotification(self, NSAccessibilitySelectedTextChangedNotification);
 }
 
+- (void)postSelectionChanged
+{
+    AWT_ASSERT_APPKIT_THREAD;
+    NSAccessibilityPostNotification(self, NSAccessibilitySelectedChildrenChangedNotification);
+}
+
+- (void)postMenuOpened
+{
+    AWT_ASSERT_APPKIT_THREAD;
+    NSAccessibilityPostNotification(self, (NSString *)kAXMenuOpenedNotification);
+}
+
+- (void)postMenuClosed
+{
+    AWT_ASSERT_APPKIT_THREAD;
+    NSAccessibilityPostNotification(self, (NSString *)kAXMenuClosedNotification);
+}
+
+- (void)postMenuItemSelected
+{
+    AWT_ASSERT_APPKIT_THREAD;
+    NSAccessibilityPostNotification(self, (NSString *)kAXMenuItemSelectedNotification);
+}
+
 - (BOOL)isEqual:(id)anObject
 {
     if (![anObject isKindOfClass:[self class]]) return NO;
@@ -225,7 +248,7 @@
 {
     if (sAttributeNamesForRoleCache == nil) {
         sAttributeNamesLOCK = [[NSObject alloc] init];
-        sAttributeNamesForRoleCache = [[NSMutableDictionary alloc] initWithCapacity:10];
+        sAttributeNamesForRoleCache = [[NSMutableDictionary alloc] initWithCapacity:60];
     }
 
     if (sRoles == nil) {
@@ -272,8 +295,7 @@
 + (jobject) getCAccessible:(jobject)jaccessible withEnv:(JNIEnv *)env {
     if (JNFIsInstanceOf(env, jaccessible, &sjc_CAccessible)) {
         return jaccessible;
-    }
-    else if (JNFIsInstanceOf(env, jaccessible, &sjc_Accessible)) {
+    } else if (JNFIsInstanceOf(env, jaccessible, &sjc_Accessible)) {
         return JNFCallStaticObjectMethod(env, sjm_getCAccessible, jaccessible);
     }
     return NULL;
@@ -281,6 +303,7 @@
 
 + (NSArray *)childrenOfParent:(JavaComponentAccessibility *)parent withEnv:(JNIEnv *)env withChildrenCode:(NSInteger)whichChildren allowIgnored:(BOOL)allowIgnored
 {
+    if (parent->fAccessible == NULL) return nil;
     jobjectArray jchildrenAndRoles = (jobjectArray)JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, parent->fAccessible, parent->fComponent, whichChildren, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
     if (jchildrenAndRoles == NULL) return nil;
 
@@ -316,11 +339,15 @@
 
 + (JavaComponentAccessibility *)createWithAccessible:(jobject)jaccessible withEnv:(JNIEnv *)env withView:(NSView *)view
 {
+    JavaComponentAccessibility *ret = nil;
     jobject jcomponent = [(AWTView *)view awtComponent:env];
     jint index = JNFCallStaticIntMethod(env, sjm_getAccessibleIndexInParent, jaccessible, jcomponent);
-    NSString *javaRole = getJavaRole(env, jaccessible, jcomponent);
+    if (index >= 0) {
+      NSString *javaRole = getJavaRole(env, jaccessible, jcomponent);
+      ret = [self createWithAccessible:jaccessible role:javaRole index:index withEnv:env withView:view];
+    }
     (*env)->DeleteLocalRef(env, jcomponent);
-    return [self createWithAccessible:jaccessible role:javaRole index:index withEnv:env withView:view];
+    return ret;
 }
 
 + (JavaComponentAccessibility *) createWithAccessible:(jobject)jaccessible role:(NSString *)javaRole index:(jint)index withEnv:(JNIEnv *)env withView:(NSView *)view
@@ -357,6 +384,14 @@
     // must init freshly -alloc'd object
     [newChild initWithParent:parent withEnv:env withAccessible:jCAX withIndex:index withView:view withJavaRole:javaRole]; // must init new instance
 
+    // If creating a JPopupMenu (not a combobox popup list) need to fire menuOpened.
+    // This is the only way to know if the menu is opening; visible state change
+    // can't be caught because the listeners are not set up in time.
+    if ( [javaRole isEqualToString:@"popupmenu"] &&
+         ![[parent javaRole] isEqualToString:@"combobox"] ) {
+        [newChild postMenuOpened];
+    }
+
     // must hard retain pointer poked into Java object
     [newChild retain];
     JNFSetLongField(env, jCAX, jf_ptr, ptr_to_jlong(newChild));
@@ -370,7 +405,7 @@
 {
     static JNF_STATIC_MEMBER_CACHE(jm_getInitialAttributeStates, sjc_CAccessibility, "getInitialAttributeStates", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)[Z");
 
-    NSMutableArray *attributeNames = [NSMutableArray arrayWithCapacity:10];
+    NSMutableArray *attributeNames = [NSMutableArray arrayWithCapacity:20];
     [attributeNames retain];
 
     // all elements respond to parent, role, role description, window, topLevelUIElement, help
@@ -449,6 +484,12 @@
     // children
     if (attributeStatesArray[6]) {
         [attributeNames addObject:NSAccessibilityChildrenAttribute];
+        if ([javaRole isEqualToString:@"list"]) {
+            [attributeNames addObject:NSAccessibilitySelectedChildrenAttribute];
+            [attributeNames addObject:NSAccessibilityVisibleChildrenAttribute];
+        }
+        // Just above, the below mentioned support has been added back in for lists.
+        // However, the following comments may still be useful for future fixes.
 //        [attributeNames addObject:NSAccessibilitySelectedChildrenAttribute];
 //        [attributeNames addObject:NSAccessibilityVisibleChildrenAttribute];
                 //According to AXRoles.txt:
@@ -567,6 +608,14 @@
     return isChildSelected(env, ((JavaComponentAccessibility *)[self parent])->fAccessible, fIndex, fComponent);
 }
 
+- (BOOL)isSelectable:(JNIEnv *)env
+{
+    jobject axContext = [self axContextWithEnv:env];
+    BOOL selectable = isSelectable(env, axContext, fComponent);
+    (*env)->DeleteLocalRef(env, axContext);
+    return selectable;
+}
+
 - (BOOL)isVisible:(JNIEnv *)env
 {
     if (fIndex == -1) {
@@ -586,18 +635,41 @@
 
     @synchronized(sAttributeNamesLOCK) {
         NSString *javaRole = [self javaRole];
-        NSArray *names = (NSArray *)[sAttributeNamesForRoleCache objectForKey:javaRole];
-        if (names != nil) return names;
-
-        names = [self initializeAttributeNamesWithEnv:env];
-        if (names != nil) {
+        NSArray *names =
+            (NSArray *)[sAttributeNamesForRoleCache objectForKey:javaRole];
+        if (names == nil) {
+            names = [self initializeAttributeNamesWithEnv:env];
 #ifdef JAVA_AX_DEBUG
             NSLog(@"Initializing: %s for %@: %@", __FUNCTION__, javaRole, names);
 #endif
             [sAttributeNamesForRoleCache setObject:names forKey:javaRole];
-            return names;
         }
-    }
+        // The above set of attributes is immutable per role, but some objects, if
+        // they are the child of a list, need to add the selected and index attributes.
+        id myParent = [self accessibilityParentAttribute];
+        if ([myParent isKindOfClass:[JavaComponentAccessibility class]]) {
+            NSString *parentRole = [(JavaComponentAccessibility *)myParent javaRole];
+            if ([parentRole isEqualToString:@"list"]) {
+                NSMutableArray *moreNames =
+                    [[NSMutableArray alloc] initWithCapacity: [names count] + 2];
+                [moreNames addObjectsFromArray: names];
+                [moreNames addObject:NSAccessibilitySelectedAttribute];
+                [moreNames addObject:NSAccessibilityIndexAttribute];
+                return moreNames;
+            }
+        }
+        // popupmenu's return values not selected children
+        if ( [javaRole isEqualToString:@"popupmenu"] &&
+             ![[[self parent] javaRole] isEqualToString:@"combobox"] ) {
+            NSMutableArray *moreNames =
+                [[NSMutableArray alloc] initWithCapacity: [names count] + 1];
+            [moreNames addObjectsFromArray: names];
+            [moreNames addObject:NSAccessibilityValueAttribute];
+            return moreNames;
+        }
+        return names;
+
+    }  // end @synchronized
 
 #ifdef JAVA_AX_DEBUG
     NSLog(@"Warning in %s: could not find attribute names for role: %@", __FUNCTION__, [self javaRole]);
@@ -656,7 +728,10 @@
 - (NSArray *)accessibilityChildrenAttribute
 {
     JNIEnv* env = [ThreadUtilities getJNIEnv];
-    NSArray *children = [JavaComponentAccessibility childrenOfParent:self withEnv:env withChildrenCode:JAVA_AX_VISIBLE_CHILDREN allowIgnored:NO];
+    NSArray *children = [JavaComponentAccessibility childrenOfParent:self
+                                                    withEnv:env
+                                                    withChildrenCode:JAVA_AX_ALL_CHILDREN
+                                                    allowIgnored:NO];
 
     NSArray *value = nil;
     if ([children count] > 0) {
@@ -665,6 +740,7 @@
 
     return value;
 }
+
 - (BOOL)accessibilityIsChildrenAttributeSettable
 {
     return NO;
@@ -680,7 +756,12 @@
         return [super accessibilityIndexOfChild:child];
     }
 
-    return JNFCallStaticIntMethod([ThreadUtilities getJNIEnv], sjm_getAccessibleIndexInParent, ((JavaComponentAccessibility *)child)->fAccessible, ((JavaComponentAccessibility *)child)->fComponent);
+    jint returnValue =
+        JNFCallStaticIntMethod( [ThreadUtilities getJNIEnv],
+                                sjm_getAccessibleIndexInParent,
+                                ((JavaComponentAccessibility *)child)->fAccessible,
+                                ((JavaComponentAccessibility *)child)->fComponent );
+    return (returnValue == -1) ? NSNotFound : returnValue;
 }
 
 // Without this optimization accessibilityChildrenAttribute is called in order to get the entire array of children.
@@ -754,7 +835,7 @@
 
     jobject val = JNFCallStaticObjectMethod(env, sjm_getAccessibleDescription, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (val == NULL) {
-        return @"unknown";
+        return nil;
     }
     NSString* str = JNFJavaToNSString(env, val);
     (*env)->DeleteLocalRef(env, val);
@@ -766,6 +847,18 @@
     return NO;
 }
 
+- (NSValue *)accessibilityIndexAttribute
+{
+    NSInteger index = fIndex;
+    NSValue *returnValue = [NSValue value:&index withObjCType:@encode(NSInteger)];
+    return returnValue;
+}
+
+- (BOOL)accessibilityIsIndexAttributeSettable
+{
+    return NO;
+}
+
 // Element's maximum value (id)
 - (id)accessibilityMaxValueAttribute
 {
@@ -880,6 +973,13 @@
     if (fNSRole == nil) {
         NSString *javaRole = [self javaRole];
         fNSRole = [sRoles objectForKey:javaRole];
+        // The sRoles NSMutableDictionary maps popupmenu to Mac's popup button.
+        // JComboBox behavior currently relies on this.  However this is not the
+        // proper mapping for a JPopupMenu so fix that.
+        if ( [javaRole isEqualToString:@"popupmenu"] &&
+             ![[[self parent] javaRole] isEqualToString:@"combobox"] ) {
+             fNSRole = NSAccessibilityMenuRole;
+        }
         if (fNSRole == nil) {
             // this component has assigned itself a custom AccessibleRole not in the sRoles array
             fNSRole = javaRole;
@@ -888,6 +988,7 @@
     }
     return fNSRole;
 }
+
 - (BOOL)accessibilityIsRoleAttributeSettable
 {
     return NO;
@@ -939,6 +1040,33 @@
     return NO; // cmcnote: actually it should be. so need to write accessibilitySetSelectedChildrenAttribute also
 }
 
+- (NSNumber *)accessibilitySelectedAttribute
+{
+    return [NSNumber numberWithBool:[self isSelected:[ThreadUtilities getJNIEnv]]];
+}
+
+- (BOOL)accessibilityIsSelectedAttributeSettable
+{
+    if ([self isSelectable:[ThreadUtilities getJNIEnv]]) {
+        return YES;
+    } else {
+        return NO;
+    }
+}
+
+- (void)accessibilitySetSelectedAttribute:(id)value
+{
+    static JNF_STATIC_MEMBER_CACHE( jm_requestSelection,
+                                    sjc_CAccessibility,
+                                    "requestSelection",
+                                    "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)V" );
+    
+    if ([(NSNumber*)value boolValue]) {
+        JNIEnv* env = [ThreadUtilities getJNIEnv];
+        JNFCallStaticVoidMethod(env, jm_requestSelection, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
+    }
+}
+
 // Element size (NSValue)
 - (NSValue *)accessibilitySizeAttribute {
     JNIEnv* env = [ThreadUtilities getJNIEnv];
@@ -960,8 +1088,7 @@
 - (NSString *)accessibilitySubroleAttribute
 {
     NSString *value = nil;
-    if ([[self javaRole] isEqualToString:@"passwordtext"])
-    {
+    if ([[self javaRole] isEqualToString:@"passwordtext"]) {
         value = NSAccessibilitySecureTextFieldSubrole;
     }
     /*
@@ -1005,7 +1132,7 @@
 
     jobject val = JNFCallStaticObjectMethod(env, sjm_getAccessibleName, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (val == NULL) {
-        return @"unknown";
+        return nil;
     }
     NSString* str = JNFJavaToNSString(env, val);
     (*env)->DeleteLocalRef(env, val);
@@ -1037,6 +1164,45 @@
 
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
+    // Need to handle popupmenus differently.
+    //
+    // At least for now don't handle combo box menus.
+    // This may change when later fixing issues which currently 
+    // exist for combo boxes, but for now the following is only
+    // for JPopupMenus, not for combobox menus.
+    id parent = [self parent];
+    if ( [[self javaRole] isEqualToString:@"popupmenu"] &&
+         ![[parent javaRole] isEqualToString:@"combobox"] ) {
+        NSArray *children =
+            [JavaComponentAccessibility childrenOfParent:self
+                                        withEnv:env
+                                        withChildrenCode:JAVA_AX_ALL_CHILDREN
+                                        allowIgnored:YES];
+        if ([children count] > 0) {
+            // handle case of AXMenuItem
+            // need to ask menu what is selected
+            NSArray *selectedChildrenOfMenu =
+            	[self accessibilitySelectedChildrenAttribute];
+            JavaComponentAccessibility *selectedMenuItem =
+            	[selectedChildrenOfMenu objectAtIndex:0];
+            if (selectedMenuItem != nil) {
+                jobject itemValue =
+                	JNFCallStaticObjectMethod( env,
+                                                   sjm_getAccessibleName,
+                                                   selectedMenuItem->fAccessible,
+                                                   selectedMenuItem->fComponent ); // AWT_THREADING Safe (AWTRunLoop)
+                if (itemValue == NULL) {
+                    return nil;
+                }
+                NSString* itemString = JNFJavaToNSString(env, itemValue);
+                (*env)->DeleteLocalRef(env, itemValue);
+                return itemString;
+            } else {
+            	return nil;
+            }
+        }
+    }
+
     // ask Java for the component's accessibleValue. In java, the "accessibleValue" just means a numerical value
     // a text value is taken care of in JavaTextAccessibility
 
@@ -1210,14 +1376,11 @@
 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessibility_focusChanged
 (JNIEnv *env, jobject jthis)
 {
-
 JNF_COCOA_ENTER(env);
     [ThreadUtilities performOnMainThread:@selector(postFocusChanged:) on:[JavaComponentAccessibility class] withObject:nil waitUntilDone:NO];
 JNF_COCOA_EXIT(env);
 }
 
-
-
 /*
  * Class:     sun_lwawt_macosx_CAccessible
  * Method:    valueChanged
@@ -1233,6 +1396,22 @@
 
 /*
  * Class:     sun_lwawt_macosx_CAccessible
+ * Method:    selectedTextChanged
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_selectedTextChanged
+(JNIEnv *env, jclass jklass, jlong element)
+{
+JNF_COCOA_ENTER(env);
+    [ThreadUtilities performOnMainThread:@selector(postSelectedTextChanged)
+                     on:(JavaComponentAccessibility *)jlong_to_ptr(element)
+                     withObject:nil
+                     waitUntilDone:NO];
+JNF_COCOA_EXIT(env);
+}
+
+/*
+ * Class:     sun_lwawt_macosx_CAccessible
  * Method:    selectionChanged
  * Signature: (I)V
  */
@@ -1244,6 +1423,53 @@
 JNF_COCOA_EXIT(env);
 }
 
+/*
+ * Class:     sun_lwawt_macosx_CAccessible
+ * Method:    menuOpened
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuOpened
+(JNIEnv *env, jclass jklass, jlong element)
+{
+JNF_COCOA_ENTER(env);
+    [ThreadUtilities performOnMainThread:@selector(postMenuOpened)
+                     on:(JavaComponentAccessibility *)jlong_to_ptr(element)
+                     withObject:nil
+                     waitUntilDone:NO];
+JNF_COCOA_EXIT(env);
+}
+
+/*
+ * Class:     sun_lwawt_macosx_CAccessible
+ * Method:    menuClosed
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuClosed
+(JNIEnv *env, jclass jklass, jlong element)
+{
+JNF_COCOA_ENTER(env);
+    [ThreadUtilities performOnMainThread:@selector(postMenuClosed)
+                     on:(JavaComponentAccessibility *)jlong_to_ptr(element)
+                     withObject:nil
+                     waitUntilDone:NO];
+JNF_COCOA_EXIT(env);
+}
+
+/*
+ * Class:     sun_lwawt_macosx_CAccessible
+ * Method:    menuItemSelected
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuItemSelected
+(JNIEnv *env, jclass jklass, jlong element)
+{
+JNF_COCOA_ENTER(env);
+    [ThreadUtilities performOnMainThread:@selector(postMenuItemSelected)
+                     on:(JavaComponentAccessibility *)jlong_to_ptr(element)
+                     withObject:nil
+                     waitUntilDone:NO];
+JNF_COCOA_EXIT(env);
+}
 
 /*
  * Class:     sun_lwawt_macosx_CAccessible
diff --git a/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.h b/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.h
index 9c627a2..a87255c 100644
--- a/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.h
+++ b/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,6 +60,4 @@
 - (NSValue *)accessibilityRangeForPositionAttributeForParameter:(id)parameter;
 - (NSValue *)accessibilityRangeForIndexAttributeForParameter:(id)parameter;
 
-// actions
-- (NSDictionary *)getActions:(JNIEnv *)env;
 @end
diff --git a/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.m b/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.m
index f7e17b0..885eafd 100644
--- a/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.m
+++ b/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.m
@@ -427,13 +427,15 @@
     return javaIntArrayToNSRangeValue(env, axTextRange);
 }
 
-- (NSDictionary *)getActions:(JNIEnv *)env {
-    // cmcnote: this isn't correct; text can have actions. Not yet implemented. radr://3941691
-    // Editable text has AXShowMenu. Textfields have AXConfirm. Static text has no actions.
-#ifdef JAVA_AX_DEBUG
-    NSLog(@"Not yet implemented: %s\n", __FUNCTION__);
-#endif
-    return nil;
-}
+/* 
+ * - (NSDictionary *)getActions:(JNIEnv *)env { ... }
+ *
+ * In the future, possibly add support: Editable text has AXShowMenu.
+ * Textfields have AXConfirm.
+ *
+ * Note: JLabels (static text) in JLists have a press/click selection action
+ *   which is currently handled in superclass JavaComponentAccessibility.
+ *   If function is added here be sure to use [super getActions:env] for JLabels.
+ */
 
 @end
diff --git a/jdk/src/macosx/native/sun/awt/LWCToolkit.h b/jdk/src/macosx/native/sun/awt/LWCToolkit.h
index 0a57501..a81bc2d 100644
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.h
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.h
@@ -41,6 +41,7 @@
 + (long) getEventCount;
 + (void) eventCountPlusPlus;
 + (jint) scrollStateWithEvent: (NSEvent*) event;
++ (BOOL) hasPreciseScrollingDeltas: (NSEvent*) event;
 @end
 
 /*
diff --git a/jdk/src/macosx/native/sun/awt/LWCToolkit.m b/jdk/src/macosx/native/sun/awt/LWCToolkit.m
index 871f319..f56f587 100644
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.m
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.m
@@ -43,7 +43,7 @@
 #define SCROLL_PHASE_UNSUPPORTED 1
 #define SCROLL_PHASE_BEGAN 2
 #define SCROLL_PHASE_CONTINUED 3
-#define SCROLL_PHASE_CANCELLED 4
+#define SCROLL_PHASE_MOMENTUM_BEGAN 4
 #define SCROLL_PHASE_ENDED 5
 
 int gNumberOfButtons;
@@ -62,21 +62,38 @@
 }
 
 + (jint) scrollStateWithEvent: (NSEvent*) event {
-
+    
     if ([event type] != NSScrollWheel) {
         return 0;
     }
-
-    NSEventPhase phase = [event phase];
-    NSEventPhase momentumPhase = [event momentumPhase];
-
-    if (!phase && !momentumPhase) return SCROLL_PHASE_UNSUPPORTED;
-    switch (phase) {
-        case NSEventPhaseBegan: return SCROLL_PHASE_BEGAN;
-        case NSEventPhaseCancelled: return SCROLL_PHASE_CANCELLED;
-        case NSEventPhaseEnded: return SCROLL_PHASE_ENDED;
+    
+    if ([event phase]) {
+        // process a phase of manual scrolling
+        switch ([event phase]) {
+            case NSEventPhaseBegan: return SCROLL_PHASE_BEGAN;
+            case NSEventPhaseCancelled: return SCROLL_PHASE_ENDED;
+            case NSEventPhaseEnded: return SCROLL_PHASE_ENDED;
+            default: return SCROLL_PHASE_CONTINUED;
+        }
     }
-    return SCROLL_PHASE_CONTINUED;
+    
+    if ([event momentumPhase]) {
+        // process a phase of automatic scrolling
+        switch ([event momentumPhase]) {
+            case NSEventPhaseBegan: return SCROLL_PHASE_MOMENTUM_BEGAN;
+            case NSEventPhaseCancelled: return SCROLL_PHASE_ENDED;
+            case NSEventPhaseEnded: return SCROLL_PHASE_ENDED;
+            default: return SCROLL_PHASE_CONTINUED;
+        }
+    }
+    // phase and momentum phase both are not set
+    return SCROLL_PHASE_UNSUPPORTED;
+}
+
++ (BOOL) hasPreciseScrollingDeltas: (NSEvent*) event {
+    return [event type] == NSScrollWheel
+    && [event respondsToSelector:@selector(hasPreciseScrollingDeltas)]
+    && [event hasPreciseScrollingDeltas];
 }
 @end
 
diff --git a/jdk/src/macosx/native/sun/awt/QuartzSurfaceData.h b/jdk/src/macosx/native/sun/awt/QuartzSurfaceData.h
index a1899af..8d4a8a2 100644
--- a/jdk/src/macosx/native/sun/awt/QuartzSurfaceData.h
+++ b/jdk/src/macosx/native/sun/awt/QuartzSurfaceData.h
@@ -44,6 +44,8 @@
     SD_Fill,
     SD_EOFill,
     SD_Shade,
+    SD_LinearGradient,
+    SD_RadialGradient,
     SD_Pattern,
     SD_Image,
     SD_Text,
@@ -65,6 +67,17 @@
 };
 typedef struct _stateShadingInfo StateShadingInfo;
 
+struct _stateGradientInfo
+{
+    CGPoint    start;
+    CGPoint    end;
+    CGFloat  radius;
+    CGFloat* colordata;
+    CGFloat* fractionsdata;
+    jint     fractionsLength;
+};
+typedef struct _stateGradientInfo StateGradientInfo;
+
 struct _statePatternInfo
 {
     CGFloat    tx;
@@ -122,6 +135,7 @@
                                                 // its callees.
 
     StateShadingInfo*        shadingInfo;        // tracks shading and its parameters
+    StateGradientInfo*       gradientInfo;       // tracks gradient and its parameters
     StatePatternInfo*        patternInfo;        // tracks pattern and its parameters
     StateGraphicsInfo        graphicsStateInfo;    // tracks other graphics state
 
diff --git a/jdk/src/macosx/native/sun/awt/QuartzSurfaceData.m b/jdk/src/macosx/native/sun/awt/QuartzSurfaceData.m
index 131dc1e..017c46a 100644
--- a/jdk/src/macosx/native/sun/awt/QuartzSurfaceData.m
+++ b/jdk/src/macosx/native/sun/awt/QuartzSurfaceData.m
@@ -72,7 +72,7 @@
 
 // given a UInt32 color, it tries to find that find the corresponding CGColorRef in the hash cache. If the CGColorRef
 // doesn't exist or there is a collision, it creates a new one CGColorRef and put's in the cache. Then,
-// it sets with current fill/stroke color for the the CGContext passed in (qsdo->cgRef).
+// it sets with current fill/stroke color for the CGContext passed in (qsdo->cgRef).
 void setCachedColor(QuartzSDOps *qsdo, UInt32 color)
 {
     static const CGFloat kColorConversionMultiplier = 1.0f/255.0f;
@@ -268,9 +268,90 @@
     free(info);
 }
 
+static inline void contextQuartzLinearGradientPath(QuartzSDOps* qsdo)
+{
+
+PRINT("    contextQuartzLinearGradientPath");
+
+    CGContextRef cgRef = qsdo->cgRef;
+    StateGradientInfo *gradientInfo = qsdo->gradientInfo;
+   
+    CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
+    size_t num_locations = gradientInfo->fractionsLength;
+    CGFloat *locations = (CGFloat *) malloc(sizeof(CGFloat) * num_locations);
+    int i = 0;
+    size_t component_size = num_locations * 4;
+    CGFloat components[component_size];
+    CGGradientRef gradient = NULL;
+
+    for (i = 0; i < num_locations; i++) {
+        locations[i] = gradientInfo->fractionsdata[i];
+    }
+    for (i = 0; i < component_size; i++) {
+        components[i] = gradientInfo->colordata[i];
+    } 
+    CGContextSaveGState(cgRef);
+    gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, num_locations);
+    if (qsdo->isEvenOddFill) {
+        CGContextEOClip(cgRef);
+    } else {
+        CGContextClip(cgRef);
+    }
+    CGContextDrawLinearGradient(cgRef, gradient, gradientInfo->start, gradientInfo->end, kCGGradientDrawsAfterEndLocation);    
+
+    CGContextRestoreGState(cgRef);
+    CGColorSpaceRelease(colorspace);
+    CGGradientRelease(gradient);
+    free(locations);
+    free(gradientInfo->colordata);
+    free(gradientInfo->fractionsdata);
+}
+
+static inline void contextQuartzRadialGradientPath(QuartzSDOps* qsdo)
+{
+
+PRINT("    contextQuartzRadialGradientPath");
+
+    CGContextRef cgRef = qsdo->cgRef;
+    StateGradientInfo *gradientInfo = qsdo->gradientInfo;
+   
+    CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
+    size_t num_locations = gradientInfo->fractionsLength;
+    CGFloat *locations = (CGFloat *) malloc(sizeof(CGFloat) * num_locations);
+    int i = 0;
+    size_t component_size = num_locations * 4;
+    CGFloat components[component_size];
+    CGGradientRef gradient = NULL;
+    CGFloat startRadius = gradientInfo->radius;
+    CGFloat endRadius = gradientInfo->radius;
+
+    for (i = 0; i < num_locations; i++) {
+        locations[i] = gradientInfo->fractionsdata[i];
+    }
+    for (i = 0; i < component_size; i++) {
+        components[i] = gradientInfo->colordata[i];
+    } 
+    CGContextSaveGState(cgRef);
+    gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, num_locations);
+    if (qsdo->isEvenOddFill) {
+        CGContextEOClip(cgRef);
+    } else {
+        CGContextClip(cgRef);
+    }
+    CGContextDrawRadialGradient(cgRef, gradient, gradientInfo->start, 0, gradientInfo->end, endRadius, kCGGradientDrawsAfterEndLocation);    
+    
+    CGContextRestoreGState(cgRef);
+    CGColorSpaceRelease(colorspace);
+    CGGradientRelease(gradient);
+    free(locations);
+    free(gradientInfo->colordata);
+    free(gradientInfo->fractionsdata);
+}
+
 static inline void contextGradientPath(QuartzSDOps* qsdo)
 {
 PRINT("    ContextGradientPath")
+ 
     CGContextRef cgRef = qsdo->cgRef;
     StateShadingInfo* shadingInfo = qsdo->shadingInfo;
 
@@ -827,6 +908,68 @@
     qsdo->renderType = renderType;
 }
 
+void setupGradient(JNIEnv *env, QuartzSDOps* qsdo, jfloat* javaFloatGraphicsStates)
+{
+    static const CGFloat kColorConversionMultiplier = 1.0f/255.0f;
+    qsdo->gradientInfo = (StateGradientInfo*)malloc(sizeof(StateGradientInfo));
+    if (qsdo->gradientInfo == NULL)
+    {
+        [JNFException raise:env as:kOutOfMemoryError reason:"Failed to malloc memory for gradient paint"];
+    }
+
+    qsdo->graphicsStateInfo.simpleStroke = NO;
+    qsdo->graphicsStateInfo.simpleColor = NO;
+
+    qsdo->gradientInfo->start.x    = javaFloatGraphicsStates[sun_java2d_OSXSurfaceData_kColorx1Index];
+    qsdo->gradientInfo->start.y    = javaFloatGraphicsStates[sun_java2d_OSXSurfaceData_kColory1Index];
+    qsdo->gradientInfo->end.x    = javaFloatGraphicsStates[sun_java2d_OSXSurfaceData_kColorx2Index];
+    qsdo->gradientInfo->end.y    = javaFloatGraphicsStates[sun_java2d_OSXSurfaceData_kColory2Index];
+
+    jobject colorArray  = ((*env)->GetObjectArrayElement(env, qsdo->javaGraphicsStatesObjects, sun_java2d_OSXSurfaceData_kColorArrayIndex)); 
+    if (colorArray != NULL)
+    {
+        jint length = (*env)->GetArrayLength(env, colorArray);
+
+        jint* jcolorData = (jint*)(*env)->GetPrimitiveArrayCritical(env, colorArray, NULL);
+        qsdo->gradientInfo->colordata = (CGFloat*)malloc(sizeof(CGFloat)*4*length);
+        memset(qsdo->gradientInfo->colordata, 0, sizeof(CGFloat)*4*length);
+        if (jcolorData != NULL)
+        {
+            int i;
+            for (i=0; i<length; i++)
+            {
+                qsdo->gradientInfo->colordata[i*4] = ((jcolorData[i]>>16)&0xff)*kColorConversionMultiplier;
+
+                qsdo->gradientInfo->colordata[i*4+1] = ((jcolorData[i]>>8)&0xff)*kColorConversionMultiplier;
+
+                qsdo->gradientInfo->colordata[i*4+2] = ((jcolorData[i]>>0)&0xff)*kColorConversionMultiplier;
+
+                qsdo->gradientInfo->colordata[i*4+3] = ((jcolorData[i]>>24)&0xff)*kColorConversionMultiplier;
+            }
+        }
+        (*env)->ReleasePrimitiveArrayCritical(env, colorArray, jcolorData, 0);
+    }
+    jobject fractionsArray  = ((*env)->GetObjectArrayElement(env, qsdo->javaGraphicsStatesObjects, sun_java2d_OSXSurfaceData_kFractionsArrayIndex)); 
+    if (fractionsArray != NULL)
+    {
+        jint length = (*env)->GetArrayLength(env, fractionsArray);
+        qsdo->gradientInfo->fractionsLength = length;
+
+        jfloat* jfractionsData = (jfloat*)(*env)->GetPrimitiveArrayCritical(env, fractionsArray, NULL);
+        if (jfractionsData != NULL)
+        {
+            int i;
+            qsdo->gradientInfo->fractionsdata = (CGFloat *)malloc(sizeof(CGFloat) *length);
+            memset(qsdo->gradientInfo->fractionsdata, 0, sizeof(CGFloat)*length);
+            for (i=0; i<length; i++)
+            {
+                qsdo->gradientInfo->fractionsdata[i] = jfractionsData[i];
+            }
+            (*env)->ReleasePrimitiveArrayCritical(env, fractionsArray, jfractionsData, 0);
+        }
+    }    
+}
+
 SDRenderType SetUpPaint(JNIEnv *env, QuartzSDOps *qsdo, SDRenderType renderType)
 {
     CGContextRef cgRef = qsdo->cgRef;
@@ -898,6 +1041,21 @@
 
             break;
         }
+        case sun_java2d_OSXSurfaceData_kColorLinearGradient:
+        {
+            renderType = SD_LinearGradient;
+            setupGradient(env, qsdo, javaFloatGraphicsStates);
+            break;
+        }
+
+        case sun_java2d_OSXSurfaceData_kColorRadialGradient:
+        {
+            renderType = SD_RadialGradient;
+            setupGradient(env, qsdo, javaFloatGraphicsStates);
+            qsdo->gradientInfo->radius = javaFloatGraphicsStates[sun_java2d_OSXSurfaceData_kRadiusIndex];
+            break;
+        }
+
         case sun_java2d_OSXSurfaceData_kColorTexture:
         {
             qsdo->patternInfo = (StatePatternInfo*)malloc(sizeof(StatePatternInfo));
@@ -1076,11 +1234,24 @@
             }
             break;
 
+        case SD_LinearGradient:
+            if (CGContextIsPathEmpty(qsdo->cgRef) == 0)
+            {
+                contextQuartzLinearGradientPath(qsdo);
+            }
+            break;
+
+        case SD_RadialGradient:
+            if (CGContextIsPathEmpty(qsdo->cgRef) == 0)
+            {
+                contextQuartzRadialGradientPath(qsdo);
+            }
+            break;
+
         case SD_Pattern:
             if (CGContextIsPathEmpty(qsdo->cgRef) == 0)
             {
-                //TODO:BG
-                //contextTexturePath(env, qsdo);
+                contextTexturePath(env, qsdo);
             }
             break;
 
@@ -1111,4 +1282,8 @@
         gradientPaintReleaseFunction(qsdo->shadingInfo);
         qsdo->shadingInfo = NULL;
     }
+    if (qsdo->gradientInfo != NULL) {
+        gradientPaintReleaseFunction(qsdo->gradientInfo);
+        qsdo->gradientInfo = NULL;
+    }
 }
diff --git a/jdk/src/macosx/native/sun/font/AWTFont.m b/jdk/src/macosx/native/sun/font/AWTFont.m
index bfb90ec..6458f17 100644
--- a/jdk/src/macosx/native/sun/font/AWTFont.m
+++ b/jdk/src/macosx/native/sun/font/AWTFont.m
@@ -162,6 +162,44 @@
     return [sFontFamilyTable objectForKey:fontname];
 }
 
+static void addFont(CTFontUIFontType uiType, 
+                    NSMutableArray *allFonts,
+                    NSMutableDictionary* fontFamilyTable) {
+
+        CTFontRef font = CTFontCreateUIFontForLanguage(uiType, 0.0, NULL);
+        if (font == NULL) {
+            return;
+        }
+        CTFontDescriptorRef desc = CTFontCopyFontDescriptor(font);
+        if (desc == NULL) {
+            CFRelease(font);
+            return;
+        }
+        CFStringRef family = CTFontDescriptorCopyAttribute(desc, kCTFontFamilyNameAttribute);
+        if (family == NULL) {
+            CFRelease(desc);
+            CFRelease(font);
+            return;
+        }
+        CFStringRef name = CTFontDescriptorCopyAttribute(desc, kCTFontNameAttribute);
+        if (name == NULL) {
+            CFRelease(family);
+            CFRelease(desc);
+            CFRelease(font);
+            return;
+        }
+        [allFonts addObject:name];
+        [fontFamilyTable setObject:family forKey:name];
+#ifdef DEBUG
+        NSLog(@"name is : %@", (NSString*)name);
+        NSLog(@"family is : %@", (NSString*)family);
+#endif
+        CFRelease(family);
+        CFRelease(name);
+        CFRelease(desc);
+        CFRelease(font);
+}
+ 
 static NSArray*
 GetFilteredFonts()
 {
@@ -196,6 +234,16 @@
             }
         }
 
+        /*
+         * JavaFX registers these fonts and so JDK needs to do so as well.
+         * If this isn't done we will have mis-matched rendering, since
+         * although these may include fonts that are enumerated normally
+         * they also demonstrably includes fonts that are not.
+         */
+        addFont(kCTFontUIFontSystem, allFonts, fontFamilyTable);
+        addFont(kCTFontUIFontEmphasizedSystem, allFonts, fontFamilyTable);
+        addFont(kCTFontUIFontUserFixedPitch, allFonts, fontFamilyTable);
+
         sFilteredFonts = allFonts;
         sFontFamilyTable = fontFamilyTable;
     }
diff --git a/jdk/src/macosx/native/sun/osxapp/NSApplicationAWT.m b/jdk/src/macosx/native/sun/osxapp/NSApplicationAWT.m
index 39c50af..21576c0 100644
--- a/jdk/src/macosx/native/sun/osxapp/NSApplicationAWT.m
+++ b/jdk/src/macosx/native/sun/osxapp/NSApplicationAWT.m
@@ -362,7 +362,6 @@
 {
     void (^copy)() = [block copy];
     NSInteger encode = (NSInteger) copy;
-    [copy retain];
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    
     NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined
                                         location: NSMakePoint(0,0)
diff --git a/jdk/src/share/back/invoker.c b/jdk/src/share/back/invoker.c
index cd1cd2f..bd316dc 100644
--- a/jdk/src/share/back/invoker.c
+++ b/jdk/src/share/back/invoker.c
@@ -211,6 +211,62 @@
     return error;
 }
 
+/*
+ * Delete saved global references - if any - for:
+ * - a potentially thrown Exception
+ * - a returned refernce/array value
+ * See invoker_doInvoke() and invoke* methods where global references
+ * are being saved.
+ */
+static void
+deletePotentiallySavedGlobalRefs(JNIEnv *env, InvokeRequest *request)
+{
+    /* Delete potentially saved return value */
+    if ((request->invokeType == INVOKE_CONSTRUCTOR) ||
+        (returnTypeTag(request->methodSignature) == JDWP_TAG(OBJECT)) ||
+        (returnTypeTag(request->methodSignature) == JDWP_TAG(ARRAY))) {
+        if (request->returnValue.l != NULL) {
+            tossGlobalRef(env, &(request->returnValue.l));
+        }
+    }
+    /* Delete potentially saved exception */
+    if (request->exception != NULL) {
+        tossGlobalRef(env, &(request->exception));
+    }
+}
+
+/*
+ * Delete global argument references from the request which got put there before a
+ * invoke request was carried out. See fillInvokeRequest().
+ */
+static void
+deleteGlobalArgumentRefs(JNIEnv *env, InvokeRequest *request)
+{
+    void *cursor;
+    jint argIndex = 0;
+    jvalue *argument = request->arguments;
+    jbyte argumentTag = firstArgumentTypeTag(request->methodSignature, &cursor);
+
+    if (request->clazz != NULL) {
+        tossGlobalRef(env, &(request->clazz));
+    }
+    if (request->instance != NULL) {
+        tossGlobalRef(env, &(request->instance));
+    }
+    /* Delete global argument references */
+    while (argIndex < request->argumentCount) {
+        if ((argumentTag == JDWP_TAG(OBJECT)) ||
+            (argumentTag == JDWP_TAG(ARRAY))) {
+            if (argument->l != NULL) {
+                tossGlobalRef(env, &(argument->l));
+            }
+        }
+        argument++;
+        argIndex++;
+        argumentTag = nextArgumentTypeTag(&cursor);
+    }
+}
+
 static jvmtiError
 fillInvokeRequest(JNIEnv *env, InvokeRequest *request,
                   jbyte invokeType, jbyte options, jint id,
@@ -320,6 +376,8 @@
 invokeConstructor(JNIEnv *env, InvokeRequest *request)
 {
     jobject object;
+
+    JDI_ASSERT_MSG(request->clazz, "Request clazz null");
     object = JNI_FUNC_PTR(env,NewObjectA)(env, request->clazz,
                                      request->method,
                                      request->arguments);
@@ -336,6 +394,7 @@
         case JDWP_TAG(OBJECT):
         case JDWP_TAG(ARRAY): {
             jobject object;
+            JDI_ASSERT_MSG(request->clazz, "Request clazz null");
             object = JNI_FUNC_PTR(env,CallStaticObjectMethodA)(env,
                                        request->clazz,
                                        request->method,
@@ -424,6 +483,7 @@
         case JDWP_TAG(OBJECT):
         case JDWP_TAG(ARRAY): {
             jobject object;
+            JDI_ASSERT_MSG(request->instance, "Request instance null");
             object = JNI_FUNC_PTR(env,CallObjectMethodA)(env,
                                  request->instance,
                                  request->method,
@@ -511,6 +571,8 @@
         case JDWP_TAG(OBJECT):
         case JDWP_TAG(ARRAY): {
             jobject object;
+            JDI_ASSERT_MSG(request->clazz, "Request clazz null");
+            JDI_ASSERT_MSG(request->instance, "Request instance null");
             object = JNI_FUNC_PTR(env,CallNonvirtualObjectMethodA)(env,
                                            request->instance,
                                            request->clazz,
@@ -607,6 +669,8 @@
     JNIEnv *env;
     jboolean startNow;
     InvokeRequest *request;
+    jbyte options;
+    jbyte invokeType;
 
     JDI_ASSERT(thread);
 
@@ -623,6 +687,9 @@
     if (startNow) {
         request->started = JNI_TRUE;
     }
+    options = request->options;
+    invokeType = request->invokeType;
+
     debugMonitorExit(invokerLock);
 
     if (!startNow) {
@@ -637,7 +704,7 @@
 
         JNI_FUNC_PTR(env,ExceptionClear)(env);
 
-        switch (request->invokeType) {
+        switch (invokeType) {
             case INVOKE_CONSTRUCTOR:
                 invokeConstructor(env, request);
                 break;
@@ -645,7 +712,7 @@
                 invokeStatic(env, request);
                 break;
             case INVOKE_INSTANCE:
-                if (request->options & JDWP_INVOKE_OPTIONS(NONVIRTUAL) ) {
+                if (options & JDWP_INVOKE_OPTIONS(NONVIRTUAL) ) {
                     invokeNonvirtual(env, request);
                 } else {
                     invokeVirtual(env, request);
@@ -723,12 +790,23 @@
     }
 
     /*
+     * At this time, there's no need to retain global references on
+     * arguments since the reply is processed. No one will deal with
+     * this request ID anymore, so we must call deleteGlobalArgumentRefs().
+     *
+     * We cannot delete saved exception or return value references
+     * since otherwise a deleted handle would escape when writing
+     * the response to the stream. Instead, we clean those refs up
+     * after writing the respone.
+     */
+    deleteGlobalArgumentRefs(env, request);
+
+    /*
      * Give up the lock before I/O operation
      */
     debugMonitorExit(invokerLock);
     eventHandler_unlock();
 
-
     if (!detached) {
         outStream_initReply(&out, id);
         (void)outStream_writeValue(env, &out, tag, returnValue);
@@ -736,6 +814,16 @@
         (void)outStream_writeObjectRef(env, &out, exc);
         outStream_sendReply(&out);
     }
+
+    /*
+     * Delete potentially saved global references of return value
+     * and exception
+     */
+    eventHandler_lock(); // for proper lock order
+    debugMonitorEnter(invokerLock);
+    deletePotentiallySavedGlobalRefs(env, request);
+    debugMonitorExit(invokerLock);
+    eventHandler_unlock();
 }
 
 jboolean
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/AESCrypt.java b/jdk/src/share/classes/com/sun/crypto/provider/AESCrypt.java
index 12ffe89..c85f715 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/AESCrypt.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/AESCrypt.java
@@ -52,7 +52,7 @@
     private boolean ROUNDS_14 = false;
 
     /** Session and Sub keys */
-    private Object[] sessionK = null;
+    private int[][] sessionK = null;
     private int[] K = null;
 
     /** Cipher encryption/decryption key */
@@ -95,7 +95,7 @@
         }
 
         // set sub key to the corresponding session Key
-        this.K = (int[]) sessionK[(decrypting? 1:0)];
+        this.K = sessionK[(decrypting? 1:0)];
     }
 
     /**
@@ -660,7 +660,7 @@
         limit = ROUNDS*4;
 
         // store the expanded sub keys into 'sessionK'
-        sessionK = new Object[] { expandedKe, expandedKd };
+        sessionK = new int[][] { expandedKe, expandedKd };
     }
 
 
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/OutputFeedback.java b/jdk/src/share/classes/com/sun/crypto/provider/OutputFeedback.java
index 250e60e..47d9d63 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/OutputFeedback.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/OutputFeedback.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -162,11 +162,11 @@
             for (int i = 0; i < numBytes; i++) {
                 cipher[i + cipherOffset] =
                     (byte)(k[i] ^ plain[i + plainOffset]);
-                if (nShift != 0) {
-                    System.arraycopy(register, numBytes, register, 0, nShift);
-                }
-                System.arraycopy(k, 0, register, nShift, numBytes);
             }
+            if (nShift != 0) {
+                System.arraycopy(register, numBytes, register, 0, nShift);
+            }
+            System.arraycopy(k, 0, register, nShift, numBytes);
         }
         return plainLen;
     }
diff --git a/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java b/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java
index 698bac9..078b857 100644
--- a/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java
+++ b/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java
@@ -1017,15 +1017,15 @@
     private static final class DirectClip extends DirectDL
             implements Clip, Runnable, AutoClosingClip {
 
-        private Thread thread;
-        private byte[] audioData = null;
-        private int frameSize;         // size of one frame in bytes
-        private int m_lengthInFrames;
-        private int loopCount;
-        private int clipBytePosition;   // index in the audioData array at current playback
-        private int newFramePosition;   // set in setFramePosition()
-        private int loopStartFrame;
-        private int loopEndFrame;      // the last sample included in the loop
+        private volatile Thread thread;
+        private volatile byte[] audioData = null;
+        private volatile int frameSize;         // size of one frame in bytes
+        private volatile int m_lengthInFrames;
+        private volatile int loopCount;
+        private volatile int clipBytePosition;   // index in the audioData array at current playback
+        private volatile int newFramePosition;   // set in setFramePosition()
+        private volatile int loopStartFrame;
+        private volatile int loopEndFrame;      // the last sample included in the loop
 
         // auto closing clip support
         private boolean autoclosing = false;
@@ -1355,7 +1355,8 @@
         // main playback loop
         public void run() {
             if (Printer.trace) Printer.trace(">>> DirectClip: run() threadID="+Thread.currentThread().getId());
-            while (thread != null) {
+            Thread curThread = Thread.currentThread();
+            while (thread == curThread) {
                 // doIO is volatile, but we could check it, then get
                 // pre-empted while another thread changes doIO and notifies,
                 // before we wait (so we sleep in wait forever).
@@ -1363,7 +1364,12 @@
                     if (!doIO) {
                         try {
                             lock.wait();
-                        } catch(InterruptedException ie) {}
+                        } catch(InterruptedException ie) {
+                        } finally {
+                            if (thread != curThread) {
+                                break;
+                            }
+                        }
                     }
                 }
                 while (doIO) {
diff --git a/jdk/src/share/classes/com/sun/tools/jdi/MethodImpl.java b/jdk/src/share/classes/com/sun/tools/jdi/MethodImpl.java
index 1d93f4c..8135aed 100644
--- a/jdk/src/share/classes/com/sun/tools/jdi/MethodImpl.java
+++ b/jdk/src/share/classes/com/sun/tools/jdi/MethodImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -315,10 +315,14 @@
             return;
         }
         Value nthArgValue = arguments.get(paramCount - 1);
-        if (nthArgValue == null) {
+        if (nthArgValue == null && argCount == paramCount) {
+            // We have one varargs parameter and it is null
+            // so we don't have to do anything.
             return;
         }
-        Type nthArgType = nthArgValue.type();
+        // If the first varargs parameter is null, then don't
+        // access its type since it can't be an array.
+        Type nthArgType = (nthArgValue == null) ? null : nthArgValue.type();
         if (nthArgType instanceof ArrayTypeImpl) {
             if (argCount == paramCount &&
                 ((ArrayTypeImpl)nthArgType).isAssignableTo(lastParamType)) {
diff --git a/jdk/src/share/classes/java/awt/Container.java b/jdk/src/share/classes/java/awt/Container.java
index 47e580b..b9e4f91 100644
--- a/jdk/src/share/classes/java/awt/Container.java
+++ b/jdk/src/share/classes/java/awt/Container.java
@@ -1089,17 +1089,18 @@
             }
             checkAddToSelf(comp);
             checkNotAWindow(comp);
+            /* Reparent the component and tidy up the tree's state. */
+            if (comp.parent != null) {
+                comp.parent.remove(comp);
+                if (index > component.size()) {
+                    throw new IllegalArgumentException("illegal component position");
+                }
+            }
             if (thisGC != null) {
                 comp.checkGD(thisGC.getDevice().getIDstring());
             }
 
-            /* Reparent the component and tidy up the tree's state. */
-            if (comp.parent != null) {
-                comp.parent.remove(comp);
-                    if (index > component.size()) {
-                        throw new IllegalArgumentException("illegal component position");
-                    }
-            }
+
 
             //index == -1 means add to the end.
             if (index == -1) {
diff --git a/jdk/src/share/classes/java/awt/TextArea.java b/jdk/src/share/classes/java/awt/TextArea.java
index 34b2137..7c2acf0 100644
--- a/jdk/src/share/classes/java/awt/TextArea.java
+++ b/jdk/src/share/classes/java/awt/TextArea.java
@@ -322,9 +322,8 @@
         TextAreaPeer peer = (TextAreaPeer)this.peer;
         if (peer != null) {
             peer.insert(str, pos);
-        } else {
-            text = text.substring(0, pos) + str + text.substring(pos);
         }
+        text = text.substring(0, pos) + str + text.substring(pos);
     }
 
     /**
@@ -347,11 +346,7 @@
      */
     @Deprecated
     public synchronized void appendText(String str) {
-        if (peer != null) {
             insertText(str, getText().length());
-        } else {
-            text = text + str;
-        }
     }
 
     /**
@@ -386,9 +381,8 @@
         TextAreaPeer peer = (TextAreaPeer)this.peer;
         if (peer != null) {
             peer.replaceRange(str, start, end);
-        } else {
-            text = text.substring(0, start) + str + text.substring(end);
         }
+        text = text.substring(0, start) + str + text.substring(end);
     }
 
     /**
diff --git a/jdk/src/share/classes/java/awt/WaitDispatchSupport.java b/jdk/src/share/classes/java/awt/WaitDispatchSupport.java
index a504252..4ca7c85 100644
--- a/jdk/src/share/classes/java/awt/WaitDispatchSupport.java
+++ b/jdk/src/share/classes/java/awt/WaitDispatchSupport.java
@@ -65,6 +65,7 @@
 
     private AtomicBoolean keepBlockingEDT = new AtomicBoolean(false);
     private AtomicBoolean keepBlockingCT = new AtomicBoolean(false);
+    private AtomicBoolean afterExit = new AtomicBoolean(false);
 
     private static synchronized void initializeTimer() {
         if (timer == null) {
@@ -174,110 +175,116 @@
             log.fine("The secondary loop is already running, aborting");
             return false;
         }
+        try {
+            if (afterExit.get()) {
+                log.fine("Exit was called already, aborting");
+                return false;
+            }
 
-        final Runnable run = new Runnable() {
-            public void run() {
-                log.fine("Starting a new event pump");
-                if (filter == null) {
-                    dispatchThread.pumpEvents(condition);
-                } else {
-                    dispatchThread.pumpEventsForFilter(condition, filter);
-                }
-            }
-        };
-
-        // We have two mechanisms for blocking: if we're on the
-        // dispatch thread, start a new event pump; if we're
-        // on any other thread, call wait() on the treelock
-
-        Thread currentThread = Thread.currentThread();
-        if (currentThread == dispatchThread) {
-            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
-                log.finest("On dispatch thread: " + dispatchThread);
-            }
-            if (interval != 0) {
-                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
-                    log.finest("scheduling the timer for " + interval + " ms");
-                }
-                timer.schedule(timerTask = new TimerTask() {
-                    @Override
-                    public void run() {
-                        if (keepBlockingEDT.compareAndSet(true, false)) {
-                            wakeupEDT();
-                        }
-                    }
-                }, interval);
-            }
-            // Dispose SequencedEvent we are dispatching on the the current
-            // AppContext, to prevent us from hang - see 4531693 for details
-            SequencedEvent currentSE = KeyboardFocusManager.
-                getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
-            if (currentSE != null) {
-                if (log.isLoggable(PlatformLogger.Level.FINE)) {
-                    log.fine("Dispose current SequencedEvent: " + currentSE);
-                }
-                currentSE.dispose();
-            }
-            // In case the exit() method is called before starting
-            // new event pump it will post the waking event to EDT.
-            // The event will be handled after the the new event pump
-            // starts. Thus, the enter() method will not hang.
-            //
-            // Event pump should be privileged. See 6300270.
-            AccessController.doPrivileged(new PrivilegedAction<Void>() {
-                public Void run() {
-                    run.run();
-                    return null;
-                }
-            });
-        } else {
-            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
-                log.finest("On non-dispatch thread: " + currentThread);
-            }
-            synchronized (getTreeLock()) {
-                if (filter != null) {
-                    dispatchThread.addEventFilter(filter);
-                }
-                try {
-                    EventQueue eq = dispatchThread.getEventQueue();
-                    eq.postEvent(new PeerEvent(this, run, PeerEvent.PRIORITY_EVENT));
-                    keepBlockingCT.set(true);
-                    if (interval > 0) {
-                        long currTime = System.currentTimeMillis();
-                        while (keepBlockingCT.get() &&
-                               ((extCondition != null) ? extCondition.evaluate() : true) &&
-                               (currTime + interval > System.currentTimeMillis()))
-                        {
-                            getTreeLock().wait(interval);
-                        }
+            final Runnable run = new Runnable() {
+                public void run() {
+                    log.fine("Starting a new event pump");
+                    if (filter == null) {
+                        dispatchThread.pumpEvents(condition);
                     } else {
-                        while (keepBlockingCT.get() &&
-                               ((extCondition != null) ? extCondition.evaluate() : true))
-                        {
-                            getTreeLock().wait();
-                        }
-                    }
-                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
-                        log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
-                    }
-                } catch (InterruptedException e) {
-                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
-                        log.fine("Exception caught while waiting: " + e);
-                    }
-                } finally {
-                    if (filter != null) {
-                        dispatchThread.removeEventFilter(filter);
+                        dispatchThread.pumpEventsForFilter(condition, filter);
                     }
                 }
-                // If the waiting process has been stopped because of the
-                // time interval passed or an exception occurred, the state
-                // should be changed
-                keepBlockingEDT.set(false);
-                keepBlockingCT.set(false);
-            }
-        }
+            };
 
-        return true;
+            // We have two mechanisms for blocking: if we're on the
+            // dispatch thread, start a new event pump; if we're
+            // on any other thread, call wait() on the treelock
+
+            Thread currentThread = Thread.currentThread();
+            if (currentThread == dispatchThread) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
+                    log.finest("On dispatch thread: " + dispatchThread);
+                }
+                if (interval != 0) {
+                    if (log.isLoggable(PlatformLogger.Level.FINEST)) {
+                        log.finest("scheduling the timer for " + interval + " ms");
+                    }
+                    timer.schedule(timerTask = new TimerTask() {
+                        @Override
+                        public void run() {
+                            if (keepBlockingEDT.compareAndSet(true, false)) {
+                                wakeupEDT();
+                            }
+                        }
+                    }, interval);
+                }
+                // Dispose SequencedEvent we are dispatching on the current
+                // AppContext, to prevent us from hang - see 4531693 for details
+                SequencedEvent currentSE = KeyboardFocusManager.
+                        getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
+                if (currentSE != null) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
+                        log.fine("Dispose current SequencedEvent: " + currentSE);
+                    }
+                    currentSE.dispose();
+                }
+                // In case the exit() method is called before starting
+                // new event pump it will post the waking event to EDT.
+                // The event will be handled after the new event pump
+                // starts. Thus, the enter() method will not hang.
+                //
+                // Event pump should be privileged. See 6300270.
+                AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                    public Void run() {
+                        run.run();
+                        return null;
+                    }
+                });
+            } else {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
+                    log.finest("On non-dispatch thread: " + currentThread);
+                }
+                keepBlockingCT.set(true);
+                synchronized (getTreeLock()) {
+                    if (afterExit.get()) return false;
+                    if (filter != null) {
+                        dispatchThread.addEventFilter(filter);
+                    }
+                    try {
+                        EventQueue eq = dispatchThread.getEventQueue();
+                        eq.postEvent(new PeerEvent(this, run, PeerEvent.PRIORITY_EVENT));
+                        if (interval > 0) {
+                            long currTime = System.currentTimeMillis();
+                            while (keepBlockingCT.get() &&
+                                    ((extCondition != null) ? extCondition.evaluate() : true) &&
+                                    (currTime + interval > System.currentTimeMillis()))
+                            {
+                                getTreeLock().wait(interval);
+                            }
+                        } else {
+                            while (keepBlockingCT.get() &&
+                                    ((extCondition != null) ? extCondition.evaluate() : true))
+                            {
+                                getTreeLock().wait();
+                            }
+                        }
+                        if (log.isLoggable(PlatformLogger.Level.FINE)) {
+                            log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
+                        }
+                    } catch (InterruptedException e) {
+                        if (log.isLoggable(PlatformLogger.Level.FINE)) {
+                            log.fine("Exception caught while waiting: " + e);
+                        }
+                    } finally {
+                        if (filter != null) {
+                            dispatchThread.removeEventFilter(filter);
+                        }
+                    }
+                }
+            }
+            return true;
+        }
+        finally {
+            keepBlockingEDT.set(false);
+            keepBlockingCT.set(false);
+            afterExit.set(false);
+        }
     }
 
     /**
@@ -288,7 +295,8 @@
             log.fine("exit(): blockingEDT=" + keepBlockingEDT.get() +
                      ", blockingCT=" + keepBlockingCT.get());
         }
-        if (keepBlockingEDT.compareAndSet(true, false)) {
+        afterExit.set(true);
+        if (keepBlockingEDT.getAndSet(false)) {
             wakeupEDT();
             return true;
         }
diff --git a/jdk/src/share/classes/java/beans/MethodRef.java b/jdk/src/share/classes/java/beans/MethodRef.java
index 59b2690..6be617f 100644
--- a/jdk/src/share/classes/java/beans/MethodRef.java
+++ b/jdk/src/share/classes/java/beans/MethodRef.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -64,10 +64,9 @@
                 this.signature = null;
                 this.methodRef = null;
                 this.typeRef = null;
+                return null;
             }
-            else {
-                this.methodRef = new SoftReference<>(method);
-            }
+            this.methodRef = new SoftReference<>(method);
         }
         return isPackageAccessible(method.getDeclaringClass()) ? method : null;
     }
diff --git a/jdk/src/share/classes/java/io/CharArrayReader.java b/jdk/src/share/classes/java/io/CharArrayReader.java
index 08d447a..2190be3 100644
--- a/jdk/src/share/classes/java/io/CharArrayReader.java
+++ b/jdk/src/share/classes/java/io/CharArrayReader.java
@@ -130,8 +130,10 @@
             if (pos >= count) {
                 return -1;
             }
-            if (pos + len > count) {
-                len = count - pos;
+
+            int avail = count - pos;
+            if (len > avail) {
+                len = avail;
             }
             if (len <= 0) {
                 return 0;
@@ -157,8 +159,10 @@
     public long skip(long n) throws IOException {
         synchronized (lock) {
             ensureOpen();
-            if (pos + n > count) {
-                n = count - pos;
+
+            long avail = count - pos;
+            if (n > avail) {
+                n = avail;
             }
             if (n < 0) {
                 return 0;
diff --git a/jdk/src/share/classes/java/io/FileInputStream.java b/jdk/src/share/classes/java/io/FileInputStream.java
index 47d13a9..d1a902d 100644
--- a/jdk/src/share/classes/java/io/FileInputStream.java
+++ b/jdk/src/share/classes/java/io/FileInputStream.java
@@ -279,7 +279,11 @@
      * @exception  IOException  if n is negative, if the stream does not
      *             support seek, or if an I/O error occurs.
      */
-    public native long skip(long n) throws IOException;
+    public long skip(long n) throws IOException {
+        return skip0(n);
+    }
+
+    private native long skip0(long n) throws IOException;
 
     /**
      * Returns an estimate of the number of remaining bytes that can be read (or
@@ -298,7 +302,11 @@
      * @exception  IOException  if this file input stream has been closed by calling
      *             {@code close} or an I/O error occurs.
      */
-    public native int available() throws IOException;
+    public int available() throws IOException {
+        return available0();
+    }
+
+    private native int available0() throws IOException;
 
     /**
      * Closes this file input stream and releases any system resources
diff --git a/jdk/src/share/classes/java/io/StringBufferInputStream.java b/jdk/src/share/classes/java/io/StringBufferInputStream.java
index 509a96c..f47eebc 100644
--- a/jdk/src/share/classes/java/io/StringBufferInputStream.java
+++ b/jdk/src/share/classes/java/io/StringBufferInputStream.java
@@ -118,8 +118,10 @@
         if (pos >= count) {
             return -1;
         }
-        if (pos + len > count) {
-            len = count - pos;
+
+        int avail = count - pos;
+        if (len > avail) {
+            len = avail;
         }
         if (len <= 0) {
             return 0;
diff --git a/jdk/src/share/classes/java/security/Signature.java b/jdk/src/share/classes/java/security/Signature.java
index 355d708..b929af7 100644
--- a/jdk/src/share/classes/java/security/Signature.java
+++ b/jdk/src/share/classes/java/security/Signature.java
@@ -438,6 +438,10 @@
         return this.provider;
     }
 
+    private String getProviderName() {
+        return (provider == null)  ? "(no provider)" : provider.getName();
+    }
+
     void chooseFirstProvider() {
         // empty, overridden in Delegate
     }
@@ -459,7 +463,7 @@
 
         if (!skipDebug && pdebug != null) {
             pdebug.println("Signature." + algorithm +
-                " verification algorithm from: " + this.provider.getName());
+                " verification algorithm from: " + getProviderName());
         }
     }
 
@@ -508,7 +512,7 @@
 
         if (!skipDebug && pdebug != null) {
             pdebug.println("Signature." + algorithm +
-                " verification algorithm from: " + this.provider.getName());
+                " verification algorithm from: " + getProviderName());
         }
     }
 
@@ -529,7 +533,7 @@
 
         if (!skipDebug && pdebug != null) {
             pdebug.println("Signature." + algorithm +
-                " signing algorithm from: " + this.provider.getName());
+                " signing algorithm from: " + getProviderName());
         }
     }
 
@@ -552,7 +556,7 @@
 
         if (!skipDebug && pdebug != null) {
             pdebug.println("Signature." + algorithm +
-                " signing algorithm from: " + this.provider.getName());
+                " signing algorithm from: " + getProviderName());
         }
     }
 
diff --git a/jdk/src/share/classes/java/time/ZoneOffset.java b/jdk/src/share/classes/java/time/ZoneOffset.java
index dc2562a..97b7f13 100644
--- a/jdk/src/share/classes/java/time/ZoneOffset.java
+++ b/jdk/src/share/classes/java/time/ZoneOffset.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -375,15 +375,15 @@
         } else if ((minutes > 0 && seconds < 0) || (minutes < 0 && seconds > 0)) {
             throw new DateTimeException("Zone offset minutes and seconds must have the same sign");
         }
-        if (Math.abs(minutes) > 59) {
-            throw new DateTimeException("Zone offset minutes not in valid range: abs(value) " +
-                    Math.abs(minutes) + " is not in the range 0 to 59");
+        if (minutes < -59 || minutes > 59) {
+            throw new DateTimeException("Zone offset minutes not in valid range: value " +
+                    minutes + " is not in the range -59 to 59");
         }
-        if (Math.abs(seconds) > 59) {
-            throw new DateTimeException("Zone offset seconds not in valid range: abs(value) " +
-                    Math.abs(seconds) + " is not in the range 0 to 59");
+        if (seconds < -59 || seconds > 59) {
+            throw new DateTimeException("Zone offset seconds not in valid range: value " +
+                    seconds + " is not in the range -59 to 59");
         }
-        if (Math.abs(hours) == 18 && (Math.abs(minutes) > 0 || Math.abs(seconds) > 0)) {
+        if (Math.abs(hours) == 18 && (minutes | seconds) != 0) {
             throw new DateTimeException("Zone offset not in valid range: -18:00 to +18:00");
         }
     }
@@ -411,7 +411,7 @@
      * @throws DateTimeException if the offset is not in the required range
      */
     public static ZoneOffset ofTotalSeconds(int totalSeconds) {
-        if (Math.abs(totalSeconds) > MAX_SECONDS) {
+        if (totalSeconds < -MAX_SECONDS || totalSeconds > MAX_SECONDS) {
             throw new DateTimeException("Zone offset not in valid range: -18:00 to +18:00");
         }
         if (totalSeconds % (15 * SECONDS_PER_MINUTE) == 0) {
@@ -696,11 +696,12 @@
      * The comparison is "consistent with equals", as defined by {@link Comparable}.
      *
      * @param other  the other date to compare to, not null
-     * @return the comparator value, negative if less, postive if greater
+     * @return the comparator value, negative if less, positive if greater
      * @throws NullPointerException if {@code other} is null
      */
     @Override
     public int compareTo(ZoneOffset other) {
+        // abs(totalSeconds) <= MAX_SECONDS, so no overflow can happen here
         return other.totalSeconds - totalSeconds;
     }
 
diff --git a/jdk/src/share/classes/java/time/chrono/Era.java b/jdk/src/share/classes/java/time/chrono/Era.java
index 0e3c533..5cf0968 100644
--- a/jdk/src/share/classes/java/time/chrono/Era.java
+++ b/jdk/src/share/classes/java/time/chrono/Era.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -310,8 +310,8 @@
      * The parameters control the style of the returned text and the locale.
      * <p>
      * If no textual mapping is found then the {@link #getValue() numeric value} is returned.
-     * <p>
-     * This default implementation is suitable for all implementations.
+     *
+     * @apiNote This default implementation is suitable for most implementations.
      *
      * @param style  the style of the text required, not null
      * @param locale  the locale to use, not null
diff --git a/jdk/src/share/classes/java/time/chrono/JapaneseEra.java b/jdk/src/share/classes/java/time/chrono/JapaneseEra.java
index 0c9e3e8..a33efcd 100644
--- a/jdk/src/share/classes/java/time/chrono/JapaneseEra.java
+++ b/jdk/src/share/classes/java/time/chrono/JapaneseEra.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -73,11 +73,13 @@
 import java.io.Serializable;
 import java.time.DateTimeException;
 import java.time.LocalDate;
+import java.time.format.TextStyle;
 import java.time.temporal.ChronoField;
 import java.time.temporal.TemporalField;
 import java.time.temporal.UnsupportedTemporalTypeException;
 import java.time.temporal.ValueRange;
 import java.util.Arrays;
+import java.util.Locale;
 import java.util.Objects;
 
 import sun.util.calendar.CalendarDate;
@@ -125,8 +127,8 @@
      */
     public static final JapaneseEra HEISEI = new JapaneseEra(2, LocalDate.of(1989, 1, 8));
 
-    // the number of defined JapaneseEra constants.
-    // There could be an extra era defined in its configuration.
+    // The number of predefined JapaneseEra constants.
+    // There may be a supplemental era defined by the property.
     private static final int N_ERA_CONSTANTS = HEISEI.getValue() + ERA_OFFSET;
 
     /**
@@ -236,6 +238,23 @@
         return Arrays.copyOf(KNOWN_ERAS, KNOWN_ERAS.length);
     }
 
+    /**
+     * {@inheritDoc}
+     *
+     * @param style {@inheritDoc}
+     * @param locale {@inheritDoc}
+     */
+    @Override
+    public String getDisplayName(TextStyle style, Locale locale) {
+        // If this JapaneseEra is a supplemental one, obtain the name from
+        // the era definition.
+        if (getValue() > N_ERA_CONSTANTS - ERA_OFFSET) {
+            Objects.requireNonNull(locale, "locale");
+            return style.asNormal() == TextStyle.NARROW ? getAbbreviation() : getName();
+        }
+        return Era.super.getDisplayName(style, locale);
+    }
+
     //-----------------------------------------------------------------------
     /**
      * Obtains an instance of {@code JapaneseEra} from a date.
@@ -337,11 +356,7 @@
 
     //-----------------------------------------------------------------------
     String getAbbreviation() {
-        int index = ordinal(getValue());
-        if (index == 0) {
-            return "";
-        }
-        return ERA_CONFIG[index].getAbbreviation();
+        return ERA_CONFIG[ordinal(getValue())].getAbbreviation();
     }
 
     String getName() {
diff --git a/jdk/src/share/classes/java/util/ArrayList.java b/jdk/src/share/classes/java/util/ArrayList.java
index 925cc18..0af3388 100644
--- a/jdk/src/share/classes/java/util/ArrayList.java
+++ b/jdk/src/share/classes/java/util/ArrayList.java
@@ -842,6 +842,8 @@
         int lastRet = -1; // index of last element returned; -1 if no such
         int expectedModCount = modCount;
 
+        Itr() {}
+
         public boolean hasNext() {
             return cursor != size;
         }
diff --git a/jdk/src/share/classes/java/util/Base64.java b/jdk/src/share/classes/java/util/Base64.java
index 172acbe..61f68d3 100644
--- a/jdk/src/share/classes/java/util/Base64.java
+++ b/jdk/src/share/classes/java/util/Base64.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -788,7 +788,7 @@
         public void write(byte[] b, int off, int len) throws IOException {
             if (closed)
                 throw new IOException("Stream is closed");
-            if (off < 0 || len < 0 || off + len > b.length)
+            if (off < 0 || len < 0 || len > b.length - off)
                 throw new ArrayIndexOutOfBoundsException();
             if (len == 0)
                 return;
diff --git a/jdk/src/share/classes/java/util/CurrencyData.properties b/jdk/src/share/classes/java/util/CurrencyData.properties
index 5f2656e..df077cd 100644
--- a/jdk/src/share/classes/java/util/CurrencyData.properties
+++ b/jdk/src/share/classes/java/util/CurrencyData.properties
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -31,14 +31,14 @@
 # Version of the currency code information in this class.
 # It is a serial number that accompanies with each amendment.
 
-dataVersion=159
+dataVersion=162
 
 # List of all valid ISO 4217 currency codes.
 # To ensure compatibility, do not remove codes.
 
 all=ADP020-AED784-AFA004-AFN971-ALL008-AMD051-ANG532-AOA973-ARS032-ATS040-AUD036-\
     AWG533-AYM945-AZM031-AZN944-BAM977-BBD052-BDT050-BEF056-BGL100-BGN975-BHD048-BIF108-\
-    BMD060-BND096-BOB068-BOV984-BRL986-BSD044-BTN064-BWP072-BYB112-BYR974-\
+    BMD060-BND096-BOB068-BOV984-BRL986-BSD044-BTN064-BWP072-BYB112-BYR974-BYN933-\
     BZD084-CAD124-CDF976-CHE947-CHF756-CHW948-CLF990-CLP152-CNY156-COP170-COU970-CRC188-CSD891-CUP192-CUC931-\
     CVE132-CYP196-CZK203-DEM276-DJF262-DKK208-DOP214-DZD012-EEK233-EGP818-\
     ERN232-ESP724-ETB230-EUR978-FIM246-FJD242-FKP238-FRF250-GBP826-GEL981-\
@@ -109,7 +109,7 @@
 AT=EUR
 # AZERBAIJAN
 AZ=AZN
-# BAHAMAS
+# BAHAMAS (THE)
 BS=BSD
 # BAHRAIN
 BH=BHD
@@ -118,7 +118,7 @@
 # BARBADOS
 BB=BBD
 # BELARUS
-BY=BYR
+BY=BYN
 # BELGIUM
 BE=EUR
 # BELIZE
@@ -131,7 +131,7 @@
 BQ=USD
 # BHUTAN
 BT=BTN
-# BOLIVIA
+# BOLIVIA (PLURINATIONAL STATE OF)
 BO=BOB
 # BOSNIA AND HERZEGOVINA
 BA=BAM
@@ -141,7 +141,7 @@
 BV=NOK
 # BRAZIL
 BR=BRL
-# BRITISH INDIAN OCEAN TERRITORY
+# BRITISH INDIAN OCEAN TERRITORY (THE)
 IO=USD
 # BRUNEI DARUSSALAM
 BN=BND
@@ -159,9 +159,9 @@
 CA=CAD
 # CAPE VERDE
 CV=CVE
-# CAYMAN ISLANDS
+# CAYMAN ISLANDS (THE)
 KY=KYD
-# CENTRAL AFRICAN REPUBLIC
+# CENTRAL AFRICAN REPUBLIC (THE)
 CF=XAF
 # CHAD
 TD=XAF
@@ -171,17 +171,17 @@
 CN=CNY
 # CHRISTMAS ISLAND
 CX=AUD
-# COCOS (KEELING) ISLANDS
+# COCOS (KEELING) ISLANDS (THE)
 CC=AUD
 # COLOMBIA
 CO=COP
-# COMOROS
+# COMOROS (THE)
 KM=KMF
-# CONGO
+# CONGO (THE)
 CG=XAF
-# CONGO, THE DEMOCRATIC REPUBLIC OF THE
+# CONGO (THE DEMOCRATIC REPUBLIC OF THE)
 CD=CDF
-# COOK ISLANDS
+# COOK ISLANDS (THE)
 CK=NZD
 # COSTA RICA
 CR=CRC
@@ -195,7 +195,7 @@
 CW=ANG
 # CYPRUS
 CY=EUR
-# CZECH REPUBLIC
+# CZECH REPUBLIC (THE)
 CZ=CZK
 # DENMARK
 DK=DKK
@@ -203,7 +203,7 @@
 DJ=DJF
 # DOMINICA
 DM=XCD
-# DOMINICAN REPUBLIC
+# DOMINICAN REPUBLIC (THE)
 DO=DOP
 # ECUADOR
 EC=USD
@@ -220,9 +220,9 @@
 EE=EUR
 # ETHIOPIA
 ET=ETB
-# FALKLAND ISLANDS (MALVINAS)
+# FALKLAND ISLANDS (THE) [MALVINAS]
 FK=FKP
-# FAROE ISLANDS
+# FAROE ISLANDS (THE)
 FO=DKK
 # FIJI
 FJ=FJD
@@ -234,11 +234,11 @@
 GF=EUR
 # FRENCH POLYNESIA
 PF=XPF
-# FRENCH SOUTHERN TERRITORIES
+# FRENCH SOUTHERN TERRITORIES (THE)
 TF=EUR
 # GABON
 GA=XAF
-# GAMBIA
+# GAMBIA (THE)
 GM=GMD
 # GEORGIA
 GE=GEL
@@ -272,7 +272,7 @@
 HT=HTG
 # HEARD ISLAND AND MCDONALD ISLANDS
 HM=AUD
-# HOLY SEE (VATICAN CITY STATE)
+# HOLY SEE (THE)
 VA=EUR
 # HONDURAS
 HN=HNL
@@ -286,7 +286,7 @@
 IN=INR
 # INDONESIA
 ID=IDR
-# IRAN, ISLAMIC REPUBLIC OF
+# IRAN (ISLAMIC REPUBLIC OF)
 IR=IRR
 # IRAQ
 IQ=IQD
@@ -312,15 +312,15 @@
 KE=KES
 # KIRIBATI
 KI=AUD
-# KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF
+# KOREA (THE DEMOCRATIC PEOPLE'S REPUBLIC OF)
 KP=KPW
-# KOREA, REPUBLIC OF
+# KOREA (THE REPUBLIC OF)
 KR=KRW
 # KUWAIT
 KW=KWD
 # KYRGYZSTAN
 KG=KGS
-# LAO PEOPLE'S DEMOCRATIC REPUBLIC
+# LAO PEOPLE'S DEMOCRATIC REPUBLIC (THE)
 LA=LAK
 # LATVIA
 LV=LVL;2013-12-31-22-00-00;EUR
@@ -340,7 +340,7 @@
 LU=EUR
 # MACAU
 MO=MOP
-# MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF
+# MACEDONIA (THE FORMER YUGOSLAV REPUBLIC OF)
 MK=MKD
 # MADAGASCAR
 MG=MGA
@@ -354,7 +354,7 @@
 ML=XOF
 # MALTA
 MT=EUR
-# MARSHALL ISLANDS
+# MARSHALL ISLANDS (THE)
 MH=USD
 # MARTINIQUE
 MQ=EUR
@@ -366,9 +366,9 @@
 YT=EUR
 # MEXICO
 MX=MXN
-# MICRONESIA, FEDERATED STATES OF
+# MICRONESIA (FEDERATED STATES OF)
 FM=USD
-# MOLDOVA, REPUBLIC OF
+# MOLDOVA (THE REPUBLIC OF)
 MD=MDL
 # MONACO
 MC=EUR
@@ -390,7 +390,7 @@
 NR=AUD
 # NEPAL
 NP=NPR
-# NETHERLANDS
+# NETHERLANDS (THE)
 NL=EUR
 # NETHERLANDS ANTILLES
 AN=ANG
@@ -400,7 +400,7 @@
 NZ=NZD
 # NICARAGUA
 NI=NIO
-# NIGER
+# NIGER (THE)
 NE=XOF
 # NIGERIA
 NG=NGN
@@ -408,7 +408,7 @@
 NU=NZD
 # NORFOLK ISLAND
 NF=AUD
-# NORTHERN MARIANA ISLANDS
+# NORTHERN MARIANA ISLANDS (THE)
 MP=USD
 # NORWAY
 NO=NOK
@@ -428,7 +428,7 @@
 PY=PYG
 # PERU
 PE=PEN
-# PHILIPPINES
+# PHILIPPINES (THE)
 PH=PHP
 # PITCAIRN
 PN=NZD
@@ -444,7 +444,7 @@
 RE=EUR
 # ROMANIA
 RO=RON
-# RUSSIAN FEDERATION
+# RUSSIAN FEDERATION (THE)
 RU=RUB
 # RWANDA
 RW=RWF
@@ -500,7 +500,7 @@
 ES=EUR
 # SRI LANKA
 LK=LKR
-# SUDAN
+# SUDAN (THE)
 SD=SDG
 # SURINAME
 SR=SRD
@@ -516,7 +516,7 @@
 CH=CHF
 # SYRIAN ARAB REPUBLIC
 SY=SYP
-# TAIWAN
+# TAIWAN (PROVINCE OF CHINA)
 TW=TWD
 # TAJIKISTAN
 TJ=TJS
@@ -540,7 +540,7 @@
 TR=TRY
 # TURKMENISTAN
 TM=TMT
-# TURKS AND CAICOS ISLANDS
+# TURKS AND CAICOS ISLANDS (THE)
 TC=USD
 # TUVALU
 TV=AUD
@@ -548,13 +548,13 @@
 UG=UGX
 # UKRAINE
 UA=UAH
-# UNITED ARAB EMIRATES
+# UNITED ARAB EMIRATES (THE)
 AE=AED
-# UNITED KINGDOM
+# UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)
 GB=GBP
-# UNITED STATES
+# UNITED STATES OF AMERICA (THE)
 US=USD
-# UNITED STATES MINOR OUTLYING ISLANDS
+# UNITED STATES MINOR OUTLYING ISLANDS (THE)
 UM=USD
 # URUGUAY
 UY=UYU
@@ -562,7 +562,7 @@
 UZ=UZS
 # VANUATU
 VU=VUV
-# VENEZUELA
+# VENEZUELA (BOLIVARIAN REPUBLIC OF)
 VE=VEF
 # VIET NAM
 VN=VND
diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java
index fed0aa4..d94c5b0 100644
--- a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java
@@ -1655,7 +1655,24 @@
      * Removes all of the mappings from this map.
      */
     public void clear() {
-        initialize();
+        for (;;) {
+            Node<K,V> b, n;
+            HeadIndex<K,V> h = head, d = (HeadIndex<K,V>)h.down;
+            if (d != null)
+                casHead(h, d);            // remove levels
+            else if ((b = h.node) != null && (n = b.next) != null) {
+                Node<K,V> f = n.next;     // remove values
+                if (n == b.next) {
+                    Object v = n.value;
+                    if (v == null)
+                        n.helpDelete(b, f);
+                    else if (n.casValue(v, null) && n.appendMarker(f))
+                        b.casNext(n, f);
+                }
+            }
+            else
+                break;
+        }
     }
 
     /**
diff --git a/jdk/src/share/classes/java/util/concurrent/ThreadLocalRandom.java b/jdk/src/share/classes/java/util/concurrent/ThreadLocalRandom.java
index 95cc654..f50a47f 100644
--- a/jdk/src/share/classes/java/util/concurrent/ThreadLocalRandom.java
+++ b/jdk/src/share/classes/java/util/concurrent/ThreadLocalRandom.java
@@ -47,6 +47,7 @@
 import java.util.stream.IntStream;
 import java.util.stream.LongStream;
 import java.util.stream.StreamSupport;
+import sun.misc.VM;
 
 /**
  * A random number generator isolated to the current thread.  Like the
@@ -135,10 +136,8 @@
     private static final AtomicLong seeder = new AtomicLong(initialSeed());
 
     private static long initialSeed() {
-        String pp = java.security.AccessController.doPrivileged(
-                new sun.security.action.GetPropertyAction(
-                        "java.util.secureRandomSeed"));
-        if (pp != null && pp.equalsIgnoreCase("true")) {
+        String sec = VM.getSavedProperty("java.util.secureRandomSeed");
+        if (Boolean.parseBoolean(sec)) {
             byte[] seedBytes = java.security.SecureRandom.getSeed(8);
             long s = (long)(seedBytes[0]) & 0xffL;
             for (int i = 1; i < 8; ++i)
diff --git a/jdk/src/share/classes/java/util/regex/Pattern.java b/jdk/src/share/classes/java/util/regex/Pattern.java
index b5578b6..009a46e 100644
--- a/jdk/src/share/classes/java/util/regex/Pattern.java
+++ b/jdk/src/share/classes/java/util/regex/Pattern.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -1411,6 +1411,8 @@
         String result;
 
         i++;
+        if (i == normalizedPattern.length())
+            throw error("Unclosed character class");
         charClass.append("[");
         while(true) {
             int c = normalizedPattern.codePointAt(i);
diff --git a/jdk/src/share/classes/javax/crypto/JceSecurity.java b/jdk/src/share/classes/javax/crypto/JceSecurity.java
index 29823e7..5def277 100644
--- a/jdk/src/share/classes/javax/crypto/JceSecurity.java
+++ b/jdk/src/share/classes/javax/crypto/JceSecurity.java
@@ -29,12 +29,14 @@
 import java.util.jar.*;
 import java.io.*;
 import java.net.URL;
+import java.nio.file.*;
 import java.security.*;
 
 import java.security.Provider.Service;
 
 import sun.security.jca.*;
 import sun.security.jca.GetInstance.Instance;
+import sun.security.util.Debug;
 
 /**
  * This class instantiates implementations of JCE engine classes from
@@ -66,6 +68,9 @@
 
     private static final boolean isRestricted;
 
+    private static final Debug debug =
+                        Debug.getInstance("jca", "Cipher");
+
     /*
      * Don't let anyone instantiate this.
      */
@@ -204,7 +209,7 @@
 
     static {
         try {
-            NULL_URL = new URL("http://null.sun.com/");
+            NULL_URL = new URL("http://null.oracle.com/");
         } catch (Exception e) {
             throw new RuntimeException(e);
         }
@@ -239,14 +244,70 @@
         }
     }
 
+    /*
+     * This is called from within an doPrivileged block.
+     *
+     * Following logic is used to decide what policy files are selected.
+     *
+     * If the new Security property (crypto.policy) is set in the
+     * java.security file, or has been set dynamically using the
+     * Security.setProperty() call before the JCE framework has
+     * been initialized, that setting will be used.
+     * Remember - this property is not defined by default. A conscious
+     * user edit or an application call is required.
+     *
+     * Otherwise, if user has policy jar files installed in the legacy
+     * jre/lib/security/ directory, the JDK will honor whatever
+     * setting is set by those policy files. (legacy/current behavior)
+     *
+     * If none of the above 2 conditions are met, the JDK will default
+     * to using the limited crypto policy files found in the
+     * jre/lib/security/policy/limited/ directory
+     */
     private static void setupJurisdictionPolicies() throws Exception {
-        String javaHomeDir = System.getProperty("java.home");
-        String sep = File.separator;
-        String pathToPolicyJar = javaHomeDir + sep + "lib" + sep +
-            "security" + sep;
+        // Sanity check the crypto.policy Security property.  Single
+        // directory entry, no pseudo-directories (".", "..", leading/trailing
+        // path separators). normalize()/getParent() will help later.
+        String javaHomeProperty = System.getProperty("java.home");
+        String cryptoPolicyProperty = Security.getProperty("crypto.policy");
+        Path cpPath = (cryptoPolicyProperty == null) ? null :
+                Paths.get(cryptoPolicyProperty);
 
-        File exportJar = new File(pathToPolicyJar, "US_export_policy.jar");
-        File importJar = new File(pathToPolicyJar, "local_policy.jar");
+        if ((cpPath != null) && ((cpPath.getNameCount() != 1) ||
+                (cpPath.compareTo(cpPath.getFileName())) != 0)) {
+            throw new SecurityException(
+                    "Invalid policy directory name format: " +
+                            cryptoPolicyProperty);
+        }
+
+        if (cpPath == null) {
+            // Security property is not set, use default path
+            cpPath = Paths.get(javaHomeProperty, "lib", "security");
+        } else {
+            // populate with java.home
+            cpPath = Paths.get(javaHomeProperty, "lib", "security",
+                    "policy", cryptoPolicyProperty);
+        }
+
+        if (debug != null) {
+            debug.println("crypto policy directory: " + cpPath);
+        }
+
+        File exportJar = new File(cpPath.toFile(),"US_export_policy.jar");
+        File importJar = new File(cpPath.toFile(),"local_policy.jar");
+
+        if (cryptoPolicyProperty == null && (!exportJar.exists() ||
+                !importJar.exists())) {
+            // Compatibility set up. If crypto.policy is not defined.
+            // check to see if legacy jars exist in lib directory. If
+            // they don't exist, we default to limited policy mode.
+            cpPath = Paths.get(
+                    javaHomeProperty, "lib", "security", "policy", "limited");
+            // point to the new jar files in limited directory
+            exportJar = new File(cpPath.toFile(),"US_export_policy.jar");
+            importJar = new File(cpPath.toFile(),"local_policy.jar");
+        }
+
         URL jceCipherURL = ClassLoader.getSystemResource
                 ("javax/crypto/Cipher.class");
 
diff --git a/jdk/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java b/jdk/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java
index c9e2b28..21fd233 100644
--- a/jdk/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java
+++ b/jdk/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java
@@ -377,7 +377,7 @@
      * @return true if this ticket is forwardable, false if not.
      */
     public final boolean isForwardable() {
-        return flags[FORWARDABLE_TICKET_FLAG];
+        return flags == null? false: flags[FORWARDABLE_TICKET_FLAG];
     }
 
     /**
@@ -389,7 +389,7 @@
      * false otherwise.
      */
     public final boolean isForwarded() {
-        return flags[FORWARDED_TICKET_FLAG];
+        return flags == null? false: flags[FORWARDED_TICKET_FLAG];
     }
 
     /**
@@ -398,7 +398,7 @@
      * @return true if this ticket is proxiable, false if not.
      */
     public final boolean isProxiable() {
-        return flags[PROXIABLE_TICKET_FLAG];
+        return flags == null? false: flags[PROXIABLE_TICKET_FLAG];
     }
 
     /**
@@ -407,7 +407,7 @@
      * @return true if this ticket is a proxy-ticket, false if not.
      */
     public final boolean isProxy() {
-        return flags[PROXY_TICKET_FLAG];
+        return flags == null? false: flags[PROXY_TICKET_FLAG];
     }
 
 
@@ -417,7 +417,7 @@
      * @return true if this ticket is post-dated, false if not.
      */
     public final boolean isPostdated() {
-        return flags[POSTDATED_TICKET_FLAG];
+        return flags == null? false: flags[POSTDATED_TICKET_FLAG];
     }
 
     /**
@@ -428,7 +428,7 @@
      * @return true if this ticket is renewable, false if not.
      */
     public final boolean isRenewable() {
-        return flags[RENEWABLE_TICKET_FLAG];
+        return flags == null? false: flags[RENEWABLE_TICKET_FLAG];
     }
 
     /**
@@ -439,7 +439,7 @@
      * protocol, false if not.
      */
     public final boolean isInitial() {
-        return flags[INITIAL_TICKET_FLAG];
+        return flags == null? false: flags[INITIAL_TICKET_FLAG];
     }
 
     /**
@@ -479,7 +479,7 @@
      * @return the expiration time for this ticket's validity period.
      */
     public final java.util.Date getEndTime() {
-        return (Date) endTime.clone();
+        return (endTime == null) ? null : (Date) endTime.clone();
     }
 
     /**
@@ -515,7 +515,7 @@
 
     /** Determines if this ticket is still current.  */
     public boolean isCurrent() {
-        return (System.currentTimeMillis() <= getEndTime().getTime());
+        return endTime == null? false: (System.currentTimeMillis() <= endTime.getTime());
     }
 
     /**
@@ -634,8 +634,9 @@
     }
 
     public String toString() {
-        if (destroyed)
-            throw new IllegalStateException("This ticket is no longer valid");
+        if (destroyed) {
+            return "Destroyed KerberosTicket";
+        }
         StringBuffer caddrBuf = new StringBuffer();
         if (clientAddresses != null) {
             for (int i = 0; i < clientAddresses.length; i++) {
diff --git a/jdk/src/share/classes/javax/swing/JList.java b/jdk/src/share/classes/javax/swing/JList.java
index ab0955a..fc2499d 100644
--- a/jdk/src/share/classes/javax/swing/JList.java
+++ b/jdk/src/share/classes/javax/swing/JList.java
@@ -3052,7 +3052,7 @@
         public Accessible getAccessibleAt(Point p) {
             int i = locationToIndex(p);
             if (i >= 0) {
-                return new AccessibleJListChild(JList.this, i);
+                return new ActionableAccessibleJListChild(JList.this, i);
             } else {
                 return null;
             }
@@ -3079,7 +3079,7 @@
             if (i >= getModel().getSize()) {
                 return null;
             } else {
-                return new AccessibleJListChild(JList.this, i);
+                return new ActionableAccessibleJListChild(JList.this, i);
             }
         }
 
@@ -3184,7 +3184,7 @@
         protected class AccessibleJListChild extends AccessibleContext
                 implements Accessible, AccessibleComponent {
             private JList<E>     parent = null;
-            private int       indexInParent;
+            int indexInParent;
             private Component component = null;
             private AccessibleContext accessibleContext = null;
             private ListModel<E> listModel;
@@ -3204,7 +3204,7 @@
                 return getComponentAtIndex(indexInParent);
             }
 
-            private AccessibleContext getCurrentAccessibleContext() {
+            AccessibleContext getCurrentAccessibleContext() {
                 Component c = getComponentAtIndex(indexInParent);
                 if (c instanceof Accessible) {
                     return c.getAccessibleContext();
@@ -3370,10 +3370,6 @@
                 }
             }
 
-            public AccessibleAction getAccessibleAction() {
-                return getCurrentAccessibleContext().getAccessibleAction();
-            }
-
            /**
             * Get the AccessibleComponent associated with this object.  In the
             * implementation of the Java Accessibility API for this class,
@@ -3387,15 +3383,18 @@
             }
 
             public AccessibleSelection getAccessibleSelection() {
-                return getCurrentAccessibleContext().getAccessibleSelection();
+                AccessibleContext ac = getCurrentAccessibleContext();
+                return ac != null ? ac.getAccessibleSelection() : null;
             }
 
             public AccessibleText getAccessibleText() {
-                return getCurrentAccessibleContext().getAccessibleText();
+                AccessibleContext ac = getCurrentAccessibleContext();
+                return ac != null ? ac.getAccessibleText() : null;
             }
 
             public AccessibleValue getAccessibleValue() {
-                return getCurrentAccessibleContext().getAccessibleValue();
+                AccessibleContext ac = getCurrentAccessibleContext();
+                return ac != null ? ac.getAccessibleValue() : null;
             }
 
 
@@ -3588,7 +3587,13 @@
 
             public Point getLocationOnScreen() {
                 if (parent != null) {
-                    Point listLocation = parent.getLocationOnScreen();
+                    Point listLocation;
+                    try {
+                        listLocation = parent.getLocationOnScreen();
+                    } catch (IllegalComponentStateException e) {
+                        // This can happen if the component isn't visisble
+                        return null;
+                    }
                     Point componentLocation = parent.indexToLocation(indexInParent);
                     if (componentLocation != null) {
                         componentLocation.translate(listLocation.x, listLocation.y);
@@ -3728,6 +3733,57 @@
                     return null;
                 }
             }
+
         } // inner class AccessibleJListChild
+
+        private class ActionableAccessibleJListChild
+            extends AccessibleJListChild
+            implements AccessibleAction {
+
+            ActionableAccessibleJListChild(JList<E> parent, int indexInParent) {
+                super(parent, indexInParent);
+            }
+
+            @Override
+            public AccessibleAction getAccessibleAction() {
+                AccessibleContext ac = getCurrentAccessibleContext();
+                if (ac == null) {
+                    return null;
+                } else {
+                    AccessibleAction aa = ac.getAccessibleAction();
+                    if (aa != null) {
+                        return aa;
+                    } else {
+                        return this;
+                    }
+                }
+            }
+
+            @Override
+            public boolean doAccessibleAction(int i) {
+                if (i == 0) {
+                    JList.this.setSelectedIndex(indexInParent);
+                    return true;
+                } else {
+                    return false;
+                }
+            }
+
+            @Override
+            public String getAccessibleActionDescription(int i) {
+                if (i == 0) {
+                    return UIManager.getString("AbstractButton.clickText");
+                } else {
+                    return null;
+                }
+            }
+
+            @Override
+            public int getAccessibleActionCount() {
+                return 1;
+            }
+
+        } // inner class ActionableAccessibleJListChild
+
     } // inner class AccessibleJList
 }
diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java
index 9c31265..8e99c38 100644
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -80,6 +80,14 @@
      * This method is here so that a subclass could do Label specific
      * layout and to shorten the method name a little.
      *
+     * @param label an instance of {@code JLabel}
+     * @param fontMetrics a font metrics
+     * @param text a text
+     * @param icon an icon
+     * @param viewR a bounding rectangle to lay out label
+     * @param iconR a bounding rectangle to lay out icon
+     * @param textR a bounding rectangle to lay out text
+     * @return a possibly clipped version of the compound labels string
      * @see SwingUtilities#layoutCompoundLabel
      */
     protected String layoutCL(
@@ -109,6 +117,11 @@
     /**
      * Paint clippedText at textX, textY with the labels foreground color.
      *
+     * @param l an instance of {@code JLabel}
+     * @param g an instance of {@code Graphics}
+     * @param s a text
+     * @param textX an X coordinate
+     * @param textY an Y coordinate
      * @see #paint
      * @see #paintDisabledText
      */
@@ -125,6 +138,11 @@
      * Paint clippedText at textX, textY with background.lighter() and then
      * shifted down and to the right by one pixel with background.darker().
      *
+     * @param l an instance of {@code JLabel}
+     * @param g an instance of {@code Graphics}
+     * @param s a text
+     * @param textX an X coordinate
+     * @param textY an Y coordinate
      * @see #paint
      * @see #paintEnabledText
      */
@@ -329,26 +347,46 @@
 
 
     public void uninstallUI(JComponent c) {
-        uninstallDefaults((JLabel)c);
-        uninstallComponents((JLabel)c);
-        uninstallListeners((JLabel)c);
-        uninstallKeyboardActions((JLabel)c);
+        uninstallDefaults((JLabel) c);
+        uninstallComponents((JLabel) c);
+        uninstallListeners((JLabel) c);
+        uninstallKeyboardActions((JLabel) c);
     }
 
-     protected void installDefaults(JLabel c){
-         LookAndFeel.installColorsAndFont(c, "Label.background", "Label.foreground", "Label.font");
-         LookAndFeel.installProperty(c, "opaque", Boolean.FALSE);
-      }
+    /**
+     * Installs default properties.
+     *
+     * @param c an instance of {@code JLabel}
+     */
+    protected void installDefaults(JLabel c){
+        LookAndFeel.installColorsAndFont(c, "Label.background", "Label.foreground", "Label.font");
+        LookAndFeel.installProperty(c, "opaque", Boolean.FALSE);
+    }
 
+    /**
+     * Registers listeners.
+     *
+     * @param c an instance of {@code JLabel}
+     */
     protected void installListeners(JLabel c){
         c.addPropertyChangeListener(this);
     }
 
+    /**
+     * Registers components.
+     *
+     * @param c an instance of {@code JLabel}
+     */
     protected void installComponents(JLabel c){
         BasicHTML.updateRenderer(c, c.getText());
         c.setInheritsPopupMenu(true);
     }
 
+    /**
+     * Registers keyboard actions.
+     *
+     * @param l an instance of {@code JLabel}
+     */
     protected void installKeyboardActions(JLabel l) {
         int dka = l.getDisplayedMnemonic();
         Component lf = l.getLabelFor();
@@ -374,17 +412,37 @@
         }
     }
 
+    /**
+     * Uninstalls default properties.
+     *
+     * @param c an instance of {@code JLabel}
+     */
     protected void uninstallDefaults(JLabel c){
     }
 
+    /**
+     * Unregisters listeners.
+     *
+     * @param c an instance of {@code JLabel}
+     */
     protected void uninstallListeners(JLabel c){
         c.removePropertyChangeListener(this);
     }
 
+    /**
+     * Unregisters components.
+     *
+     * @param c an instance of {@code JLabel}
+     */
     protected void uninstallComponents(JLabel c){
         BasicHTML.updateRenderer(c, "");
     }
 
+    /**
+     * Unregisters keyboard actions.
+     *
+     * @param c an instance of {@code JLabel}
+     */
     protected void uninstallKeyboardActions(JLabel c) {
         SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_FOCUSED, null);
         SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_IN_FOCUSED_WINDOW,
@@ -392,6 +450,12 @@
         SwingUtilities.replaceUIActionMap(c, null);
     }
 
+    /**
+     * Returns an instance of {@code BasicLabelUI}.
+     *
+     * @param c a component
+     * @return an instance of {@code BasicLabelUI}
+     */
     public static ComponentUI createUI(JComponent c) {
         if (System.getSecurityManager() != null) {
             AppContext appContext = AppContext.getAppContext();
@@ -440,7 +504,7 @@
                 doPress(label);
             }
             else if (key == RELEASE) {
-                doRelease(label);
+                doRelease(label, e.getActionCommand() != null);
             }
         }
 
@@ -453,33 +517,77 @@
                     SwingUtilities.replaceUIInputMap(label, JComponent.WHEN_FOCUSED, inputMap);
                 }
                 int dka = label.getDisplayedMnemonic();
-                inputMap.put(KeyStroke.getKeyStroke(dka, BasicLookAndFeel.getFocusAcceleratorKeyMask(), true), RELEASE);
+                putOnRelease(inputMap, dka, BasicLookAndFeel
+                        .getFocusAcceleratorKeyMask());
                 // Need this when the sticky keys are enabled
-                inputMap.put(KeyStroke.getKeyStroke(dka, 0, true), RELEASE);
+                putOnRelease(inputMap, dka, 0);
                 // Need this if ALT is released before the accelerator
-                inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ALT, 0, true), RELEASE);
+                putOnRelease(inputMap, KeyEvent.VK_ALT, 0);
                 label.requestFocus();
             }
         }
 
-        private void doRelease(JLabel label) {
+        private void doRelease(JLabel label, boolean isCommand) {
             Component labelFor = label.getLabelFor();
             if (labelFor != null && labelFor.isEnabled()) {
-                InputMap inputMap = SwingUtilities.getUIInputMap(label, JComponent.WHEN_FOCUSED);
-                if (inputMap != null) {
-                    // inputMap should never be null.
+                if (label.hasFocus()) {
+                    InputMap inputMap = SwingUtilities.getUIInputMap(label,
+                            JComponent.WHEN_FOCUSED);
+                    if (inputMap != null) {
+                        // inputMap should never be null.
+                        int dka = label.getDisplayedMnemonic();
+                        removeOnRelease(inputMap, dka, BasicLookAndFeel
+                                .getFocusAcceleratorKeyMask());
+                        removeOnRelease(inputMap, dka, 0);
+                        removeOnRelease(inputMap, KeyEvent.VK_ALT, 0);
+                    }
+                    inputMap = SwingUtilities.getUIInputMap(label,
+                            JComponent.WHEN_IN_FOCUSED_WINDOW);
+                    if (inputMap == null) {
+                        inputMap = new InputMapUIResource();
+                        SwingUtilities.replaceUIInputMap(label,
+                                JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);
+                    }
                     int dka = label.getDisplayedMnemonic();
-                    inputMap.remove(KeyStroke.getKeyStroke(dka, BasicLookAndFeel.getFocusAcceleratorKeyMask(), true));
-                    inputMap.remove(KeyStroke.getKeyStroke(dka, 0, true));
-                    inputMap.remove(KeyStroke.getKeyStroke(KeyEvent.VK_ALT, 0, true));
-                }
-                if (labelFor instanceof Container &&
-                        ((Container) labelFor).isFocusCycleRoot()) {
-                    labelFor.requestFocus();
+                    if (isCommand) {
+                        putOnRelease(inputMap, KeyEvent.VK_ALT, 0);
+                    } else {
+                        putOnRelease(inputMap, dka, BasicLookAndFeel
+                                .getFocusAcceleratorKeyMask());
+                        // Need this when the sticky keys are enabled
+                        putOnRelease(inputMap, dka, 0);
+                    }
+                    if (labelFor instanceof Container &&
+                            ((Container) labelFor).isFocusCycleRoot()) {
+                        labelFor.requestFocus();
+                    } else {
+                        SwingUtilities2.compositeRequestFocus(labelFor);
+                    }
                 } else {
-                    SwingUtilities2.compositeRequestFocus(labelFor);
+                    InputMap inputMap = SwingUtilities.getUIInputMap(label,
+                            JComponent.WHEN_IN_FOCUSED_WINDOW);
+                    int dka = label.getDisplayedMnemonic();
+                    if (inputMap != null) {
+                        if (isCommand) {
+                            removeOnRelease(inputMap, dka, BasicLookAndFeel
+                                    .getFocusAcceleratorKeyMask());
+                            removeOnRelease(inputMap, dka, 0);
+                        } else {
+                            removeOnRelease(inputMap, KeyEvent.VK_ALT, 0);
+                        }
+                    }
                 }
             }
         }
+
+        private void putOnRelease(InputMap inputMap, int keyCode, int modifiers) {
+            inputMap.put(KeyStroke.getKeyStroke(keyCode, modifiers, true),
+                    RELEASE);
+        }
+
+        private void removeOnRelease(InputMap inputMap, int keyCode, int modifiers) {
+            inputMap.remove(KeyStroke.getKeyStroke(keyCode, modifiers, true));
+        }
+
     }
 }
diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java
index 1c6f496..fd94c96 100644
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java
@@ -180,6 +180,15 @@
             arrowIcon instanceof UIResource) {
             arrowIcon = UIManager.getIcon(prefix + ".arrowIcon");
         }
+        updateCheckIcon();
+    }
+
+    /**
+     * Updates check Icon based on column layout
+     */
+    private void updateCheckIcon() {
+        String prefix = getPropertyPrefix();
+
         if (checkIcon == null ||
             checkIcon instanceof UIResource) {
             checkIcon = UIManager.getIcon(prefix + ".checkIcon");
@@ -190,8 +199,8 @@
                     BasicGraphicsUtils.isLeftToRight(menuItem), menuItem);
             if (isColumnLayout) {
                 MenuItemCheckIconFactory iconFactory =
-                    (MenuItemCheckIconFactory) UIManager.get(prefix
-                        + ".checkIconFactory");
+                        (MenuItemCheckIconFactory) UIManager.get(prefix
+                                + ".checkIconFactory");
                 if (iconFactory != null
                         && MenuItemLayoutHelper.useCheckAndArrow(menuItem)
                         && iconFactory.isCompatible(checkIcon, prefix)) {
@@ -966,6 +975,8 @@
                 BasicHTML.updateRenderer(lbl, text);
             } else if (name  == "iconTextGap") {
                 defaultTextIconGap = ((Number)e.getNewValue()).intValue();
+            } else if (name == "horizontalTextPosition") {
+                updateCheckIcon();
             }
         }
     }
diff --git a/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java b/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java
index 21f5703..f7fbdaa 100644
--- a/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java
@@ -2021,8 +2021,11 @@
             }
 
             /* To account for extra read()'s that happened */
-            for (int j = 0; j < i; j++) {
-                addString(charsToAdd[j]);
+            if (i > 0) {
+                for (int j = 0; j < i; j++) {
+                    addString(charsToAdd[j]);
+                }
+                continue;
             }
             switch (ch) {
             case -1:
diff --git a/jdk/src/share/classes/sun/awt/CustomCursor.java b/jdk/src/share/classes/sun/awt/CustomCursor.java
index a3863e9..f73a98b 100644
--- a/jdk/src/share/classes/sun/awt/CustomCursor.java
+++ b/jdk/src/share/classes/sun/awt/CustomCursor.java
@@ -65,7 +65,8 @@
 
         // Scale image to nearest supported size.
         Dimension nativeSize = toolkit.getBestCursorSize(width, height);
-        if (nativeSize.width != width || nativeSize.height != height) {
+        if ((nativeSize.width != width || nativeSize.height != height) &&
+            (nativeSize.width != 0 && nativeSize.height != 0)) {
             cursor = cursor.getScaledInstance(nativeSize.width,
                                               nativeSize.height,
                                               Image.SCALE_DEFAULT);
diff --git a/jdk/src/share/classes/sun/font/CompositeFont.java b/jdk/src/share/classes/sun/font/CompositeFont.java
index a7df046..fa925e5 100644
--- a/jdk/src/share/classes/sun/font/CompositeFont.java
+++ b/jdk/src/share/classes/sun/font/CompositeFont.java
@@ -93,20 +93,25 @@
          * better that it is handled internally to the CompositeFont class.
          */
         if (fm.getEUDCFont() != null) {
+            int msCnt = numMetricsSlots;
+            int fbCnt = numSlots - msCnt;
             numSlots++;
             if (componentNames != null) {
                 componentNames = new String[numSlots];
-                System.arraycopy(compNames, 0, componentNames, 0, numSlots-1);
-                componentNames[numSlots-1] =
-                    fm.getEUDCFont().getFontName(null);
+                System.arraycopy(compNames, 0, componentNames, 0, msCnt);
+                componentNames[msCnt] = fm.getEUDCFont().getFontName(null);
+                System.arraycopy(compNames, msCnt,
+                                 componentNames, msCnt+1, fbCnt);
             }
             if (componentFileNames != null) {
                 componentFileNames = new String[numSlots];
                 System.arraycopy(compFileNames, 0,
-                                  componentFileNames, 0, numSlots-1);
+                                  componentFileNames, 0, msCnt);
+                System.arraycopy(compFileNames, msCnt,
+                                  componentFileNames, msCnt+1, fbCnt);
             }
             components = new PhysicalFont[numSlots];
-            components[numSlots-1] = fm.getEUDCFont();
+            components[msCnt] = fm.getEUDCFont();
             deferredInitialisation = new boolean[numSlots];
             if (defer) {
                 for (int i=0; i<numSlots-1; i++) {
diff --git a/jdk/src/share/classes/sun/font/FontFamily.java b/jdk/src/share/classes/sun/font/FontFamily.java
index e319886..a0d8032 100644
--- a/jdk/src/share/classes/sun/font/FontFamily.java
+++ b/jdk/src/share/classes/sun/font/FontFamily.java
@@ -27,6 +27,7 @@
 
 import java.io.File;
 import java.awt.Font;
+import java.io.IOException;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.concurrent.ConcurrentHashMap;
@@ -132,6 +133,16 @@
 
         FileFont newFont = (FileFont)font;
         File newDir = (new File(newFont.platName)).getParentFile();
+        if (existDir != null) {
+            try {
+                existDir = existDir.getCanonicalFile();
+            } catch (IOException ignored) {}
+        }
+        if (newDir != null) {
+            try {
+                newDir = newDir.getCanonicalFile();
+            } catch (IOException ignored) {}
+        }
         return java.util.Objects.equals(newDir, existDir);
     }
 
diff --git a/jdk/src/share/classes/sun/management/DiagnosticCommandImpl.java b/jdk/src/share/classes/sun/management/DiagnosticCommandImpl.java
index eeeee9a..faae805 100644
--- a/jdk/src/share/classes/sun/management/DiagnosticCommandImpl.java
+++ b/jdk/src/share/classes/sun/management/DiagnosticCommandImpl.java
@@ -312,7 +312,7 @@
                                                    "Diagnostic Framework Notification");
             }
         }
-        return notifInfo;
+        return notifInfo.clone();
     }
 
     private static long seqNumber = 0;
diff --git a/jdk/src/share/classes/sun/misc/Launcher.java b/jdk/src/share/classes/sun/misc/Launcher.java
index d4d9657..37bc190 100644
--- a/jdk/src/share/classes/sun/misc/Launcher.java
+++ b/jdk/src/share/classes/sun/misc/Launcher.java
@@ -29,6 +29,7 @@
 import java.io.IOException;
 import java.io.FilePermission;
 import java.net.*;
+import java.nio.file.Paths;
 import java.util.HashSet;
 import java.util.StringTokenizer;
 import java.util.Set;
@@ -218,7 +219,9 @@
                     // skip this URL if cannot convert it to URI
                     continue;
                 }
-                File dir = new File(uri).getParentFile();
+                // Use the Paths.get(uri) call in order to handle
+                // UNC based file name conversion correctly.
+                File dir = Paths.get(uri).toFile().getParentFile();
                 if (dir != null && !dir.equals(prevDir)) {
                     // Look in architecture-specific subdirectory first
                     // Read from the saved system properties to avoid deadlock
diff --git a/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java b/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
index 65f4b19..9cd81c0 100644
--- a/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
+++ b/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
@@ -1718,7 +1718,7 @@
      */
     public InputStream nameList(String path) throws sun.net.ftp.FtpProtocolException, IOException {
         Socket s;
-        s = openDataConnection("NLST " + path);
+        s = openDataConnection(path == null ? "NLST" : "NLST " + path);
         if (s != null) {
             return createInputStream(s.getInputStream());
         }
diff --git a/jdk/src/share/classes/sun/net/spi/DefaultProxySelector.java b/jdk/src/share/classes/sun/net/spi/DefaultProxySelector.java
index f7018ed..36db753 100644
--- a/jdk/src/share/classes/sun/net/spi/DefaultProxySelector.java
+++ b/jdk/src/share/classes/sun/net/spi/DefaultProxySelector.java
@@ -32,13 +32,14 @@
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.StringTokenizer;
 import java.io.IOException;
-import sun.misc.RegexpPool;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.util.StringJoiner;
+import java.util.regex.Pattern;
 import sun.net.NetProperties;
 import sun.net.SocksProxy;
+import static java.util.regex.Pattern.quote;
 
 /**
  * Supports proxy settings using system properties This proxy selector
@@ -107,7 +108,7 @@
 
     /**
      * How to deal with "non proxy hosts":
-     * since we do have to generate a RegexpPool we don't want to do that if
+     * since we do have to generate a pattern we don't want to do that if
      * it's not necessary. Therefore we do cache the result, on a per-protocol
      * basis, and change it only when the "source", i.e. the system property,
      * did change.
@@ -119,17 +120,17 @@
         static final String defStringVal = "localhost|127.*|[::1]|0.0.0.0|[::0]";
 
         String hostsSource;
-        RegexpPool hostsPool;
+        Pattern pattern;
         final String property;
         final String defaultVal;
         static NonProxyInfo ftpNonProxyInfo = new NonProxyInfo("ftp.nonProxyHosts", null, null, defStringVal);
         static NonProxyInfo httpNonProxyInfo = new NonProxyInfo("http.nonProxyHosts", null, null, defStringVal);
         static NonProxyInfo socksNonProxyInfo = new NonProxyInfo("socksNonProxyHosts", null, null, defStringVal);
 
-        NonProxyInfo(String p, String s, RegexpPool pool, String d) {
+        NonProxyInfo(String p, String s, Pattern pattern, String d) {
             property = p;
             hostsSource = s;
-            hostsPool = pool;
+            this.pattern = pattern;
             defaultVal = d;
         }
     }
@@ -255,7 +256,7 @@
                                             nphosts = nprop.defaultVal;
                                         } else {
                                             nprop.hostsSource = null;
-                                            nprop.hostsPool = null;
+                                            nprop.pattern = null;
                                         }
                                     } else if (nphosts.length() != 0) {
                                         // add the required default patterns
@@ -266,20 +267,11 @@
                                     }
                                     if (nphosts != null) {
                                         if (!nphosts.equals(nprop.hostsSource)) {
-                                            RegexpPool pool = new RegexpPool();
-                                            StringTokenizer st = new StringTokenizer(nphosts, "|", false);
-                                            try {
-                                                while (st.hasMoreTokens()) {
-                                                    pool.add(st.nextToken().toLowerCase(), Boolean.TRUE);
-                                                }
-                                            } catch (sun.misc.REException ex) {
-                                            }
-                                            nprop.hostsPool = pool;
+                                            nprop.pattern = toPattern(nphosts);
                                             nprop.hostsSource = nphosts;
                                         }
                                     }
-                                    if (nprop.hostsPool != null &&
-                                        nprop.hostsPool.match(urlhost) != null) {
+                                    if (shouldNotUseProxyFor(nprop.pattern, urlhost)) {
                                         return Proxy.NO_PROXY;
                                     }
                                 }
@@ -355,4 +347,49 @@
 
     private native static boolean init();
     private synchronized native Proxy getSystemProxy(String protocol, String host);
+
+    /**
+     * @return {@code true} if given this pattern for non-proxy hosts and this
+     *         urlhost the proxy should NOT be used to access this urlhost
+     */
+    static boolean shouldNotUseProxyFor(Pattern pattern, String urlhost) {
+        if (pattern == null || urlhost.isEmpty())
+            return false;
+        boolean matches = pattern.matcher(urlhost).matches();
+        return matches;
+    }
+
+    /**
+     * @param mask non-null mask
+     * @return {@link java.util.regex.Pattern} corresponding to this mask
+     *         or {@code null} in case mask should not match anything
+     */
+    static Pattern toPattern(String mask) {
+        boolean disjunctionEmpty = true;
+        StringJoiner joiner = new StringJoiner("|");
+        for (String disjunct : mask.split("\\|")) {
+            if (disjunct.isEmpty())
+                continue;
+            disjunctionEmpty = false;
+            String regex = disjunctToRegex(disjunct.toLowerCase());
+            joiner.add(regex);
+        }
+        return disjunctionEmpty ? null : Pattern.compile(joiner.toString());
+    }
+
+    /**
+     * @param disjunct non-null mask disjunct
+     * @return java regex string corresponding to this mask
+     */
+    static String disjunctToRegex(String disjunct) {
+        String regex;
+        if (disjunct.startsWith("*")) {
+            regex = ".*" + quote(disjunct.substring(1));
+        } else if (disjunct.endsWith("*")) {
+            regex = quote(disjunct.substring(0, disjunct.length() - 1)) + ".*";
+        } else {
+            regex = quote(disjunct);
+        }
+        return regex;
+    }
 }
diff --git a/jdk/src/share/classes/sun/net/www/protocol/jar/JarURLConnection.java b/jdk/src/share/classes/sun/net/www/protocol/jar/JarURLConnection.java
index 509b712..d7c4424 100644
--- a/jdk/src/share/classes/sun/net/www/protocol/jar/JarURLConnection.java
+++ b/jdk/src/share/classes/sun/net/www/protocol/jar/JarURLConnection.java
@@ -125,7 +125,9 @@
              * to get the jarFile, and set it as our permission.
              */
             if (getUseCaches()) {
+                boolean oldUseCaches = jarFileURLConnection.getUseCaches();
                 jarFileURLConnection = factory.getConnection(jarFile);
+                jarFileURLConnection.setUseCaches(oldUseCaches);
             }
 
             if ((entryName != null)) {
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/NSPrintInfo.java b/jdk/src/share/classes/sun/print/DialogOnTop.java
similarity index 62%
rename from jdk/src/macosx/classes/sun/lwawt/macosx/NSPrintInfo.java
rename to jdk/src/share/classes/sun/print/DialogOnTop.java
index 5698864..821e4e0 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/NSPrintInfo.java
+++ b/jdk/src/share/classes/sun/print/DialogOnTop.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 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,41 +23,42 @@
  * questions.
  */
 
-package sun.lwawt.macosx;
+package sun.print;
 
+import javax.print.attribute.Attribute;
+import javax.print.attribute.PrintRequestAttribute;
 
-import java.io.*;
-import javax.print.attribute.*;
+/*
+ * An implementation class used to request the dialog be set always-on-top.
+ * It needs to be read and honoured by the dialog code which will use
+ * java.awt.Window.setAlwaysOnTop(true) in cases where it is supported.
+ */
+public class DialogOnTop implements PrintRequestAttribute {
 
-public final class NSPrintInfo implements PrintJobAttribute, PrintRequestAttribute, Serializable, Cloneable {
+    private static final long serialVersionUID = -1901909867156076547L;
 
-    private long fNSPrintInfo;
+    long id;
 
-    public NSPrintInfo(long nsPrintInfo) {
-        fNSPrintInfo = nsPrintInfo;
+    public DialogOnTop() {
     }
 
-    public long getValue() {
-        return fNSPrintInfo;
-    }
-
-    public boolean equals(Object object) {
-        return (object != null && object instanceof NSPrintInfo && fNSPrintInfo == ((NSPrintInfo)object).fNSPrintInfo);
-    }
-
-    public int hashCode() {
-        return (int)fNSPrintInfo;
-    }
-
-    public String toString() {
-        return "" + fNSPrintInfo;
+    public DialogOnTop(long id) {
+        this.id = id;
     }
 
     public final Class<? extends Attribute> getCategory() {
-        return NSPrintInfo.class;
+        return DialogOnTop.class;
+    }
+
+    public long getID() {
+        return id;
     }
 
     public final String getName() {
-        return "nsPrintInfo";
+        return "dialog-on-top";
+    }
+
+    public String toString() {
+       return "dialog-on-top";
     }
 }
diff --git a/jdk/src/share/classes/sun/print/RasterPrinterJob.java b/jdk/src/share/classes/sun/print/RasterPrinterJob.java
index 1bb3dad..b38cb68 100644
--- a/jdk/src/share/classes/sun/print/RasterPrinterJob.java
+++ b/jdk/src/share/classes/sun/print/RasterPrinterJob.java
@@ -742,7 +742,19 @@
         }
         updatePageAttributes(service, page);
 
-        PageFormat newPage = pageDialog(attributes);
+        PageFormat newPage = null;
+        DialogTypeSelection dts =
+            (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
+        if (dts == DialogTypeSelection.NATIVE) {
+            // Remove DialogTypeSelection.NATIVE to prevent infinite loop in
+            // RasterPrinterJob.
+            attributes.remove(DialogTypeSelection.class);
+            newPage = pageDialog(attributes);
+            // restore attribute
+            attributes.add(DialogTypeSelection.NATIVE);
+        } else {
+            newPage = pageDialog(attributes);
+        }
 
         if (newPage == null) {
             return page;
@@ -767,8 +779,17 @@
         // Check for native, note that default dialog is COMMON.
         if (dlg == DialogTypeSelection.NATIVE) {
             PrintService pservice = getPrintService();
-            PageFormat page = pageDialog(attributeToPageFormat(pservice,
-                                                               attributes));
+            PageFormat pageFrmAttrib = attributeToPageFormat(pservice,
+                                                             attributes);
+            setParentWindowID(attributes);
+            PageFormat page = pageDialog(pageFrmAttrib);
+            clearParentWindowID();
+
+            // If user cancels the dialog, pageDialog() will return the original
+            // page object and as per spec, we should return null in that case.
+            if (page == pageFrmAttrib) {
+                return null;
+            }
             updateAttributesWithPageFormat(pservice, page, attributes);
             return page;
         }
@@ -797,6 +818,10 @@
             return null;
         }
 
+        if (onTop != null) {
+            attributes.add(onTop);
+        }
+
         ServiceDialog pageDialog = new ServiceDialog(gc, x, y, service,
                                        DocFlavor.SERVICE_FORMATTED.PAGEABLE,
                                        attributes, (Frame)null);
@@ -861,7 +886,9 @@
 
             }
 
+            setParentWindowID(attributes);
             boolean ret = printDialog();
+            clearParentWindowID();
             this.attributes = attributes;
             return ret;
 
@@ -2419,4 +2446,26 @@
             return new String(out_chars, 0, pos);
         }
     }
+
+    private DialogOnTop onTop = null;
+
+    private long parentWindowID = 0L;
+
+    /* Called from native code */
+    private long getParentWindowID() {
+        return parentWindowID;
+    }
+
+    private void clearParentWindowID() {
+        parentWindowID = 0L;
+        onTop = null;
+    }
+
+    private void setParentWindowID(PrintRequestAttributeSet attrs) {
+        parentWindowID = 0L;
+        onTop = (DialogOnTop)attrs.get(DialogOnTop.class);
+        if (onTop != null) {
+            parentWindowID = onTop.getID();
+        }
+    }
 }
diff --git a/jdk/src/share/classes/sun/print/ServiceDialog.java b/jdk/src/share/classes/sun/print/ServiceDialog.java
index 7c557db..9c6fd12 100644
--- a/jdk/src/share/classes/sun/print/ServiceDialog.java
+++ b/jdk/src/share/classes/sun/print/ServiceDialog.java
@@ -183,6 +183,9 @@
             isAWT = true;
         }
 
+        if (attributes.get(DialogOnTop.class) != null) {
+            setAlwaysOnTop(true);
+        }
         Container c = getContentPane();
         c.setLayout(new BorderLayout());
 
@@ -274,6 +277,10 @@
         this.asOriginal = attributes;
         this.asCurrent = new HashPrintRequestAttributeSet(attributes);
 
+        if (attributes.get(DialogOnTop.class) != null) {
+            setAlwaysOnTop(true);
+        }
+
         Container c = getContentPane();
         c.setLayout(new BorderLayout());
 
diff --git a/jdk/src/share/classes/sun/rmi/transport/tcp/TCPChannel.java b/jdk/src/share/classes/sun/rmi/transport/tcp/TCPChannel.java
index dbce2cc..c518024 100644
--- a/jdk/src/share/classes/sun/rmi/transport/tcp/TCPChannel.java
+++ b/jdk/src/share/classes/sun/rmi/transport/tcp/TCPChannel.java
@@ -298,11 +298,15 @@
                     out.flush();
                 }
             } catch (IOException e) {
-                if (e instanceof RemoteException)
+                try {
+                    conn.close();
+                } catch (Exception ex) {}
+                if (e instanceof RemoteException) {
                     throw (RemoteException) e;
-                else
+                } else {
                     throw new ConnectIOException(
                         "error during JRMP connection establishment", e);
+                }
             }
         } else {
             try {
diff --git a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java
index 536f927..02ce5e0 100644
--- a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java
@@ -235,8 +235,11 @@
      */
     public int getInitLifetime() throws GSSException {
         int retVal = 0;
-        retVal = (int)(getEndTime().getTime()
-                       - (new Date().getTime()));
+        Date d = getEndTime();
+        if (d == null) {
+            return 0;
+        }
+        retVal = (int)(d.getTime() - (new Date().getTime()));
 
         return retVal/1000;
     }
diff --git a/jdk/src/share/classes/sun/security/krb5/PrincipalName.java b/jdk/src/share/classes/sun/security/krb5/PrincipalName.java
index 885e13c..6d5ed3d 100644
--- a/jdk/src/share/classes/sun/security/krb5/PrincipalName.java
+++ b/jdk/src/share/classes/sun/security/krb5/PrincipalName.java
@@ -424,6 +424,9 @@
                 } catch (UnknownHostException | SecurityException e) {
                     // not canonicalized or no permission to do so, use old
                 }
+                if (hostName.endsWith(".")) {
+                    hostName = hostName.substring(0, hostName.length() - 1);
+                }
                 nameParts[1] = hostName.toLowerCase(Locale.ENGLISH);
             }
             nameStrings = nameParts;
diff --git a/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java b/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
index a6439ef..09dd4cb 100644
--- a/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
+++ b/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
@@ -255,7 +255,13 @@
 
     @Override
     void print(PrintStream s) throws IOException {
-        s.println("*** ClientKeyExchange, RSA PreMasterSecret, " +
-                                                        protocolVersion);
+        String version = "version not available/extractable";
+
+        byte[] ba = preMaster.getEncoded();
+        if (ba != null && ba.length >= 2) {
+            version = ProtocolVersion.valueOf(ba[0], ba[1]).name;
+        }
+
+        s.println("*** ClientKeyExchange, RSA PreMasterSecret, " + version);
     }
 }
diff --git a/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java b/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
index b471337..60aa908 100644
--- a/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
+++ b/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
@@ -1118,7 +1118,7 @@
             }
         } catch (CertPathValidatorException cpve) {
             throw new CertificateException(
-                "Certificates does not conform to algorithm constraints");
+                "Certificates do not conform to algorithm constraints", cpve);
         }
     }
 }
diff --git a/jdk/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java b/jdk/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java
index b763f7a..0319bad 100644
--- a/jdk/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java
+++ b/jdk/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java
@@ -703,6 +703,7 @@
         private int minSize;            // the minimal available key size
         private int maxSize;            // the maximal available key size
         private int prohibitedSize = -1;    // unavailable key sizes
+        private int size;
 
         public KeySizeConstraint(String algo, Operator operator, int length) {
             algorithm = algo;
@@ -789,7 +790,7 @@
                 return true;
             }
 
-            int size = KeyUtil.getKeySize(key);
+            size = KeyUtil.getKeySize(key);
             if (size == 0) {
                 return false;    // we don't allow any key of size 0.
             } else if (size > 0) {
diff --git a/jdk/src/share/classes/sun/util/locale/provider/CalendarNameProviderImpl.java b/jdk/src/share/classes/sun/util/locale/provider/CalendarNameProviderImpl.java
index edbcc44..4a41607 100644
--- a/jdk/src/share/classes/sun/util/locale/provider/CalendarNameProviderImpl.java
+++ b/jdk/src/share/classes/sun/util/locale/provider/CalendarNameProviderImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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,8 @@
 import java.util.Set;
 import java.util.TreeMap;
 import java.util.spi.CalendarNameProvider;
+import sun.util.calendar.CalendarSystem;
+import sun.util.calendar.Era;
 
 /**
  * Concrete implementation of the  {@link java.util.spi.CalendarDataProvider
@@ -67,7 +69,21 @@
                 if (field == DAY_OF_WEEK || field == YEAR) {
                     --value;
                 }
-                if (value < 0 || value >= strings.length) {
+                if (value < 0 || value > strings.length) {
+                    return null;
+                } else if (value == strings.length) {
+                    if (field == ERA && "japanese".equals(calendarType)) {
+                        // get the supplemental era, if any, specified through
+                        // the property "jdk.calendar.japanese.supplemental.era"
+                        // which is always the last element.
+                        Era[] jeras = CalendarSystem.forName("japanese").getEras();
+                        if (jeras.length == value) {
+                            Era supEra = jeras[value - 1]; // 0-based index
+                            return style == LONG ?
+                                supEra.getName() :
+                                supEra.getAbbreviation();
+                        }
+                    }
                     return null;
                 }
                 name = strings[value];
diff --git a/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties b/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties
index 55ecf42..c62d518 100644
--- a/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties
+++ b/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties
@@ -60,9 +60,6 @@
 # or other dealings in these Data Files or Software without prior
 # written authorization of the copyright holder.
 
-#
-# Generated automatically from the Common Locale Data Repository. DO NOT EDIT!
-#
 ADP=ADP
 AED=AED
 AFA=AFA
@@ -95,6 +92,7 @@
 BTN=BTN
 BWP=BWP
 BYB=BYB
+BYN=BYN
 BYR=BYR
 BZD=BZD
 CAD=CAD
@@ -313,8 +311,9 @@
 bsd=Bahamian Dollar
 btn=Bhutanese Ngultrum
 bwp=Botswanan Pula
-byb=Belarusian New Ruble (1994-1999)
-byr=Belarusian Ruble
+byb=Belarusian Ruble (1994-1999)
+byn=Belarusian Ruble
+byr=Belarusian Ruble (2000-2016)
 bzd=Belize Dollar
 cad=Canadian Dollar
 cdf=Congolese Franc
@@ -358,7 +357,7 @@
 gyd=Guyanaese Dollar
 hkd=Hong Kong Dollar
 hnl=Honduran Lempira
-hrk=Croatian Kuna
+hrk=Kuna
 htg=Haitian Gourde
 huf=Hungarian Forint
 idr=Indonesian Rupiah
@@ -402,7 +401,7 @@
 mtl=Maltese Lira
 mur=Mauritian Rupee
 mvr=Maldivian Rufiyaa
-mwk=Malawian Kwacha
+mwk=Malawian Malawi Kwacha
 mxn=Mexican Peso
 mxv=Mexican Investment Unit
 myr=Malaysian Ringgit
@@ -417,7 +416,7 @@
 nzd=New Zealand Dollar
 omr=Omani Rial
 pab=Panamanian Balboa
-pen=Peruvian Nuevo Sol
+pen=Peruvian Sol
 pgk=Papua New Guinean Kina
 php=Philippine Peso
 pkr=Pakistani Rupee
diff --git a/jdk/src/share/classes/sun/util/resources/be/CurrencyNames_be_BY.properties b/jdk/src/share/classes/sun/util/resources/be/CurrencyNames_be_BY.properties
index 4651ad1..54cc2a6 100644
--- a/jdk/src/share/classes/sun/util/resources/be/CurrencyNames_be_BY.properties
+++ b/jdk/src/share/classes/sun/util/resources/be/CurrencyNames_be_BY.properties
@@ -35,4 +35,5 @@
 # This notice and attribution to Taligent may not be removed.
 # Taligent is a registered trademark of Taligent, Inc.
 
+BYN=\u0420\u0443\u0431
 BYR=\u0420\u0443\u0431
diff --git a/jdk/src/share/demo/jvmti/hprof/manual.html b/jdk/src/share/demo/jvmti/hprof/manual.html
index a62610d..a19e0cd 100644
--- a/jdk/src/share/demo/jvmti/hprof/manual.html
+++ b/jdk/src/share/demo/jvmti/hprof/manual.html
@@ -1457,7 +1457,7 @@
 </table>
 <h3><a name="mozTocId348360" class="mozTocH3"></a>Handling of Arrays</h3>
 <br>
-There will be a "LOAD CLASS" tag for type type of each array
+There will be a "LOAD CLASS" tag for the type of each array
 in the dump. In the LOAD CLASS record, the class name string ID
 will refer to a string with a human-readable name of the array
 type that is formatted as the type name would be in Java source
diff --git a/jdk/src/share/lib/security/java.security-aix b/jdk/src/share/lib/security/java.security-aix
index 18cc34d..a2ccb40 100644
--- a/jdk/src/share/lib/security/java.security-aix
+++ b/jdk/src/share/lib/security/java.security-aix
@@ -735,7 +735,72 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
+# Cryptographic Jurisdiction Policy defaults
 #
+# Due to the import control restrictions of some countries, the default
+# JCE policy files allow for strong but "limited" cryptographic key
+# lengths to be used.  If your country's cryptographic regulations allow,
+# the "unlimited" strength policy files can be used instead, which contain
+# no restrictions on cryptographic strengths.
+#
+# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
+# TO DETERMINE THE EXACT REQUIREMENTS.
+#
+# <java-home> (below) refers to the directory where the JRE was
+# installed. It is determined based on whether you are running JCE
+# on a JRE or a JRE contained within the Java Development Kit, or
+# JDK(TM). The JDK contains the JRE, but at a different level in the
+# file hierarchy. For example, if the JDK is installed in
+# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
+# <java-home> is:
+#
+#  /home/user1/jdk1.8.0/jre           [Unix]
+#  C:\jdk1.8.0\jre                    [Windows]
+#
+# If on the other hand the JRE is installed in /home/user1/jre1.8.0
+# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
+# installed, then <java-home> is:
+#
+#  /home/user1/jre1.8.0               [Unix]
+#  C:\jre1.8.0                        [Windows]
+#
+# On Windows, for each JDK installation, there may be additional
+# JREs installed under the "Program Files" directory. Please make
+# sure that you install the unlimited strength policy JAR files
+# for all JREs that you plan to use.
+#
+# The policy files are jar files organized into subdirectories of
+# <java-home>/lib/security/policy.  Each directory contains a complete
+# set of policy files.
+#
+# The "crypto.policy" Security property controls the directory selection,
+# and thus the effective cryptographic policy.
+#
+# The default set of directories is:
+#
+#     limited | unlimited
+#
+# however other directories can be created and configured.
+#
+# To support older JDK Update releases, the crypto.policy property
+# is not defined by default. When the property is not defined, an
+# update release binary aware of the new property will use the following
+# logic to decide what crypto policy files get used :
+#
+# * If the US_export_policy.jar and local_policy.jar files are located
+# in the (legacy) <java-home>/lib/security directory, then the rules
+# embedded in those jar files will be used. This helps preserve compatibility
+# for users upgrading from an older installation.
+#
+# * If crypto.policy is not defined and no such jar files are present in
+# the legacy locations, then the JDK will use the limited settings
+# (equivalent to crypto.policy=limited)
+#
+# Please see the JCA documentation for additional information on these
+# files and formats.
+#crypto.policy=unlimited
+#
+
 # The policy for the XML Signature secure validation mode. The mode is
 # enabled by setting the property "org.jcp.xml.dsig.secureValidation" to
 # true with the javax.xml.crypto.XMLCryptoContext.setProperty() method,
diff --git a/jdk/src/share/lib/security/java.security-linux b/jdk/src/share/lib/security/java.security-linux
index 18cc34d..fe6bf51 100644
--- a/jdk/src/share/lib/security/java.security-linux
+++ b/jdk/src/share/lib/security/java.security-linux
@@ -735,6 +735,71 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
+# Cryptographic Jurisdiction Policy defaults
+#
+# Due to the import control restrictions of some countries, the default
+# JCE policy files allow for strong but "limited" cryptographic key
+# lengths to be used.  If your country's cryptographic regulations allow,
+# the "unlimited" strength policy files can be used instead, which contain
+# no restrictions on cryptographic strengths.
+#
+# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
+# TO DETERMINE THE EXACT REQUIREMENTS.
+#
+# <java-home> (below) refers to the directory where the JRE was
+# installed. It is determined based on whether you are running JCE
+# on a JRE or a JRE contained within the Java Development Kit, or
+# JDK(TM). The JDK contains the JRE, but at a different level in the
+# file hierarchy. For example, if the JDK is installed in
+# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
+# <java-home> is:
+#
+#  /home/user1/jdk1.8.0/jre           [Unix]
+#  C:\jdk1.8.0\jre                    [Windows]
+#
+# If on the other hand the JRE is installed in /home/user1/jre1.8.0
+# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
+# installed, then <java-home> is:
+#
+#  /home/user1/jre1.8.0               [Unix]
+#  C:\jre1.8.0                        [Windows]
+#
+# On Windows, for each JDK installation, there may be additional
+# JREs installed under the "Program Files" directory. Please make
+# sure that you install the unlimited strength policy JAR files
+# for all JREs that you plan to use.
+#
+# The policy files are jar files organized into subdirectories of
+# <java-home>/lib/security/policy.  Each directory contains a complete
+# set of policy files.
+#
+# The "crypto.policy" Security property controls the directory selection,
+# and thus the effective cryptographic policy.
+#
+# The default set of directories is:
+#
+#     limited | unlimited
+#
+# however other directories can be created and configured.
+#
+# To support older JDK Update releases, the crypto.policy property
+# is not defined by default. When the property is not defined, an
+# update release binary aware of the new property will use the following
+# logic to decide what crypto policy files get used :
+#
+# * If the US_export_policy.jar and local_policy.jar files are located
+# in the (legacy) <java-home>/lib/security directory, then the rules
+# embedded in those jar files will be used. This helps preserve compatibility
+# for users upgrading from an older installation.
+#
+# * If crypto.policy is not defined and no such jar files are present in
+# the legacy locations, then the JDK will use the limited settings
+# (equivalent to crypto.policy=limited)
+#
+# Please see the JCA documentation for additional information on these
+# files and formats.
+#crypto.policy=unlimited
+
 #
 # The policy for the XML Signature secure validation mode. The mode is
 # enabled by setting the property "org.jcp.xml.dsig.secureValidation" to
@@ -843,3 +908,4 @@
 #    java.rmi.dgc.VMID;\
 #    java.rmi.dgc.Lease;\
 #    maxdepth=5;maxarray=10000
+
diff --git a/jdk/src/share/lib/security/java.security-macosx b/jdk/src/share/lib/security/java.security-macosx
index 388031a..7a0ba39 100644
--- a/jdk/src/share/lib/security/java.security-macosx
+++ b/jdk/src/share/lib/security/java.security-macosx
@@ -738,6 +738,71 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
+# Cryptographic Jurisdiction Policy defaults
+#
+# Due to the import control restrictions of some countries, the default
+# JCE policy files allow for strong but "limited" cryptographic key
+# lengths to be used.  If your country's cryptographic regulations allow,
+# the "unlimited" strength policy files can be used instead, which contain
+# no restrictions on cryptographic strengths.
+#
+# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
+# TO DETERMINE THE EXACT REQUIREMENTS.
+#
+# <java-home> (below) refers to the directory where the JRE was
+# installed. It is determined based on whether you are running JCE
+# on a JRE or a JRE contained within the Java Development Kit, or
+# JDK(TM). The JDK contains the JRE, but at a different level in the
+# file hierarchy. For example, if the JDK is installed in
+# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
+# <java-home> is:
+#
+#  /home/user1/jdk1.8.0/jre           [Unix]
+#  C:\jdk1.8.0\jre                    [Windows]
+#
+# If on the other hand the JRE is installed in /home/user1/jre1.8.0
+# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
+# installed, then <java-home> is:
+#
+#  /home/user1/jre1.8.0               [Unix]
+#  C:\jre1.8.0                        [Windows]
+#
+# On Windows, for each JDK installation, there may be additional
+# JREs installed under the "Program Files" directory. Please make
+# sure that you install the unlimited strength policy JAR files
+# for all JREs that you plan to use.
+#
+# The policy files are jar files organized into subdirectories of
+# <java-home>/lib/security/policy.  Each directory contains a complete
+# set of policy files.
+#
+# The "crypto.policy" Security property controls the directory selection,
+# and thus the effective cryptographic policy.
+#
+# The default set of directories is:
+#
+#     limited | unlimited
+#
+# however other directories can be created and configured.
+#
+# To support older JDK Update releases, the crypto.policy property
+# is not defined by default. When the property is not defined, an
+# update release binary aware of the new property will use the following
+# logic to decide what crypto policy files get used :
+#
+# * If the US_export_policy.jar and local_policy.jar files are located
+# in the (legacy) <java-home>/lib/security directory, then the rules
+# embedded in those jar files will be used. This helps preserve compatibility
+# for users upgrading from an older installation.
+#
+# * If crypto.policy is not defined and no such jar files are present in
+# the legacy locations, then the JDK will use the limited settings
+# (equivalent to crypto.policy=limited)
+#
+# Please see the JCA documentation for additional information on these
+# files and formats.
+#crypto.policy=unlimited
+
 #
 # The policy for the XML Signature secure validation mode. The mode is
 # enabled by setting the property "org.jcp.xml.dsig.secureValidation" to
diff --git a/jdk/src/share/lib/security/java.security-solaris b/jdk/src/share/lib/security/java.security-solaris
index 818b619..70cbe17 100644
--- a/jdk/src/share/lib/security/java.security-solaris
+++ b/jdk/src/share/lib/security/java.security-solaris
@@ -737,6 +737,71 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
+# Cryptographic Jurisdiction Policy defaults
+#
+# Due to the import control restrictions of some countries, the default
+# JCE policy files allow for strong but "limited" cryptographic key
+# lengths to be used.  If your country's cryptographic regulations allow,
+# the "unlimited" strength policy files can be used instead, which contain
+# no restrictions on cryptographic strengths.
+#
+# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
+# TO DETERMINE THE EXACT REQUIREMENTS.
+#
+# <java-home> (below) refers to the directory where the JRE was
+# installed. It is determined based on whether you are running JCE
+# on a JRE or a JRE contained within the Java Development Kit, or
+# JDK(TM). The JDK contains the JRE, but at a different level in the
+# file hierarchy. For example, if the JDK is installed in
+# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
+# <java-home> is:
+#
+#  /home/user1/jdk1.8.0/jre           [Unix]
+#  C:\jdk1.8.0\jre                    [Windows]
+#
+# If on the other hand the JRE is installed in /home/user1/jre1.8.0
+# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
+# installed, then <java-home> is:
+#
+#  /home/user1/jre1.8.0               [Unix]
+#  C:\jre1.8.0                        [Windows]
+#
+# On Windows, for each JDK installation, there may be additional
+# JREs installed under the "Program Files" directory. Please make
+# sure that you install the unlimited strength policy JAR files
+# for all JREs that you plan to use.
+#
+# The policy files are jar files organized into subdirectories of
+# <java-home>/lib/security/policy.  Each directory contains a complete
+# set of policy files.
+#
+# The "crypto.policy" Security property controls the directory selection,
+# and thus the effective cryptographic policy.
+#
+# The default set of directories is:
+#
+#     limited | unlimited
+#
+# however other directories can be created and configured.
+#
+# To support older JDK Update releases, the crypto.policy property
+# is not defined by default. When the property is not defined, an
+# update release binary aware of the new property will use the following
+# logic to decide what crypto policy files get used :
+#
+# * If the US_export_policy.jar and local_policy.jar files are located
+# in the (legacy) <java-home>/lib/security directory, then the rules
+# embedded in those jar files will be used. This helps preserve compatibility
+# for users upgrading from an older installation.
+#
+# * If crypto.policy is not defined and no such jar files are present in
+# the legacy locations, then the JDK will use the limited settings
+# (equivalent to crypto.policy=limited)
+#
+# Please see the JCA documentation for additional information on these
+# files and formats.
+#crypto.policy=unlimited
+
 #
 # The policy for the XML Signature secure validation mode. The mode is
 # enabled by setting the property "org.jcp.xml.dsig.secureValidation" to
diff --git a/jdk/src/share/lib/security/java.security-windows b/jdk/src/share/lib/security/java.security-windows
index 5dc77e6..28a415d 100644
--- a/jdk/src/share/lib/security/java.security-windows
+++ b/jdk/src/share/lib/security/java.security-windows
@@ -738,6 +738,71 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
+# Cryptographic Jurisdiction Policy defaults
+#
+# Due to the import control restrictions of some countries, the default
+# JCE policy files allow for strong but "limited" cryptographic key
+# lengths to be used.  If your country's cryptographic regulations allow,
+# the "unlimited" strength policy files can be used instead, which contain
+# no restrictions on cryptographic strengths.
+#
+# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
+# TO DETERMINE THE EXACT REQUIREMENTS.
+#
+# <java-home> (below) refers to the directory where the JRE was
+# installed. It is determined based on whether you are running JCE
+# on a JRE or a JRE contained within the Java Development Kit, or
+# JDK(TM). The JDK contains the JRE, but at a different level in the
+# file hierarchy. For example, if the JDK is installed in
+# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
+# <java-home> is:
+#
+#  /home/user1/jdk1.8.0/jre           [Unix]
+#  C:\jdk1.8.0\jre                    [Windows]
+#
+# If on the other hand the JRE is installed in /home/user1/jre1.8.0
+# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
+# installed, then <java-home> is:
+#
+#  /home/user1/jre1.8.0               [Unix]
+#  C:\jre1.8.0                        [Windows]
+#
+# On Windows, for each JDK installation, there may be additional
+# JREs installed under the "Program Files" directory. Please make
+# sure that you install the unlimited strength policy JAR files
+# for all JREs that you plan to use.
+#
+# The policy files are jar files organized into subdirectories of
+# <java-home>/lib/security/policy.  Each directory contains a complete
+# set of policy files.
+#
+# The "crypto.policy" Security property controls the directory selection,
+# and thus the effective cryptographic policy.
+#
+# The default set of directories is:
+#
+#     limited | unlimited
+#
+# however other directories can be created and configured.
+#
+# To support older JDK Update releases, the crypto.policy property
+# is not defined by default. When the property is not defined, an
+# update release binary aware of the new property will use the following
+# logic to decide what crypto policy files get used :
+#
+# * If the US_export_policy.jar and local_policy.jar files are located
+# in the (legacy) <java-home>/lib/security directory, then the rules
+# embedded in those jar files will be used. This helps preserve compatibility
+# for users upgrading from an older installation.
+#
+# * If crypto.policy is not defined and no such jar files are present in
+# the legacy locations, then the JDK will use the limited settings
+# (equivalent to crypto.policy=limited)
+#
+# Please see the JCA documentation for additional information on these
+# files and formats.
+#crypto.policy=unlimited
+
 #
 # The policy for the XML Signature secure validation mode. The mode is
 # enabled by setting the property "org.jcp.xml.dsig.secureValidation" to
diff --git a/jdk/src/share/native/com/sun/tools/jdi/SharedMemoryConnection.c b/jdk/src/share/native/com/sun/tools/jdi/SharedMemoryConnection.c
index 5936b5a..e28efe6 100644
--- a/jdk/src/share/native/com/sun/tools/jdi/SharedMemoryConnection.c
+++ b/jdk/src/share/native/com/sun/tools/jdi/SharedMemoryConnection.c
@@ -174,9 +174,20 @@
      * Get the packet header
      */
     (*env)->GetByteArrayRegion(env, b, 0, sizeof(pktHeader), pktHeader);
+    if ((*env)->ExceptionOccurred(env)) {
+        /* b shorter than sizeof(pktHeader) */
+        return;
+    }
 
     total_length = (int)pktHeader[3] | ((int)pktHeader[2] << 8) |
                    ((int)pktHeader[1] << 16) | ((int)pktHeader[0] << 24);
+
+    if (total_length < sizeof(pktHeader)) {
+        throwException(env, "java/lang/IllegalArgumentException",
+                            "JDWP header is incorrect");
+        return;
+    }
+
     /*
      * The id field is in big endian (also errorCode field in the case
      * of reply packets).
@@ -195,9 +206,9 @@
     }
 
     /*
-     * The length of the JDWP packet is 11 + data
+     * The length of the JDWP packet is sizeof(pktHeader) + data
      */
-    data_length = total_length - 11;
+    data_length = total_length - sizeof(pktHeader);
 
     if (data_length == 0) {
         data = NULL;
@@ -209,7 +220,7 @@
             return;
         }
 
-        (*env)->GetByteArrayRegion(env, b, 11, /*sizeof(CmdPacket)+4*/ data_length, data);
+        (*env)->GetByteArrayRegion(env, b, sizeof(pktHeader), /*sizeof(CmdPacket)+4*/ data_length, data);
         if ((*env)->ExceptionOccurred(env)) {
             free(data);
             return;
diff --git a/jdk/src/share/native/common/jni_util.c b/jdk/src/share/native/common/jni_util.c
index 0d00897..87cd00e 100644
--- a/jdk/src/share/native/common/jni_util.c
+++ b/jdk/src/share/native/common/jni_util.c
@@ -175,12 +175,14 @@
                 jio_snprintf(str1, messageextlen, " (%s)", message);
                 s2 = (*env)->NewStringUTF(env, str1);
                 free(str1);
+                JNU_CHECK_EXCEPTION(env);
                 if (s2 != NULL) {
                     jstring s3 = JNU_CallMethodByName(
                                      env, NULL, s, "concat",
                                      "(Ljava/lang/String;)Ljava/lang/String;",
                                      s2).l;
                     (*env)->DeleteLocalRef(env, s2);
+                    JNU_CHECK_EXCEPTION(env);
                     if (s3 != NULL) {
                         (*env)->DeleteLocalRef(env, s);
                         s = s3;
diff --git a/jdk/src/share/native/java/io/FileInputStream.c b/jdk/src/share/native/java/io/FileInputStream.c
index dc1aea5..db565e6 100644
--- a/jdk/src/share/native/java/io/FileInputStream.c
+++ b/jdk/src/share/native/java/io/FileInputStream.c
@@ -73,7 +73,7 @@
 }
 
 JNIEXPORT jlong JNICALL
-Java_java_io_FileInputStream_skip(JNIEnv *env, jobject this, jlong toSkip) {
+Java_java_io_FileInputStream_skip0(JNIEnv *env, jobject this, jlong toSkip) {
     jlong cur = jlong_zero;
     jlong end = jlong_zero;
     FD fd = GET_FD(this, fis_fd);
@@ -90,7 +90,7 @@
 }
 
 JNIEXPORT jint JNICALL
-Java_java_io_FileInputStream_available(JNIEnv *env, jobject this) {
+Java_java_io_FileInputStream_available0(JNIEnv *env, jobject this) {
     jlong ret;
     FD fd = GET_FD(this, fis_fd);
     if (fd == -1) {
diff --git a/jdk/src/share/native/java/io/io_util.c b/jdk/src/share/native/java/io/io_util.c
index 5dd8223..f256af4 100644
--- a/jdk/src/share/native/java/io/io_util.c
+++ b/jdk/src/share/native/java/io/io_util.c
@@ -216,6 +216,7 @@
 #else
         why = JNU_NewStringPlatform(env, buf);
 #endif
+        CHECK_NULL(why);
     }
     x = JNU_NewObjectByName(env,
                             "java/io/FileNotFoundException",
diff --git a/jdk/src/share/native/java/lang/ClassLoader.c b/jdk/src/share/native/java/lang/ClassLoader.c
index 1d9da67..40b0b85 100644
--- a/jdk/src/share/native/java/lang/ClassLoader.c
+++ b/jdk/src/share/native/java/lang/ClassLoader.c
@@ -132,7 +132,6 @@
     if (name != NULL) {
         utfName = getUTF(env, name, buf, sizeof(buf));
         if (utfName == NULL) {
-            JNU_ThrowOutOfMemoryError(env, NULL);
             goto free_body;
         }
         VerifyFixClassname(utfName);
@@ -143,7 +142,6 @@
     if (source != NULL) {
         utfSource = getUTF(env, source, sourceBuf, sizeof(sourceBuf));
         if (utfSource == NULL) {
-            JNU_ThrowOutOfMemoryError(env, NULL);
             goto free_utfName;
         }
     } else {
@@ -517,7 +515,6 @@
     procHandle = getProcessHandle();
     cname = JNU_GetStringPlatformChars(env, name, 0);
     if (cname == NULL) {
-        JNU_ThrowOutOfMemoryError(env, NULL);
         return NULL;
     }
     // Copy name Skipping PREFIX
diff --git a/jdk/src/share/native/java/lang/System.c b/jdk/src/share/native/java/lang/System.c
index cb0044f..5c36460 100644
--- a/jdk/src/share/native/java/lang/System.c
+++ b/jdk/src/share/native/java/lang/System.c
@@ -56,44 +56,56 @@
     return JVM_IHashCode(env, x);
 }
 
-#define PUTPROP(props, key, val) \
-    if (1) { \
-        jstring jkey = (*env)->NewStringUTF(env, key); \
-        jstring jval = (*env)->NewStringUTF(env, val); \
-        jobject r = (*env)->CallObjectMethod(env, props, putID, jkey, jval); \
-        if ((*env)->ExceptionOccurred(env)) return NULL; \
-        (*env)->DeleteLocalRef(env, jkey); \
-        (*env)->DeleteLocalRef(env, jval); \
-        (*env)->DeleteLocalRef(env, r); \
+#define PUTPROP(props, key, val)                                     \
+    if (1) {                                                         \
+        jstring jkey, jval;                                          \
+        jobject r;                                                   \
+        jkey = (*env)->NewStringUTF(env, key);                       \
+        if (jkey == NULL) return NULL;                               \
+        jval = (*env)->NewStringUTF(env, val);                       \
+        if (jval == NULL) return NULL;                               \
+        r = (*env)->CallObjectMethod(env, props, putID, jkey, jval); \
+        if ((*env)->ExceptionOccurred(env)) return NULL;             \
+        (*env)->DeleteLocalRef(env, jkey);                           \
+        (*env)->DeleteLocalRef(env, jval);                           \
+        (*env)->DeleteLocalRef(env, r);                              \
     } else ((void) 0)
 
 /*  "key" is a char type string with only ASCII character in it.
     "val" is a nchar (typedefed in java_props.h) type string  */
 
-#define PUTPROP_ForPlatformNString(props, key, val) \
-    if (1) { \
-        jstring jkey = (*env)->NewStringUTF(env, key);  \
-        jstring jval = GetStringPlatform(env, val); \
-        jobject r = (*env)->CallObjectMethod(env, props, putID, jkey, jval); \
-        if ((*env)->ExceptionOccurred(env)) return NULL; \
-        (*env)->DeleteLocalRef(env, jkey); \
-        (*env)->DeleteLocalRef(env, jval); \
-        (*env)->DeleteLocalRef(env, r); \
+#define PUTPROP_ForPlatformNString(props, key, val)                  \
+    if (1) {                                                         \
+        jstring jkey, jval;                                          \
+        jobject r;                                                   \
+        jkey = (*env)->NewStringUTF(env, key);                       \
+        if (jkey == NULL) return NULL;                               \
+        jval = GetStringPlatform(env, val);                          \
+        if (jval == NULL) return NULL;                               \
+        r = (*env)->CallObjectMethod(env, props, putID, jkey, jval); \
+        if ((*env)->ExceptionOccurred(env)) return NULL;             \
+        (*env)->DeleteLocalRef(env, jkey);                           \
+        (*env)->DeleteLocalRef(env, jval);                           \
+        (*env)->DeleteLocalRef(env, r);                              \
     } else ((void) 0)
-#define REMOVEPROP(props, key) \
-    if (1) { \
-        jstring jkey = JNU_NewStringPlatform(env, key); \
-        jobject r = (*env)->CallObjectMethod(env, props, removeID, jkey); \
-        if ((*env)->ExceptionOccurred(env)) return NULL; \
-        (*env)->DeleteLocalRef(env, jkey); \
-        (*env)->DeleteLocalRef(env, r); \
+#define REMOVEPROP(props, key)                                    \
+    if (1) {                                                      \
+        jstring jkey;                                             \
+        jobject r;                                                \
+        jkey = JNU_NewStringPlatform(env, key);                   \
+        if (jkey == NULL) return NULL;                            \
+        r = (*env)->CallObjectMethod(env, props, removeID, jkey); \
+        if ((*env)->ExceptionOccurred(env)) return NULL;          \
+        (*env)->DeleteLocalRef(env, jkey);                        \
+        (*env)->DeleteLocalRef(env, r);                           \
     } else ((void) 0)
-#define GETPROP(props, key, jret) \
-    if (1) { \
-        jstring jkey = JNU_NewStringPlatform(env, key); \
+#define GETPROP(props, key, jret)                                     \
+    if (1) {                                                          \
+        jstring jkey = JNU_NewStringPlatform(env, key);               \
+        if (jkey == NULL) return NULL;                                \
         jret = (*env)->CallObjectMethod(env, props, getPropID, jkey); \
-        if ((*env)->ExceptionOccurred(env)) return NULL; \
-        (*env)->DeleteLocalRef(env, jkey); \
+        if ((*env)->ExceptionOccurred(env)) return NULL;              \
+        (*env)->DeleteLocalRef(env, jkey);                            \
     } else ((void) 0)
 
 #ifndef VENDOR /* Third party may overwrite this. */
@@ -169,23 +181,31 @@
 Java_java_lang_System_initProperties(JNIEnv *env, jclass cla, jobject props)
 {
     char buf[128];
-    java_props_t *sprops = GetJavaProperties(env);
-    jmethodID putID = (*env)->GetMethodID(env,
-                                          (*env)->GetObjectClass(env, props),
-                                          "put",
-            "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
-    jmethodID removeID = (*env)->GetMethodID(env,
-                                          (*env)->GetObjectClass(env, props),
-                                          "remove",
-            "(Ljava/lang/Object;)Ljava/lang/Object;");
-    jmethodID getPropID = (*env)->GetMethodID(env,
-                                          (*env)->GetObjectClass(env, props),
-                                          "getProperty",
-            "(Ljava/lang/String;)Ljava/lang/String;");
+    java_props_t *sprops;
+    jmethodID putID, removeID, getPropID;
     jobject ret = NULL;
     jstring jVMVal = NULL;
 
-    if (sprops == NULL || putID == NULL ) return NULL;
+    sprops = GetJavaProperties(env);
+    CHECK_NULL_RETURN(sprops, NULL);
+
+    putID = (*env)->GetMethodID(env,
+                                (*env)->GetObjectClass(env, props),
+                                "put",
+            "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+    CHECK_NULL_RETURN(putID, NULL);
+
+    removeID = (*env)->GetMethodID(env,
+                                   (*env)->GetObjectClass(env, props),
+                                   "remove",
+            "(Ljava/lang/Object;)Ljava/lang/Object;");
+    CHECK_NULL_RETURN(removeID, NULL);
+
+    getPropID = (*env)->GetMethodID(env,
+                                    (*env)->GetObjectClass(env, props),
+                                    "getProperty",
+            "(Ljava/lang/String;)Ljava/lang/String;");
+    CHECK_NULL_RETURN(getPropID, NULL);
 
     PUTPROP(props, "java.specification.version",
             JDK_MAJOR_VERSION "." JDK_MINOR_VERSION);
@@ -382,6 +402,7 @@
     GETPROP(props, "sun.locale.formatasdefault", jVMVal);
     if (jVMVal) {
         const char * val = (*env)->GetStringUTFChars(env, jVMVal, 0);
+        CHECK_NULL_RETURN(val, NULL);
         fmtdefault = !strcmp(val, "true");
         (*env)->ReleaseStringUTFChars(env, jVMVal, val);
         (*env)->DeleteLocalRef(env, jVMVal);
diff --git a/jdk/src/share/native/java/net/Inet4Address.c b/jdk/src/share/native/java/net/Inet4Address.c
index 62ad3d6..cc43241 100644
--- a/jdk/src/share/native/java/net/Inet4Address.c
+++ b/jdk/src/share/native/java/net/Inet4Address.c
@@ -34,6 +34,8 @@
 jclass ia4_class;
 jmethodID ia4_ctrID;
 
+static int ia4_initialized = 0;
+
 /*
  * Class:     java_net_Inet4Address
  * Method:    init
@@ -41,9 +43,13 @@
  */
 JNIEXPORT void JNICALL
 Java_java_net_Inet4Address_init(JNIEnv *env, jclass cls) {
-    jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
-    CHECK_NULL(c);
-    ia4_class = (*env)->NewGlobalRef(env, c);
-    CHECK_NULL(ia4_class);
-    ia4_ctrID = (*env)->GetMethodID(env, ia4_class, "<init>", "()V");
+    if (!ia4_initialized) {
+        jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
+        CHECK_NULL(c);
+        ia4_class = (*env)->NewGlobalRef(env, c);
+        CHECK_NULL(ia4_class);
+        ia4_ctrID = (*env)->GetMethodID(env, ia4_class, "<init>", "()V");
+        CHECK_NULL(ia4_ctrID);
+        ia4_initialized = 1;
+    }
 }
diff --git a/jdk/src/share/native/java/net/Inet6Address.c b/jdk/src/share/native/java/net/Inet6Address.c
index 9b828af..3d0151a 100644
--- a/jdk/src/share/native/java/net/Inet6Address.c
+++ b/jdk/src/share/native/java/net/Inet6Address.c
@@ -42,6 +42,8 @@
 jfieldID ia6_scopeifnameID;
 jmethodID ia6_ctrID;
 
+static int ia6_initialized = 0;
+
 /*
  * Class:     java_net_Inet6Address
  * Method:    init
@@ -49,24 +51,28 @@
  */
 JNIEXPORT void JNICALL
 Java_java_net_Inet6Address_init(JNIEnv *env, jclass cls) {
-    jclass ia6h_class;
-    jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
-    CHECK_NULL(c);
-    ia6_class = (*env)->NewGlobalRef(env, c);
-    CHECK_NULL(ia6_class);
-    ia6h_class = (*env)->FindClass(env, "java/net/Inet6Address$Inet6AddressHolder");
-    CHECK_NULL(ia6h_class);
-    ia6_holder6ID = (*env)->GetFieldID(env, ia6_class, "holder6", "Ljava/net/Inet6Address$Inet6AddressHolder;");
-    CHECK_NULL(ia6_holder6ID);
-    ia6_ipaddressID = (*env)->GetFieldID(env, ia6h_class, "ipaddress", "[B");
-    CHECK_NULL(ia6_ipaddressID);
-    ia6_scopeidID = (*env)->GetFieldID(env, ia6h_class, "scope_id", "I");
-    CHECK_NULL(ia6_scopeidID);
-    ia6_cachedscopeidID = (*env)->GetFieldID(env, ia6_class, "cached_scope_id", "I");
-    CHECK_NULL(ia6_cachedscopeidID);
-    ia6_scopeidsetID = (*env)->GetFieldID(env, ia6h_class, "scope_id_set", "Z");
-    CHECK_NULL(ia6_scopeidsetID);
-    ia6_scopeifnameID = (*env)->GetFieldID(env, ia6h_class, "scope_ifname", "Ljava/net/NetworkInterface;");
-    CHECK_NULL(ia6_scopeifnameID);
-    ia6_ctrID = (*env)->GetMethodID(env, ia6_class, "<init>", "()V");
+    if (!ia6_initialized) {
+        jclass ia6h_class;
+        jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
+        CHECK_NULL(c);
+        ia6_class = (*env)->NewGlobalRef(env, c);
+        CHECK_NULL(ia6_class);
+        ia6h_class = (*env)->FindClass(env, "java/net/Inet6Address$Inet6AddressHolder");
+        CHECK_NULL(ia6h_class);
+        ia6_holder6ID = (*env)->GetFieldID(env, ia6_class, "holder6", "Ljava/net/Inet6Address$Inet6AddressHolder;");
+        CHECK_NULL(ia6_holder6ID);
+        ia6_ipaddressID = (*env)->GetFieldID(env, ia6h_class, "ipaddress", "[B");
+        CHECK_NULL(ia6_ipaddressID);
+        ia6_scopeidID = (*env)->GetFieldID(env, ia6h_class, "scope_id", "I");
+        CHECK_NULL(ia6_scopeidID);
+        ia6_cachedscopeidID = (*env)->GetFieldID(env, ia6_class, "cached_scope_id", "I");
+        CHECK_NULL(ia6_cachedscopeidID);
+        ia6_scopeidsetID = (*env)->GetFieldID(env, ia6h_class, "scope_id_set", "Z");
+        CHECK_NULL(ia6_scopeidsetID);
+        ia6_scopeifnameID = (*env)->GetFieldID(env, ia6h_class, "scope_ifname", "Ljava/net/NetworkInterface;");
+        CHECK_NULL(ia6_scopeifnameID);
+        ia6_ctrID = (*env)->GetMethodID(env, ia6_class, "<init>", "()V");
+        CHECK_NULL(ia6_ctrID);
+        ia6_initialized = 1;
+    }
 }
diff --git a/jdk/src/share/native/java/net/InetAddress.c b/jdk/src/share/native/java/net/InetAddress.c
index 607ed35..a0d55c2 100644
--- a/jdk/src/share/native/java/net/InetAddress.c
+++ b/jdk/src/share/native/java/net/InetAddress.c
@@ -41,6 +41,8 @@
 jfieldID iac_origHostNameID;
 jfieldID ia_preferIPv6AddressID;
 
+static int ia_initialized = 0;
+
 /*
  * Class:     java_net_InetAddress
  * Method:    init
@@ -48,23 +50,28 @@
  */
 JNIEXPORT void JNICALL
 Java_java_net_InetAddress_init(JNIEnv *env, jclass cls) {
-    jclass c = (*env)->FindClass(env,"java/net/InetAddress");
-    CHECK_NULL(c);
-    ia_class = (*env)->NewGlobalRef(env, c);
-    CHECK_NULL(ia_class);
-    c = (*env)->FindClass(env,"java/net/InetAddress$InetAddressHolder");
-    CHECK_NULL(c);
-    iac_class = (*env)->NewGlobalRef(env, c);
-    ia_holderID = (*env)->GetFieldID(env, ia_class, "holder", "Ljava/net/InetAddress$InetAddressHolder;");
-    CHECK_NULL(ia_holderID);
-    ia_preferIPv6AddressID = (*env)->GetStaticFieldID(env, ia_class, "preferIPv6Address", "Z");
-    CHECK_NULL(ia_preferIPv6AddressID);
+    if (!ia_initialized) {
+        jclass c = (*env)->FindClass(env,"java/net/InetAddress");
+        CHECK_NULL(c);
+        ia_class = (*env)->NewGlobalRef(env, c);
+        CHECK_NULL(ia_class);
+        c = (*env)->FindClass(env,"java/net/InetAddress$InetAddressHolder");
+        CHECK_NULL(c);
+        iac_class = (*env)->NewGlobalRef(env, c);
+        CHECK_NULL(iac_class);
+        ia_holderID = (*env)->GetFieldID(env, ia_class, "holder", "Ljava/net/InetAddress$InetAddressHolder;");
+        CHECK_NULL(ia_holderID);
+        ia_preferIPv6AddressID = (*env)->GetStaticFieldID(env, ia_class, "preferIPv6Address", "Z");
+        CHECK_NULL(ia_preferIPv6AddressID);
 
-    iac_addressID = (*env)->GetFieldID(env, iac_class, "address", "I");
-    CHECK_NULL(iac_addressID);
-    iac_familyID = (*env)->GetFieldID(env, iac_class, "family", "I");
-    CHECK_NULL(iac_familyID);
-    iac_hostNameID = (*env)->GetFieldID(env, iac_class, "hostName", "Ljava/lang/String;");
-    CHECK_NULL(iac_hostNameID);
-    iac_origHostNameID = (*env)->GetFieldID(env, iac_class, "originalHostName", "Ljava/lang/String;");
+        iac_addressID = (*env)->GetFieldID(env, iac_class, "address", "I");
+        CHECK_NULL(iac_addressID);
+        iac_familyID = (*env)->GetFieldID(env, iac_class, "family", "I");
+        CHECK_NULL(iac_familyID);
+        iac_hostNameID = (*env)->GetFieldID(env, iac_class, "hostName", "Ljava/lang/String;");
+        CHECK_NULL(iac_hostNameID);
+        iac_origHostNameID = (*env)->GetFieldID(env, iac_class, "originalHostName", "Ljava/lang/String;");
+        CHECK_NULL(iac_origHostNameID);
+        ia_initialized = 1;
+    }
 }
diff --git a/jdk/src/share/native/java/net/net_util.c b/jdk/src/share/native/java/net/net_util.c
index 56edb63..2194e2e 100644
--- a/jdk/src/share/native/java/net/net_util.c
+++ b/jdk/src/share/native/java/net/net_util.c
@@ -75,11 +75,14 @@
 
 static int initialized = 0;
 
-static void initInetAddrs(JNIEnv *env) {
+JNIEXPORT void JNICALL initInetAddressIDs(JNIEnv *env) {
     if (!initialized) {
         Java_java_net_InetAddress_init(env, 0);
+        JNU_CHECK_EXCEPTION(env);
         Java_java_net_Inet4Address_init(env, 0);
+        JNU_CHECK_EXCEPTION(env);
         Java_java_net_Inet6Address_init(env, 0);
+        JNU_CHECK_EXCEPTION(env);
         initialized = 1;
     }
 }
@@ -100,47 +103,32 @@
  * get_ methods that return objects return NULL on error.
  */
 jobject getInet6Address_scopeifname(JNIEnv *env, jobject iaObj) {
-    jobject holder;
-
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, NULL);
     return (*env)->GetObjectField(env, holder, ia6_scopeifnameID);
 }
 
 int setInet6Address_scopeifname(JNIEnv *env, jobject iaObj, jobject scopeifname) {
-    jobject holder;
-
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, JNI_FALSE);
     (*env)->SetObjectField(env, holder, ia6_scopeifnameID, scopeifname);
     return JNI_TRUE;
 }
 
 int getInet6Address_scopeid_set(JNIEnv *env, jobject iaObj) {
-    jobject holder;
-
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, -1);
     return (*env)->GetBooleanField(env, holder, ia6_scopeidsetID);
 }
 
 int getInet6Address_scopeid(JNIEnv *env, jobject iaObj) {
-    jobject holder;
-
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, -1);
     return (*env)->GetIntField(env, holder, ia6_scopeidID);
 }
 
 int setInet6Address_scopeid(JNIEnv *env, jobject iaObj, int scopeid) {
-    jobject holder;
-
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, JNI_FALSE);
     (*env)->SetIntField(env, holder, ia6_scopeidID, scopeid);
     if (scopeid > 0) {
@@ -154,7 +142,6 @@
     jobject holder, addr;
     jbyteArray barr;
 
-    initInetAddrs(env);
     holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, JNI_FALSE);
     addr =  (*env)->GetObjectField(env, holder, ia6_ipaddressID);
@@ -167,7 +154,6 @@
     jobject holder;
     jbyteArray addr;
 
-    initInetAddrs(env);
     holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, JNI_FALSE);
     addr =  (jbyteArray)(*env)->GetObjectField(env, holder, ia6_ipaddressID);
@@ -181,53 +167,39 @@
 }
 
 void setInetAddress_addr(JNIEnv *env, jobject iaObj, int address) {
-    jobject holder;
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     (*env)->SetIntField(env, holder, iac_addressID, address);
 }
 
 void setInetAddress_family(JNIEnv *env, jobject iaObj, int family) {
-    jobject holder;
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     (*env)->SetIntField(env, holder, iac_familyID, family);
 }
 
 void setInetAddress_hostName(JNIEnv *env, jobject iaObj, jobject host) {
-    jobject holder;
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     (*env)->SetObjectField(env, holder, iac_hostNameID, host);
     (*env)->SetObjectField(env, holder, iac_origHostNameID, host);
 }
 
 int getInetAddress_addr(JNIEnv *env, jobject iaObj) {
-    jobject holder;
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     return (*env)->GetIntField(env, holder, iac_addressID);
 }
 
 int getInetAddress_family(JNIEnv *env, jobject iaObj) {
-    jobject holder;
-
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     return (*env)->GetIntField(env, holder, iac_familyID);
 }
 
 jobject getInetAddress_hostName(JNIEnv *env, jobject iaObj) {
-    jobject holder;
-    initInetAddrs(env);
-    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     return (*env)->GetObjectField(env, holder, iac_hostNameID);
 }
 
 JNIEXPORT jobject JNICALL
 NET_SockaddrToInetAddress(JNIEnv *env, struct sockaddr *him, int *port) {
     jobject iaObj;
-    initInetAddrs(env);
 #ifdef AF_INET6
     if (him->sa_family == AF_INET6) {
         jbyteArray ipaddress;
@@ -239,31 +211,15 @@
         jbyte *caddr = (jbyte *)&(him6->sin6_addr);
         if (NET_IsIPv4Mapped(caddr)) {
             int address;
-            static jclass inet4Cls = 0;
-            if (inet4Cls == 0) {
-                jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
-                CHECK_NULL_RETURN(c, NULL);
-                inet4Cls = (*env)->NewGlobalRef(env, c);
-                CHECK_NULL_RETURN(inet4Cls, NULL);
-                (*env)->DeleteLocalRef(env, c);
-            }
-            iaObj = (*env)->NewObject(env, inet4Cls, ia4_ctrID);
+            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             CHECK_NULL_RETURN(iaObj, NULL);
             address = NET_IPv4MappedToIPv4(caddr);
             setInetAddress_addr(env, iaObj, address);
             setInetAddress_family(env, iaObj, IPv4);
         } else {
-            static jclass inet6Cls = 0;
             jint scope;
             int ret;
-            if (inet6Cls == 0) {
-                jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
-                CHECK_NULL_RETURN(c, NULL);
-                inet6Cls = (*env)->NewGlobalRef(env, c);
-                CHECK_NULL_RETURN(inet6Cls, NULL);
-                (*env)->DeleteLocalRef(env, c);
-            }
-            iaObj = (*env)->NewObject(env, inet6Cls, ia6_ctrID);
+            iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
             CHECK_NULL_RETURN(iaObj, NULL);
             ret = setInet6Address_ipaddress(env, iaObj, (char *)&(him6->sin6_addr));
             CHECK_NULL_RETURN(ret, NULL);
@@ -276,16 +232,7 @@
 #endif /* AF_INET6 */
         {
             struct sockaddr_in *him4 = (struct sockaddr_in *)him;
-            static jclass inet4Cls = 0;
-
-            if (inet4Cls == 0) {
-                jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
-                CHECK_NULL_RETURN(c, NULL);
-                inet4Cls = (*env)->NewGlobalRef(env, c);
-                CHECK_NULL_RETURN(inet4Cls, NULL);
-                (*env)->DeleteLocalRef(env, c);
-            }
-            iaObj = (*env)->NewObject(env, inet4Cls, ia4_ctrID);
+            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             CHECK_NULL_RETURN(iaObj, NULL);
             setInetAddress_family(env, iaObj, IPv4);
             setInetAddress_addr(env, iaObj, ntohl(him4->sin_addr.s_addr));
diff --git a/jdk/src/share/native/java/net/net_util.h b/jdk/src/share/native/java/net/net_util.h
index 9063c3e..c8a5e68 100644
--- a/jdk/src/share/native/java/net/net_util.h
+++ b/jdk/src/share/native/java/net/net_util.h
@@ -56,6 +56,8 @@
 extern jfieldID iac_origHostNameID;
 extern jfieldID ia_preferIPv6AddressID;
 
+JNIEXPORT void JNICALL initInetAddressIDs(JNIEnv *env);
+
 /** (Inet6Address accessors)
  * set_ methods return JNI_TRUE on success JNI_FALSE on error
  * get_ methods that return int/boolean, return -1 on error
diff --git a/jdk/src/share/native/java/nio/Bits.c b/jdk/src/share/native/java/nio/Bits.c
index 20aa0d1..8bc3ff7 100644
--- a/jdk/src/share/native/java/nio/Bits.c
+++ b/jdk/src/share/native/java/nio/Bits.c
@@ -51,10 +51,13 @@
 
 #define MBYTE 1048576
 
-#define GETCRITICAL(bytes, env, obj) { \
+#define GETCRITICAL_OR_RETURN(bytes, env, obj) { \
     bytes = (*env)->GetPrimitiveArrayCritical(env, obj, NULL); \
-    if (bytes == NULL) \
-        JNU_ThrowInternalError(env, "Unable to get array"); \
+    if (bytes == NULL)  { \
+        if ((*env)->ExceptionOccurred(env) == NULL) \
+            JNU_ThrowInternalError(env, "Unable to get array"); \
+        return; \
+    } \
 }
 
 #define RELEASECRITICAL(bytes, env, obj, mode) { \
@@ -85,7 +88,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL(bytes, env, src);
+        GETCRITICAL_OR_RETURN(bytes, env, src);
 
         srcShort = (jshort *)(bytes + srcPos);
         endShort = srcShort + (size / sizeof(jshort));
@@ -120,7 +123,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL(bytes, env, dst);
+        GETCRITICAL_OR_RETURN(bytes, env, dst);
 
         dstShort = (jshort *)(bytes + dstPos);
         endShort = srcShort + (size / sizeof(jshort));
@@ -155,7 +158,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL(bytes, env, src);
+        GETCRITICAL_OR_RETURN(bytes, env, src);
 
         srcInt = (jint *)(bytes + srcPos);
         endInt = srcInt + (size / sizeof(jint));
@@ -190,7 +193,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL(bytes, env, dst);
+        GETCRITICAL_OR_RETURN(bytes, env, dst);
 
         dstInt = (jint *)(bytes + dstPos);
         endInt = srcInt + (size / sizeof(jint));
@@ -225,7 +228,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL(bytes, env, src);
+        GETCRITICAL_OR_RETURN(bytes, env, src);
 
         srcLong = (jlong *)(bytes + srcPos);
         endLong = srcLong + (size / sizeof(jlong));
@@ -260,7 +263,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL(bytes, env, dst);
+        GETCRITICAL_OR_RETURN(bytes, env, dst);
 
         dstLong = (jlong *)(bytes + dstPos);
         endLong = srcLong + (size / sizeof(jlong));
diff --git a/jdk/src/share/native/sun/awt/giflib/dgif_lib.c b/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
index 2d3d882..1c1b217 100644
--- a/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
+++ b/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
@@ -114,7 +114,7 @@
     GifFile->SavedImages = NULL;
     GifFile->SColorMap = NULL;
 
-    Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType));
+    Private = (GifFilePrivateType *)calloc(1, sizeof(GifFilePrivateType));
     if (Private == NULL) {
         if (Error != NULL)
             *Error = D_GIF_ERR_NOT_ENOUGH_MEM;
@@ -122,6 +122,9 @@
         free((char *)GifFile);
         return NULL;
     }
+
+    /*@i1@*/memset(Private, '\0', sizeof(GifFilePrivateType));
+
 #ifdef _WIN32
     _setmode(FileHandle, O_BINARY);    /* Make sure it is in binary mode. */
 #endif /* _WIN32 */
@@ -197,13 +200,14 @@
     GifFile->SavedImages = NULL;
     GifFile->SColorMap = NULL;
 
-    Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType));
+    Private = (GifFilePrivateType *)calloc(1, sizeof(GifFilePrivateType));
     if (!Private) {
         if (Error != NULL)
             *Error = D_GIF_ERR_NOT_ENOUGH_MEM;
         free((char *)GifFile);
         return NULL;
     }
+    /*@i1@*/memset(Private, '\0', sizeof(GifFilePrivateType));
 
     GifFile->Private = (void *)Private;
     Private->FileHandle = 0;
@@ -417,8 +421,8 @@
 
     if (GifFile->SavedImages) {
         SavedImage* new_saved_images =
-            (SavedImage *)realloc(GifFile->SavedImages,
-                            sizeof(SavedImage) * (GifFile->ImageCount + 1));
+            (SavedImage *)reallocarray(GifFile->SavedImages,
+                            (GifFile->ImageCount + 1), sizeof(SavedImage));
         if (new_saved_images == NULL) {
             GifFile->Error = D_GIF_ERR_NOT_ENOUGH_MEM;
             return GIF_ERROR;
@@ -788,6 +792,12 @@
     }
     BitsPerPixel = CodeSize;
 
+    /* this can only happen on a severely malformed GIF */
+    if (BitsPerPixel > 8) {
+        GifFile->Error = D_GIF_ERR_READ_FAILED;    /* somewhat bogus error code */
+        return GIF_ERROR;    /* Failed to read Code size. */
+    }
+
     Private->Buf[0] = 0;    /* Input Buffer empty. */
     Private->BitsPerPixel = BitsPerPixel;
     Private->ClearCode = (1 << BitsPerPixel);
@@ -1123,7 +1133,7 @@
               if (ImageSize > (SIZE_MAX / sizeof(GifPixelType))) {
                   return GIF_ERROR;
               }
-              sp->RasterBits = (unsigned char *)malloc(ImageSize *
+              sp->RasterBits = (unsigned char *)reallocarray(NULL, ImageSize,
                       sizeof(GifPixelType));
 
               if (sp->RasterBits == NULL) {
diff --git a/jdk/src/share/native/sun/awt/giflib/gif_lib.h b/jdk/src/share/native/sun/awt/giflib/gif_lib.h
index aa35636..e8d7090 100644
--- a/jdk/src/share/native/sun/awt/giflib/gif_lib.h
+++ b/jdk/src/share/native/sun/awt/giflib/gif_lib.h
@@ -37,7 +37,7 @@
 
 #define GIFLIB_MAJOR 5
 #define GIFLIB_MINOR 1
-#define GIFLIB_RELEASE 1
+#define GIFLIB_RELEASE 4
 
 #define GIF_ERROR   0
 #define GIF_OK      1
@@ -274,6 +274,9 @@
                                      GifPixelType ColorTransIn2[]);
 extern int GifBitSize(int n);
 
+extern void * reallocarray(void *optr, size_t nmemb, size_t size);
+
+
 /******************************************************************************
  Support for the in-core structures allocation (slurp mode).
 ******************************************************************************/
diff --git a/jdk/src/share/native/sun/awt/giflib/gifalloc.c b/jdk/src/share/native/sun/awt/giflib/gifalloc.c
index f7a6a3d..cc784d1 100644
--- a/jdk/src/share/native/sun/awt/giflib/gifalloc.c
+++ b/jdk/src/share/native/sun/awt/giflib/gifalloc.c
@@ -212,8 +212,8 @@
 
         /* perhaps we can shrink the map? */
         if (RoundUpTo < ColorUnion->ColorCount) {
-            GifColorType *new_map = (GifColorType *)realloc(Map,
-                                 sizeof(GifColorType) * RoundUpTo);
+            GifColorType *new_map = (GifColorType *)reallocarray(Map,
+                                 RoundUpTo, sizeof(GifColorType));
             if( new_map == NULL ) {
                 GifFreeMapObject(ColorUnion);
                 return ((ColorMapObject *) NULL);
@@ -256,9 +256,9 @@
     if (*ExtensionBlocks == NULL)
         *ExtensionBlocks=(ExtensionBlock *)malloc(sizeof(ExtensionBlock));
     else {
-        ExtensionBlock* ep_new = (ExtensionBlock *)realloc(*ExtensionBlocks,
-                                      sizeof(ExtensionBlock) *
-                                      (*ExtensionBlockCount + 1));
+        ExtensionBlock* ep_new = (ExtensionBlock *)reallocarray
+                                      (*ExtensionBlocks, (*ExtensionBlockCount + 1),
+                                      sizeof(ExtensionBlock));
         if( ep_new == NULL )
             return (GIF_ERROR);
         *ExtensionBlocks = ep_new;
@@ -349,8 +349,8 @@
     if (GifFile->SavedImages == NULL)
         GifFile->SavedImages = (SavedImage *)malloc(sizeof(SavedImage));
     else
-        GifFile->SavedImages = (SavedImage *)realloc(GifFile->SavedImages,
-                               sizeof(SavedImage) * (GifFile->ImageCount + 1));
+        GifFile->SavedImages = (SavedImage *)reallocarray(GifFile->SavedImages,
+                               (GifFile->ImageCount + 1), sizeof(SavedImage));
 
     if (GifFile->SavedImages == NULL)
         return ((SavedImage *)NULL);
@@ -379,9 +379,10 @@
             }
 
             /* next, the raster */
-            sp->RasterBits = (unsigned char *)malloc(sizeof(GifPixelType) *
-                                                   CopyFrom->ImageDesc.Height *
-                                                   CopyFrom->ImageDesc.Width);
+            sp->RasterBits = (unsigned char *)reallocarray(NULL,
+                                                  (CopyFrom->ImageDesc.Height *
+                                                  CopyFrom->ImageDesc.Width),
+                                                  sizeof(GifPixelType));
             if (sp->RasterBits == NULL) {
                 FreeLastSavedImage(GifFile);
                 return (SavedImage *)(NULL);
@@ -392,9 +393,9 @@
 
             /* finally, the extension blocks */
             if (sp->ExtensionBlocks != NULL) {
-                sp->ExtensionBlocks = (ExtensionBlock *)malloc(
-                                      sizeof(ExtensionBlock) *
-                                      CopyFrom->ExtensionBlockCount);
+                sp->ExtensionBlocks = (ExtensionBlock *)reallocarray(NULL,
+                                      CopyFrom->ExtensionBlockCount,
+                                      sizeof(ExtensionBlock));
                 if (sp->ExtensionBlocks == NULL) {
                     FreeLastSavedImage(GifFile);
                     return (SavedImage *)(NULL);
diff --git a/jdk/src/share/native/sun/awt/giflib/openbsd-reallocarray.c b/jdk/src/share/native/sun/awt/giflib/openbsd-reallocarray.c
new file mode 100644
index 0000000..1087671
--- /dev/null
+++ b/jdk/src/share/native/sun/awt/giflib/openbsd-reallocarray.c
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+
+/*    $OpenBSD: reallocarray.c,v 1.1 2014/05/08 21:43:49 deraadt Exp $    */
+/*
+ * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <errno.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+/*
+ * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
+ * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
+ */
+#define MUL_NO_OVERFLOW    ((size_t)1 << (sizeof(size_t) * 4))
+
+void *
+reallocarray(void *optr, size_t nmemb, size_t size)
+{
+    if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
+        nmemb > 0 && SIZE_MAX / nmemb < size) {
+        errno = ENOMEM;
+        return NULL;
+    }
+    /*
+     * Head off variations in realloc behavior on different
+     * platforms (reported by MarkR <mrogers6@users.sf.net>)
+     *
+     * The behaviour of reallocarray is implementation-defined if
+     * nmemb or size is zero. It can return NULL or non-NULL
+     * depending on the platform.
+     * https://www.securecoding.cert.org/confluence/display/c/MEM04-C.Beware+of+zero-lengthallocations
+     *
+     * Here are some extracts from realloc man pages on different platforms.
+     *
+     * void realloc( void memblock, size_t size );
+     *
+     * Windows:
+     *
+     * If there is not enough available memory to expand the block
+     * to the given size, the original block is left unchanged,
+     * and NULL is returned.  If size is zero, then the block
+     * pointed to by memblock is freed; the return value is NULL,
+     * and memblock is left pointing at a freed block.
+     *
+     * OpenBSD:
+     *
+     * If size or nmemb is equal to 0, a unique pointer to an
+     * access protected, zero sized object is returned. Access via
+     * this pointer will generate a SIGSEGV exception.
+     *
+     * Linux:
+     *
+     * If size was equal to 0, either NULL or a pointer suitable
+     * to be passed to free() is returned.
+     *
+     * OS X:
+     *
+     * If size is zero and ptr is not NULL, a new, minimum sized
+     * object is allocated and the original object is freed.
+     *
+     * It looks like images with zero width or height can trigger
+     * this, and fuzzing behaviour will differ by platform, so
+     * fuzzing on one platform may not detect zero-size allocation
+     * problems on other platforms.
+     */
+    if (size == 0 || nmemb == 0)
+        return NULL;
+    return realloc(optr, size * nmemb);
+}
diff --git a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
index 87c640b..7e1d8c9 100644
--- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
+++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
@@ -2686,6 +2686,18 @@
     RELEASE_ARRAYS(env, data, NULL);
 }
 
+static void freeArray(void** arr, jint size) {
+    int i;
+    if (arr != NULL) {
+        for (i = 0; i < size; i++) {
+            if (arr[i] != NULL) {
+                free(arr[i]);
+            }
+        }
+        free(arr);
+    }
+}
+
 JNIEXPORT jboolean JNICALL
 Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
     (JNIEnv *env,
@@ -2794,6 +2806,8 @@
                 scale = (UINT8**) calloc(numBands, sizeof(UINT8*));
 
                 if (scale == NULL) {
+                    (*env)->ReleaseIntArrayElements(env, bandSizes,
+                                                    bandSize, JNI_ABORT);
                     JNU_ThrowByName( env, "java/lang/OutOfMemoryError",
                                      "Writing JPEG Stream");
                     return JNI_FALSE;
@@ -2810,6 +2824,8 @@
                     free(scale[j]);
                 }
                 free(scale);
+                (*env)->ReleaseIntArrayElements(env, bandSizes,
+                                                bandSize, JNI_ABORT);
                 JNU_ThrowByName( env, "java/lang/OutOfMemoryError",
                                  "Writing JPEG Stream");
                 return JNI_FALSE;
@@ -2834,21 +2850,14 @@
     pb = &data->pixelBuf;
 
     if (setPixelBuffer(env, pb, buffer) == NOT_OK) {
-        if (scale != NULL) {
-            for (i = 0; i < numBands; i++) {
-                if (scale[i] != NULL) {
-                    free(scale[i]);
-                }
-            }
-            free(scale);
-        }
+        freeArray(scale, numBands);
         return data->abortFlag;  // We already threw an out of memory exception
     }
 
     // Allocate a 1-scanline buffer
     scanLinePtr = (JSAMPROW)malloc(scanLineSize);
     if (scanLinePtr == NULL) {
-        RELEASE_ARRAYS(env, data, (const JOCTET *)(dest->next_output_byte));
+        freeArray(scale, numBands);
         JNU_ThrowByName( env,
                          "java/lang/OutOfMemoryError",
                          "Writing JPEG Stream");
@@ -2870,15 +2879,7 @@
             JNU_ThrowByName(env, "javax/imageio/IIOException", buffer);
         }
 
-        if (scale != NULL) {
-            for (i = 0; i < numBands; i++) {
-                if (scale[i] != NULL) {
-                    free(scale[i]);
-                }
-            }
-            free(scale);
-        }
-
+        freeArray(scale, numBands);
         free(scanLinePtr);
         return data->abortFlag;
     }
@@ -2926,7 +2927,11 @@
     if (qsels) {
         (*env)->ReleaseIntArrayElements(env, QtableSelectors, qsels, JNI_ABORT);
     }
-    if (!success) return data->abortFlag;
+    if (!success) {
+        freeArray(scale, numBands);
+        free(scanLinePtr);
+        return data->abortFlag;
+    }
 
     jpeg_suppress_tables(cinfo, TRUE);  // Disable writing any current
 
@@ -2944,6 +2949,8 @@
     if (GET_ARRAYS(env, data,
                    (const JOCTET **)(&dest->next_output_byte)) == NOT_OK) {
         (*env)->ExceptionClear(env);
+        freeArray(scale, numBands);
+        free(scanLinePtr);
         JNU_ThrowByName(env,
                         "javax/imageio/IIOException",
                         "Array pin failed");
@@ -2978,7 +2985,12 @@
             cinfo->scan_info = cinfo->script_space;
             scanptr = (int *) cinfo->script_space;
             scanData = (*env)->GetIntArrayElements(env, scanInfo, NULL);
-            CHECK_NULL_RETURN(scanData, data->abortFlag);
+            if (scanData == NULL) {
+                RELEASE_ARRAYS(env, data, (const JOCTET *)(dest->next_output_byte));
+                freeArray(scale, numBands);
+                free(scanLinePtr);
+                return data->abortFlag;
+            }
             // number of jints per scan is 9
             // We avoid a memcpy to handle different size ints
             for (i = 0; i < numScans*9; i++) {
@@ -3074,15 +3086,7 @@
         jpeg_abort((j_common_ptr)cinfo);
     }
 
-    if (scale != NULL) {
-        for (i = 0; i < numBands; i++) {
-            if (scale[i] != NULL) {
-                free(scale[i]);
-            }
-        }
-        free(scale);
-    }
-
+    freeArray(scale, numBands);
     free(scanLinePtr);
     RELEASE_ARRAYS(env, data, NULL);
     return data->abortFlag;
diff --git a/jdk/src/share/native/sun/awt/libpng/png.h b/jdk/src/share/native/sun/awt/libpng/png.h
index 550b8d2..d2feaef 100644
--- a/jdk/src/share/native/sun/awt/libpng/png.h
+++ b/jdk/src/share/native/sun/awt/libpng/png.h
@@ -90,6 +90,9 @@
  *    Glenn Randers-Pehrson
  *    Willem van Schaik
  *
+ * Some files in the "scripts" directory have different copyright owners
+ * but are also released under this license.
+ *
  * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  * Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
  * and are distributed according to the same disclaimer and license as
diff --git a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
index 472b5ee..2845899 100644
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -772,6 +772,7 @@
     mlib_image *src;
     mlib_image *dst;
     int i;
+    int j = 0;
     int retStatus = 1;
     mlib_status status;
     double *matrix;
@@ -824,6 +825,15 @@
         return 0;
     }
 
+    /* Check for invalid double value in transformation matrix */
+    for (j = 0; j < 6; j++) {
+
+        if (!(IS_FINITE(matrix[j]))) {
+            (*env)->ReleasePrimitiveArrayCritical(env, jmatrix, matrix, JNI_ABORT);
+            return 0;
+        }
+    }
+
     if (s_printIt) {
         printf("matrix is %g %g %g %g %g %g\n", matrix[0], matrix[1],
                matrix[2], matrix[3], matrix[4], matrix[5]);
@@ -980,6 +990,7 @@
     mlib_image *src;
     mlib_image *dst;
     int i;
+    int j = 0;
     int retStatus = 1;
     mlib_status status;
     double *matrix;
@@ -1044,6 +1055,17 @@
         return 0;
     }
 
+    /* Check for invalid double value in transformation matrix */
+    for (j = 0; j < 6; j++) {
+
+        if (!(IS_FINITE(matrix[j]))) {
+            (*env)->ReleasePrimitiveArrayCritical(env, jmatrix, matrix, JNI_ABORT);
+            free(srcRasterP);
+            free(dstRasterP);
+            return 0;
+        }
+    }
+
     if (s_printIt) {
         printf("matrix is %g %g %g %g %g %g\n", matrix[0], matrix[1],
                matrix[2], matrix[3], matrix[4], matrix[5]);
diff --git a/jdk/src/share/native/sun/awt/medialib/mlib_ImageScanPoly.c b/jdk/src/share/native/sun/awt/medialib/mlib_ImageScanPoly.c
index 34c2171..ccc1572 100644
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageScanPoly.c
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageScanPoly.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,6 +33,8 @@
 #include "mlib_image.h"
 #include "mlib_SysMath.h"
 #include "mlib_ImageAffine.h"
+#include "safe_math.h"
+
 
 /***************************************************************/
 mlib_status mlib_AffineEdges(mlib_affine_param *param,
@@ -83,6 +85,12 @@
   dstYStride = mlib_ImageGetStride(dst);
   paddings = mlib_ImageGetPaddings(src);
 
+  /* All the transformation matrix parameters should be finite. if not, return failure */
+  if (!(IS_FINITE(a) && IS_FINITE(b) && IS_FINITE(c) && IS_FINITE(d) &&
+        IS_FINITE(tx) && IS_FINITE(ty))) {
+    return MLIB_FAILURE;
+  }
+
   if (srcWidth >= (1 << 15) || srcHeight >= (1 << 15)) {
     return MLIB_FAILURE;
   }
@@ -288,6 +296,10 @@
     if (dY1 == dY2)
       continue;
 
+    if (!(IS_FINITE(slope))) {
+       continue;
+    }
+
     if (dY1 < 0.0)
       y1 = 0;
     else {
@@ -328,6 +340,10 @@
     if (dY1 == dY2)
       continue;
 
+    if (!(IS_FINITE(slope))) {
+        continue;
+    }
+
     if (dY1 < 0.0)
       y1 = 0;
     else {
diff --git a/jdk/src/share/native/sun/awt/medialib/safe_math.h b/jdk/src/share/native/sun/awt/medialib/safe_math.h
index 34c1fc5..a87eba1 100644
--- a/jdk/src/share/native/sun/awt/medialib/safe_math.h
+++ b/jdk/src/share/native/sun/awt/medialib/safe_math.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,15 @@
 #ifndef __SAFE_MATH_H__
 #define __SAFE_MATH_H__
 
+#include "mlib_types.h"
+
 #define SAFE_TO_MULT(a, b) \
     (((a) > 0) && ((b) >= 0) && ((0x7fffffff / (a)) > (b)))
 
 #define SAFE_TO_ADD(a, b) \
     (((a) >= 0) && ((b) >= 0) && ((0x7fffffff - (a)) > (b)))
 
+#define IS_FINITE(a) \
+    (((a) >= MLIB_D64_MIN) && ((a) <= MLIB_D64_MAX))
+
 #endif // __SAFE_MATH_H__
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsalpha.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsalpha.c
new file mode 100644
index 0000000..277ed55
--- /dev/null
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsalpha.c
@@ -0,0 +1,547 @@
+/*
+ * 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.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2016 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
+
+
+// Alpha copy ------------------------------------------------------------------------------------------------------------------
+
+// Floor to byte, taking care of saturation
+cmsINLINE cmsUInt8Number _cmsQuickSaturateByte(cmsFloat64Number d)
+{
+       d += 0.5;
+       if (d <= 0) return 0;
+       if (d >= 255.0) return 255;
+
+       return (cmsUInt8Number) _cmsQuickFloorWord(d);
+}
+
+
+// Return the size in bytes of a given formatter
+static
+int trueBytesSize(cmsUInt32Number Format)
+{
+       int fmt_bytes = T_BYTES(Format);
+
+       // For double, the T_BYTES field returns zero
+       if (fmt_bytes == 0)
+              return sizeof(double);
+
+       // Otherwise, it is already correct for all formats
+       return fmt_bytes;
+}
+
+
+// Several format converters
+
+typedef void(*cmsFormatterAlphaFn)(void* dst, const void* src);
+
+
+// From 8
+
+static
+void copy8(void* dst, const void* src)
+{
+       memmove(dst, src, 1);
+}
+
+static
+void from8to16(void* dst, const void* src)
+{
+       cmsUInt8Number n = *(cmsUInt8Number*)src;
+       *(cmsUInt16Number*) dst = FROM_8_TO_16(n);
+}
+
+static
+void from8toFLT(void* dst, const void* src)
+{
+       *(cmsFloat32Number*)dst = (*(cmsUInt8Number*)src) / 255.0f;
+}
+
+static
+void from8toDBL(void* dst, const void* src)
+{
+       *(cmsFloat64Number*)dst = (*(cmsUInt8Number*)src) / 255.0;
+}
+
+static
+void from8toHLF(void* dst, const void* src)
+{
+       cmsFloat32Number n = (*(cmsUInt8Number*)src) / 255.0f;
+       *(cmsUInt16Number*)dst = _cmsFloat2Half(n);
+}
+
+// From 16
+
+static
+void from16to8(void* dst, const void* src)
+{
+       cmsUInt16Number n = *(cmsUInt16Number*)src;
+       *(cmsUInt8Number*) dst = FROM_16_TO_8(n);
+}
+
+static
+void copy16(void* dst, const void* src)
+{
+       memmove(dst, src, 2);
+}
+
+void from16toFLT(void* dst, const void* src)
+{
+       *(cmsFloat32Number*)dst = (*(cmsUInt16Number*)src) / 65535.0f;
+}
+
+void from16toDBL(void* dst, const void* src)
+{
+       *(cmsFloat64Number*)dst = (*(cmsUInt16Number*)src) / 65535.0f;
+}
+
+static
+void from16toHLF(void* dst, const void* src)
+{
+       cmsFloat32Number n = (*(cmsUInt16Number*)src) / 65535.0f;
+       *(cmsUInt16Number*)dst = _cmsFloat2Half(n);
+}
+
+// From Float
+
+static
+void fromFLTto8(void* dst, const void* src)
+{
+       cmsFloat32Number n = *(cmsFloat32Number*)src;
+       *(cmsUInt8Number*)dst = _cmsQuickSaturateByte(n * 255.0f);
+}
+
+static
+void fromFLTto16(void* dst, const void* src)
+{
+       cmsFloat32Number n = *(cmsFloat32Number*)src;
+       *(cmsUInt16Number*)dst = _cmsQuickSaturateWord(n * 65535.0f);
+}
+
+static
+void copy32(void* dst, const void* src)
+{
+       memmove(dst, src, sizeof(cmsFloat32Number));
+}
+
+static
+void fromFLTtoDBL(void* dst, const void* src)
+{
+       cmsFloat32Number n = *(cmsFloat32Number*)src;
+       *(cmsFloat64Number*)dst = (cmsFloat64Number)n;
+}
+
+static
+void fromFLTtoHLF(void* dst, const void* src)
+{
+       cmsFloat32Number n = *(cmsFloat32Number*)src;
+       *(cmsUInt16Number*)dst = _cmsFloat2Half(n);
+}
+
+
+// From HALF
+
+static
+void fromHLFto8(void* dst, const void* src)
+{
+       cmsFloat32Number n = _cmsHalf2Float(*(cmsUInt16Number*)src);
+       *(cmsUInt8Number*)dst = _cmsQuickSaturateByte(n * 255.0f);
+}
+
+static
+void fromHLFto16(void* dst, const void* src)
+{
+       cmsFloat32Number n = _cmsHalf2Float(*(cmsUInt16Number*)src);
+       *(cmsUInt16Number*)dst = _cmsQuickSaturateWord(n * 65535.0f);
+}
+
+static
+void fromHLFtoFLT(void* dst, const void* src)
+{
+       *(cmsFloat32Number*)dst = _cmsHalf2Float(*(cmsUInt16Number*)src);
+}
+
+static
+void fromHLFtoDBL(void* dst, const void* src)
+{
+       *(cmsFloat64Number*)dst = (cmsFloat64Number)_cmsHalf2Float(*(cmsUInt16Number*)src);
+}
+
+// From double
+static
+void fromDBLto8(void* dst, const void* src)
+{
+       cmsFloat64Number n = *(cmsFloat64Number*)src;
+       *(cmsUInt8Number*)dst = _cmsQuickSaturateByte(n * 255.0);
+}
+
+static
+void fromDBLto16(void* dst, const void* src)
+{
+       cmsFloat64Number n = *(cmsFloat64Number*)src;
+       *(cmsUInt16Number*)dst = _cmsQuickSaturateWord(n * 65535.0f);
+}
+
+static
+void fromDBLtoFLT(void* dst, const void* src)
+{
+       cmsFloat64Number n = *(cmsFloat64Number*)src;
+       *(cmsFloat32Number*)dst = (cmsFloat32Number) n;
+}
+
+static
+void fromDBLtoHLF(void* dst, const void* src)
+{
+       cmsFloat32Number n = (cmsFloat32Number) *(cmsFloat64Number*)src;
+       *(cmsUInt16Number*)dst = _cmsFloat2Half(n);
+}
+
+static
+void copy64(void* dst, const void* src)
+{
+       memmove(dst, src, sizeof(cmsFloat64Number));
+}
+
+
+// Returns the position (x or y) of the formatter in the table of functions
+static
+int FormatterPos(cmsUInt32Number frm)
+{
+       int  b = T_BYTES(frm);
+
+       if (b == 0 && T_FLOAT(frm))
+              return 4; // DBL
+       if (b == 2 && T_FLOAT(frm))
+              return 2; // HLF
+       if (b == 4 && T_FLOAT(frm))
+              return 3; // FLT
+       if (b == 2 && !T_FLOAT(frm))
+              return 1; // 16
+       if (b == 1 && !T_FLOAT(frm))
+              return 0; // 8
+
+       return -1; // not recognized
+
+}
+
+// Obtains a alpha-to-alpha funmction formatter
+static
+cmsFormatterAlphaFn _cmsGetFormatterAlpha(cmsContext id, cmsUInt32Number in, cmsUInt32Number out)
+{
+static cmsFormatterAlphaFn FormattersAlpha[5][5] = {
+
+       /* from 8 */  { copy8,      from8to16,   from8toHLF,   from8toFLT,   from8toDBL   },
+       /* from 16*/  { from16to8,  copy16,      from16toHLF,  from16toFLT,  from16toDBL  },
+       /* from HLF*/ { fromHLFto8, fromHLFto16, copy16,       fromHLFtoFLT, fromHLFtoDBL },
+       /* from FLT*/ { fromFLTto8, fromFLTto16, fromFLTtoHLF, copy32,       fromFLTtoDBL },
+       /* from DBL*/ { fromDBLto8, fromDBLto16, fromDBLtoHLF, fromDBLtoFLT, copy64 }};
+
+        int in_n  = FormatterPos(in);
+        int out_n = FormatterPos(out);
+
+        if (in_n < 0 || out_n < 0 || in_n > 4 || out_n > 4) {
+
+               cmsSignalError(id, cmsERROR_UNKNOWN_EXTENSION, "Unrecognized alpha channel width");
+               return NULL;
+        }
+
+        return FormattersAlpha[in_n][out_n];
+}
+
+
+
+// This function computes the distance from each component to the next one in bytes.
+static
+void ComputeIncrementsForChunky(cmsUInt32Number Format,
+                                cmsUInt32Number ComponentStartingOrder[],
+                                cmsUInt32Number ComponentPointerIncrements[])
+{
+       cmsUInt32Number channels[cmsMAXCHANNELS];
+       int extra = T_EXTRA(Format);
+       int nchannels = T_CHANNELS(Format);
+       int total_chans = nchannels + extra;
+       int i;
+       int channelSize = trueBytesSize(Format);
+       int pixelSize = channelSize * total_chans;
+
+           // Sanity check
+           if (total_chans <= 0 || total_chans >= cmsMAXCHANNELS)
+                   return;
+
+        memset(channels, 0, sizeof(channels));
+
+       // Separation is independent of starting point and only depends on channel size
+       for (i = 0; i < extra; i++)
+              ComponentPointerIncrements[i] = pixelSize;
+
+       // Handle do swap
+       for (i = 0; i < total_chans; i++)
+       {
+              if (T_DOSWAP(Format)) {
+                     channels[i] = total_chans - i - 1;
+              }
+              else {
+                     channels[i] = i;
+              }
+       }
+
+       // Handle swap first (ROL of positions), example CMYK -> KCMY | 0123 -> 3012
+       if (T_SWAPFIRST(Format) && total_chans > 1) {
+
+              cmsUInt32Number tmp = channels[0];
+              for (i = 0; i < total_chans-1; i++)
+                     channels[i] = channels[i + 1];
+
+              channels[total_chans - 1] = tmp;
+       }
+
+       // Handle size
+       if (channelSize > 1)
+              for (i = 0; i < total_chans; i++) {
+                     channels[i] *= channelSize;
+              }
+
+       for (i = 0; i < extra; i++)
+              ComponentStartingOrder[i] = channels[i + nchannels];
+}
+
+
+
+//  On planar configurations, the distance is the stride added to any non-negative
+static
+void ComputeIncrementsForPlanar(cmsUInt32Number Format,
+                                cmsUInt32Number BytesPerPlane,
+                                cmsUInt32Number ComponentStartingOrder[],
+                                cmsUInt32Number ComponentPointerIncrements[])
+{
+       cmsUInt32Number channels[cmsMAXCHANNELS];
+       int extra = T_EXTRA(Format);
+       int nchannels = T_CHANNELS(Format);
+       int total_chans = nchannels + extra;
+       int i;
+       int channelSize = trueBytesSize(Format);
+
+       // Sanity check
+       if (total_chans <= 0 || total_chans >= cmsMAXCHANNELS)
+           return;
+
+       memset(channels, 0, sizeof(channels));
+
+       // Separation is independent of starting point and only depends on channel size
+       for (i = 0; i < extra; i++)
+              ComponentPointerIncrements[i] = channelSize;
+
+       // Handle do swap
+       for (i = 0; i < total_chans; i++)
+       {
+              if (T_DOSWAP(Format)) {
+                     channels[i] = total_chans - i - 1;
+              }
+              else {
+                     channels[i] = i;
+              }
+       }
+
+       // Handle swap first (ROL of positions), example CMYK -> KCMY | 0123 -> 3012
+       if (T_SWAPFIRST(Format) && total_chans > 0) {
+
+              cmsUInt32Number tmp = channels[0];
+              for (i = 0; i < total_chans - 1; i++)
+                     channels[i] = channels[i + 1];
+
+              channels[total_chans - 1] = tmp;
+       }
+
+       // Handle size
+       for (i = 0; i < total_chans; i++) {
+              channels[i] *= BytesPerPlane;
+       }
+
+       for (i = 0; i < extra; i++)
+              ComponentStartingOrder[i] = channels[i + nchannels];
+}
+
+
+
+// Dispatcher por chunky and planar RGB
+static
+void  ComputeComponentIncrements(cmsUInt32Number Format,
+                                 cmsUInt32Number BytesPerPlane,
+                                 cmsUInt32Number ComponentStartingOrder[],
+                                 cmsUInt32Number ComponentPointerIncrements[])
+{
+       if (T_PLANAR(Format)) {
+
+              ComputeIncrementsForPlanar(Format,  BytesPerPlane, ComponentStartingOrder, ComponentPointerIncrements);
+       }
+       else {
+              ComputeIncrementsForChunky(Format,  ComponentStartingOrder, ComponentPointerIncrements);
+       }
+
+}
+
+
+
+// Handles extra channels copying alpha if requested by the flags
+void _cmsHandleExtraChannels(_cmsTRANSFORM* p, const void* in,
+                                               void* out,
+                                               cmsUInt32Number PixelsPerLine,
+                                               cmsUInt32Number LineCount,
+                                               const cmsStride* Stride)
+{
+    cmsUInt32Number i, j, k;
+    cmsUInt32Number nExtra;
+    cmsUInt32Number SourceStartingOrder[cmsMAXCHANNELS];
+    cmsUInt32Number SourceIncrements[cmsMAXCHANNELS];
+    cmsUInt32Number DestStartingOrder[cmsMAXCHANNELS];
+    cmsUInt32Number DestIncrements[cmsMAXCHANNELS];
+
+    cmsFormatterAlphaFn copyValueFn;
+
+    // Make sure we need some copy
+    if (!(p->dwOriginalFlags & cmsFLAGS_COPY_ALPHA))
+        return;
+
+    // Exit early if in-place color-management is occurring - no need to copy extra channels to themselves.
+    if (p->InputFormat == p->OutputFormat && in == out)
+        return;
+
+    // Make sure we have same number of alpha channels. If not, just return as this should be checked at transform creation time.
+    nExtra = T_EXTRA(p->InputFormat);
+    if (nExtra != T_EXTRA(p->OutputFormat))
+        return;
+
+    // Anything to do?
+    if (nExtra == 0)
+        return;
+
+    // Compute the increments
+    ComputeComponentIncrements(p->InputFormat, Stride->BytesPerPlaneIn, SourceStartingOrder, SourceIncrements);
+    ComputeComponentIncrements(p->OutputFormat, Stride->BytesPerPlaneOut, DestStartingOrder, DestIncrements);
+
+    // Check for conversions 8, 16, half, float, dbl
+    copyValueFn = _cmsGetFormatterAlpha(p->ContextID, p->InputFormat, p->OutputFormat);
+
+    if (nExtra == 1) { // Optimized routine for copying a single extra channel quickly
+
+        cmsUInt8Number* SourcePtr;
+        cmsUInt8Number* DestPtr;
+
+        cmsUInt32Number SourceStrideIncrement = 0;
+        cmsUInt32Number DestStrideIncrement = 0;
+
+        // The loop itself
+        for (i = 0; i < LineCount; i++) {
+
+            // Prepare pointers for the loop
+            SourcePtr = (cmsUInt8Number*)in + SourceStartingOrder[0] + SourceStrideIncrement;
+            DestPtr = (cmsUInt8Number*)out + DestStartingOrder[0] + DestStrideIncrement;
+
+            for (j = 0; j < PixelsPerLine; j++) {
+
+                copyValueFn(DestPtr, SourcePtr);
+
+                SourcePtr += SourceIncrements[0];
+                DestPtr += DestIncrements[0];
+            }
+
+            SourceStrideIncrement += Stride->BytesPerLineIn;
+            DestStrideIncrement += Stride->BytesPerLineOut;
+        }
+
+    }
+    else { // General case with more than one extra channel
+
+        cmsUInt8Number* SourcePtr[cmsMAXCHANNELS];
+        cmsUInt8Number* DestPtr[cmsMAXCHANNELS];
+
+        cmsUInt32Number SourceStrideIncrements[cmsMAXCHANNELS];
+        cmsUInt32Number DestStrideIncrements[cmsMAXCHANNELS];
+
+        memset(SourceStrideIncrements, 0, sizeof(SourceStrideIncrements));
+        memset(DestStrideIncrements, 0, sizeof(DestStrideIncrements));
+
+        // The loop itself
+        for (i = 0; i < LineCount; i++) {
+
+            // Prepare pointers for the loop
+            for (j = 0; j < nExtra; j++) {
+
+                SourcePtr[j] = (cmsUInt8Number*)in + SourceStartingOrder[j] + SourceStrideIncrements[j];
+                DestPtr[j] = (cmsUInt8Number*)out + DestStartingOrder[j] + DestStrideIncrements[j];
+            }
+
+            for (j = 0; j < PixelsPerLine; j++) {
+
+                for (k = 0; k < nExtra; k++) {
+
+                    copyValueFn(DestPtr[k], SourcePtr[k]);
+
+                    SourcePtr[k] += SourceIncrements[k];
+                    DestPtr[k] += DestIncrements[k];
+                }
+            }
+
+            for (j = 0; j < nExtra; j++) {
+
+                SourceStrideIncrements[j] += Stride->BytesPerLineIn;
+                DestStrideIncrements[j] += Stride->BytesPerLineOut;
+            }
+        }
+    }
+}
+
+
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
index 86ec167..ae7038c 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
index 5e5f296..c4f4fb5 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -625,7 +625,7 @@
 }
 
 // Parses a float number
-// This can not call directly atof because it uses locale dependant
+// This can not call directly atof because it uses locale dependent
 // parsing, while CCMX files always use . as decimal separator
 static
 cmsFloat64Number ParseFloatNumber(const char *Buffer)
@@ -830,11 +830,11 @@
 
                     if (it8 ->sy == SINUM) {
 
-                        sprintf(it8->id, "%d", it8->inum);
+                        snprintf(it8->id, 127, "%d", it8->inum);
                     }
                     else {
 
-                        sprintf(it8->id, it8 ->DoubleFormatter, it8->dnum);
+                        snprintf(it8->id, 127, it8 ->DoubleFormatter, it8->dnum);
                     }
 
                     k = (int) strlen(it8 ->id);
@@ -1392,7 +1392,7 @@
     cmsIT8* it8 = (cmsIT8*) hIT8;
     char Buffer[1024];
 
-    sprintf(Buffer, it8->DoubleFormatter, Val);
+    snprintf(Buffer, 1023, it8->DoubleFormatter, Val);
 
     return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_UNCOOKED) != NULL;
 }
@@ -1402,7 +1402,7 @@
     cmsIT8* it8 = (cmsIT8*) hIT8;
     char Buffer[1024];
 
-    sprintf(Buffer, "%u", Val);
+    snprintf(Buffer, 1023, "%u", Val);
 
     return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_HEXADECIMAL) != NULL;
 }
@@ -1846,7 +1846,7 @@
 }
 
 
-// -------------------------------------------------------------- Higer level parsing
+// -------------------------------------------------------------- Higher level parsing
 
 static
 cmsBool DataFormatSection(cmsIT8* it8)
@@ -2153,7 +2153,7 @@
 
 
 
-// Init usefull pointers
+// Init useful pointers
 
 static
 void CookPointers(cmsIT8* it8)
@@ -2550,9 +2550,9 @@
 
         fld = GetDataFormat(it8, i);
         if (fld != NULL) {
-        if (cmsstrcasecmp(fld, cSample) == 0)
-            return i;
-    }
+            if (cmsstrcasecmp(fld, cSample) == 0)
+                return i;
+        }
     }
 
     return -1;
@@ -2610,7 +2610,7 @@
 
     _cmsAssert(hIT8 != NULL);
 
-    sprintf(Buff, it8->DoubleFormatter, Val);
+    snprintf(Buff, 255, it8->DoubleFormatter, Val);
 
     return SetData(it8, row, col, Buff);
 }
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
index f6ef06c..2ac99be 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -136,7 +136,7 @@
 };
 
 
-// A pointer to the begining of the list
+// A pointer to the beginning of the list
 _cmsIntentsPluginChunkType _cmsIntentsPluginChunk = { NULL };
 
 // Duplicates the zone of memory used by the plug-in in the new context
@@ -299,6 +299,7 @@
     cmsMAT3 Scale, m1, m2, m3, m4;
 
     // TODO: Follow Marc Mahy's recommendation to check if CHAD is same by using M1*M2 == M2*M1. If so, do nothing.
+    // TODO: Add support for ArgyllArts tag
 
     // Adaptation state
     if (AdaptationState == 1.0) {
@@ -917,7 +918,7 @@
         return TRUE;
     }
 
-    // Make sure to pass thru K (which now is fixed)
+    // Make sure to pass through K (which now is fixed)
     Outf[3] = LabK[3];
 
     // Apply TAC if needed
@@ -985,7 +986,7 @@
     memset(&bp, 0, sizeof(bp));
 
     // We need the input LUT of the last profile, assuming this one is responsible of
-    // black generation. This LUT will be seached in inverse order.
+    // black generation. This LUT will be searched in inverse order.
     bp.LabK2cmyk = _cmsReadInputLUT(hProfiles[nProfiles-1], INTENT_RELATIVE_COLORIMETRIC);
     if (bp.LabK2cmyk == NULL) goto Cleanup;
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
index a708997..fc74aa7 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2015 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -227,7 +227,7 @@
     }
 }
 
-// Auxiliar to fill memory management functions from plugin (or context 0 defaults)
+// Auxiliary to fill memory management functions from plugin (or context 0 defaults)
 void _cmsInstallAllocFunctions(cmsPluginMemHandler* Plugin, _cmsMemPluginChunkType* ptr)
 {
     if (Plugin == NULL) {
@@ -459,14 +459,14 @@
 
 // Error logging ******************************************************************
 
-// There is no error handling at all. When a funtion fails, it returns proper value.
+// There is no error handling at all. When a function fails, it returns proper value.
 // For example, all create functions does return NULL on failure. Other return FALSE
 // It may be interesting, for the developer, to know why the function is failing.
 // for that reason, lcms2 does offer a logging function. This function does recive
 // a ENGLISH string with some clues on what is going wrong. You can show this
 // info to the end user, or just create some sort of log.
 // The logging function should NOT terminate the program, as this obviously can leave
-// resources. It is the programmer's responsability to check each function return code
+// resources. It is the programmer's responsibility to check each function return code
 // to make sure it didn't fail.
 
 // Error messages are limited to MAX_ERROR_MESSAGE_LEN
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
index e68f258..e940fe2 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
@@ -596,7 +596,7 @@
     return Val;
 }
 
-// Evaluate a segmented funtion for a single value. Return -1 if no valid segment found .
+// Evaluate a segmented function for a single value. Return -1 if no valid segment found .
 // If fn type is 0, perform an interpolation on the table
 static
 cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R)
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
index 0be9173..81254c2 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -56,7 +56,7 @@
 #include "lcms2_internal.h"
 
 
-// Auxiliar: append a Lab identity after the given sequence of profiles
+// Auxiliary: append a Lab identity after the given sequence of profiles
 // and return the transform. Lab profile is closed, rest of profiles are kept open.
 cmsHTRANSFORM _cmsChain2Lab(cmsContext            ContextID,
                             cmsUInt32Number        nProfiles,
@@ -201,7 +201,7 @@
     }
 
     // Build the relationship. This effectively limits the maximum accuracy to 16 bits, but
-    // since this is used on black-preserving LUTs, we are not loosing  accuracy in any case
+    // since this is used on black-preserving LUTs, we are not losing  accuracy in any case
     KTone = cmsJoinToneCurve(ContextID, in, out, nPoints);
 
     // Get rid of components
@@ -307,7 +307,7 @@
 }
 
 // Does compute a gamut LUT going back and forth across pcs -> relativ. colorimetric intent -> pcs
-// the dE obtained is then annotated on the LUT. Values truely out of gamut are clipped to dE = 0xFFFE
+// the dE obtained is then annotated on the LUT. Values truly out of gamut are clipped to dE = 0xFFFE
 // and values changed are supposed to be handled by any gamut remapping, so, are out of gamut as well.
 //
 // **WARNING: This algorithm does assume that gamut remapping algorithms does NOT move in-gamut colors,
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmshalf.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmshalf.c
index 11efe3a..ddcaf48 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmshalf.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmshalf.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
index 20175ef..aa96cbb 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -185,7 +185,7 @@
     int i;
     cmsUInt32Number Samples[MAX_INPUT_DIMENSIONS];
 
-    // Fill the auxiliar array
+    // Fill the auxiliary array
     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
         Samples[i] = nSamples;
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
index 3811ef9..f86f2e7 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -353,7 +353,7 @@
     return nReaded;
 }
 
-// Postion file pointer in the file
+// Position file pointer in the file
 static
 cmsBool  FileSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
 {
@@ -397,6 +397,7 @@
 {
     cmsIOHANDLER* iohandler = NULL;
     FILE* fm = NULL;
+    cmsInt32Number fileLen;
 
     _cmsAssert(FileName != NULL);
     _cmsAssert(AccessMode != NULL);
@@ -413,7 +414,16 @@
              cmsSignalError(ContextID, cmsERROR_FILE, "File '%s' not found", FileName);
             return NULL;
         }
-        iohandler -> ReportedSize = (cmsUInt32Number) cmsfilelength(fm);
+        fileLen = cmsfilelength(fm);
+        if (fileLen < 0)
+        {
+            fclose(fm);
+            _cmsFree(ContextID, iohandler);
+            cmsSignalError(ContextID, cmsERROR_FILE, "Cannot get size of file '%s'", FileName);
+            return NULL;
+        }
+
+        iohandler -> ReportedSize = (cmsUInt32Number) fileLen;
         break;
 
     case 'w':
@@ -453,6 +463,14 @@
 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromStream(cmsContext ContextID, FILE* Stream)
 {
     cmsIOHANDLER* iohandler = NULL;
+    cmsInt32Number fileSize;
+
+    fileSize = cmsfilelength(Stream);
+    if (fileSize < 0)
+    {
+        cmsSignalError(ContextID, cmsERROR_FILE, "Cannot get size of stream");
+        return NULL;
+    }
 
     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
     if (iohandler == NULL) return NULL;
@@ -460,7 +478,7 @@
     iohandler -> ContextID = ContextID;
     iohandler -> stream = (void*) Stream;
     iohandler -> UsedSpace = 0;
-    iohandler -> ReportedSize = (cmsUInt32Number) cmsfilelength(Stream);
+    iohandler -> ReportedSize = (cmsUInt32Number) fileSize;
     iohandler -> PhysicalFile[0] = 0;
 
     iohandler ->Read    = FileRead;
@@ -652,7 +670,7 @@
 }
 
 
-// Check existance
+// Check existence
 cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
 {
        _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) (void*) hProfile;
@@ -708,7 +726,7 @@
         return FALSE;
     }
 
-    // Adjust endianess of the used parameters
+    // Adjust endianness of the used parameters
     Icc -> DeviceClass     = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
     Icc -> ColorSpace      = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.colorSpace);
     Icc -> PCS             = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.pcs);
@@ -826,7 +844,7 @@
 
     memset(&Header.reserved, 0, sizeof(Header.reserved));
 
-    // Set profile ID. Endianess is always big endian
+    // Set profile ID. Endianness is always big endian
     memmove(&Header.profileID, &Icc ->ProfileID, 16);
 
     // Dump the header
@@ -836,7 +854,7 @@
 
     // Get true count
     for (i=0;  i < Icc -> TagCount; i++) {
-        if (Icc ->TagNames[i] != 0)
+        if (Icc ->TagNames[i] != (cmsTagSignature) 0)
             Count++;
     }
 
@@ -845,7 +863,7 @@
 
     for (i=0; i < Icc -> TagCount; i++) {
 
-        if (Icc ->TagNames[i] == 0) continue;   // It is just a placeholder
+        if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;   // It is just a placeholder
 
         Tag.sig    = (cmsTagSignature) _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagNames[i]);
         Tag.offset = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagOffsets[i]);
@@ -1195,7 +1213,7 @@
 
     for (i=0; i < Icc -> TagCount; i++) {
 
-        if (Icc ->TagNames[i] == 0) continue;
+        if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;
 
         // Linked tags are not written
         if (Icc ->TagLinked[i] != (cmsTagSignature) 0) continue;
@@ -1329,11 +1347,15 @@
 
     _cmsAssert(hProfile != NULL);
 
+    if (!_cmsLockMutex(Icc->ContextID, Icc->UsrMutex)) return 0;
     memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
 
     ContextID = cmsGetProfileContextID(hProfile);
     PrevIO = Icc ->IOhandler = cmsOpenIOhandlerFromNULL(ContextID);
-    if (PrevIO == NULL) return 0;
+    if (PrevIO == NULL) {
+        _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
+        return 0;
+    }
 
     // Pass #1 does compute offsets
 
@@ -1353,7 +1375,10 @@
     }
 
     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
-    if (!cmsCloseIOhandler(PrevIO)) return 0;
+    if (!cmsCloseIOhandler(PrevIO))
+        UsedSpace = 0; // As a error marker
+
+    _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
 
     return UsedSpace;
 
@@ -1361,6 +1386,8 @@
 Error:
     cmsCloseIOhandler(PrevIO);
     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
+    _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
+
     return 0;
 }
 
@@ -1571,7 +1598,7 @@
     LocalTypeHandler.ICCVersion = Icc ->Version;
     Icc -> TagPtrs[n] = LocalTypeHandler.ReadPtr(&LocalTypeHandler, io, &ElemCount, TagSize);
 
-    // The tag type is supported, but something wrong happend and we cannot read the tag.
+    // The tag type is supported, but something wrong happened and we cannot read the tag.
     // let know the user about this (although it is just a warning)
     if (Icc -> TagPtrs[n] == NULL) {
 
@@ -1890,7 +1917,7 @@
     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
 
     if (Icc->TagPtrs[i] == NULL) {
-           Icc->TagNames[i] = 0;
+           Icc->TagNames[i] = (cmsTagSignature) 0;
            return FALSE;
     }
     return TRUE;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
index 4c259f8..c478b2e 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -157,7 +157,7 @@
 }
 
 
-// Auxiliar, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
+// Auxiliary, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
 static
 cmsBool ReadICCMatrixRGB2XYZ(cmsMAT3* r, cmsHPROFILE hProfile)
 {
@@ -343,7 +343,7 @@
     cmsTagSignature tagFloat;
     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
-    // On named color, take the appropiate tag
+    // On named color, take the appropriate tag
     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
 
         cmsPipeline* Lut;
@@ -365,9 +365,9 @@
         return Lut;
     }
 
-    // This is an attempt to reuse this funtion to retrieve the matrix-shaper as pipeline no
+    // This is an attempt to reuse this function to retrieve the matrix-shaper as pipeline no
     // matter other LUT are present and have precedence. Intent = -1 means just this.
-    if (Intent != -1) {
+    if (Intent >= INTENT_PERCEPTUAL && Intent <= INTENT_ABSOLUTE_COLORIMETRIC) {
 
         tag16 = Device2PCS16[Intent];
         tagFloat = Device2PCSFloat[Intent];
@@ -423,7 +423,7 @@
     // Check if this is a grayscale profile.
     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
 
-        // if so, build appropiate conversion tables.
+        // if so, build appropriate conversion tables.
         // The tables are the PCS iluminant, scaled across GrayTRC
         return BuildGrayInputMatrixPipeline(hProfile);
     }
@@ -578,7 +578,7 @@
     if (Lut == NULL) return NULL;
 
     // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding,
-    // and since the formatter has already accomodated to 0..1.0, we should undo this change
+    // and since the formatter has already accommodated to 0..1.0, we should undo this change
     if ( PCS == cmsSigLabData)
     {
         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
@@ -619,7 +619,7 @@
     cmsContext ContextID  = cmsGetProfileContextID(hProfile);
 
 
-    if (Intent != -1) {
+    if (Intent >= INTENT_PERCEPTUAL && Intent <= INTENT_ABSOLUTE_COLORIMETRIC) {
 
         tag16 = PCS2Device16[Intent];
         tagFloat = PCS2DeviceFloat[Intent];
@@ -680,7 +680,7 @@
     // Check if this is a grayscale profile.
     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
 
-        // if so, build appropiate conversion tables.
+        // if so, build appropriate conversion tables.
         // The tables are the PCS iluminant, scaled across GrayTRC
         return BuildGrayOutputPipeline(hProfile);
     }
@@ -738,15 +738,21 @@
 {
     cmsPipeline* Lut;
     cmsTagTypeSignature OriginalType;
-    cmsTagSignature tag16    = Device2PCS16[Intent];
-    cmsTagSignature tagFloat = Device2PCSFloat[Intent];
+    cmsTagSignature tag16;
+    cmsTagSignature tagFloat;
     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
 
-    // On named color, take the appropiate tag
+    if (Intent < INTENT_PERCEPTUAL || Intent > INTENT_ABSOLUTE_COLORIMETRIC)
+        return NULL;
+
+    tag16 = Device2PCS16[Intent];
+    tagFloat = Device2PCSFloat[Intent];
+
+    // On named color, take the appropriate tag
     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
 
-        cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, cmsSigNamedColor2Tag);
+        cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*)cmsReadTag(hProfile, cmsSigNamedColor2Tag);
 
         if (nc == NULL) return NULL;
 
@@ -762,12 +768,13 @@
                 goto Error;
 
         return Lut;
-Error:
+    Error:
         cmsPipelineFree(Lut);
         cmsFreeNamedColorList(nc);
         return NULL;
     }
 
+
     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 
         // Floating point LUT are always V
@@ -777,19 +784,19 @@
     tagFloat = Device2PCSFloat[0];
     if (cmsIsTag(hProfile, tagFloat)) {
 
-        return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
+        return cmsPipelineDup((cmsPipeline*)cmsReadTag(hProfile, tagFloat));
     }
 
     if (!cmsIsTag(hProfile, tag16)) {  // Is there any LUT-Based table?
 
-        tag16    = Device2PCS16[0];
+        tag16 = Device2PCS16[0];
         if (!cmsIsTag(hProfile, tag16)) return NULL;
     }
 
     // Check profile version and LUT type. Do the necessary adjustments if needed
 
     // Read the tag
-    Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
+    Lut = (cmsPipeline*)cmsReadTag(hProfile, tag16);
     if (Lut == NULL) return NULL;
 
     // The profile owns the Lut, so we need to copy it
@@ -802,7 +809,7 @@
         ChangeInterpolationToTrilinear(Lut);
 
     // After reading it, we have info about the original type
-    OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
+    OriginalType = _cmsGetTagTrueType(hProfile, tag16);
 
     // We need to adjust data for Lab16 on output
     if (OriginalType != cmsSigLut16Type) return Lut;
@@ -810,12 +817,12 @@
     // Here it is possible to get Lab on both sides
 
     if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
-        if(!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
+        if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
             goto Error2;
     }
 
     if (cmsGetPCS(hProfile) == cmsSigLabData) {
-        if(!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+        if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
             goto Error2;
     }
 
@@ -950,7 +957,7 @@
 }
 
 
-// Auxiliar, read and duplicate a MLU if found.
+// Auxiliary, read and duplicate a MLU if found.
 static
 cmsMLU* GetMLUFromProfile(cmsHPROFILE h, cmsTagSignature sig)
 {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
index 4c04ee9..6c4b8ce 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -534,7 +534,7 @@
                 goto Error;
         } else {
             NewElem ->Tab.T = (cmsUInt16Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.T, Data ->nEntries * sizeof (cmsUInt16Number));
-            if (NewElem ->Tab.TFloat == NULL)
+            if (NewElem ->Tab.T == NULL)
                 goto Error;
         }
     }
@@ -1482,7 +1482,8 @@
                  First = FALSE;
              }
              else {
-                Anterior ->Next = NewMPE;
+                if (Anterior != NULL)
+                    Anterior ->Next = NewMPE;
              }
 
             Anterior = NewMPE;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
index c238e41..619c94e 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c
index ed9366c..2bc6a49 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -67,7 +67,7 @@
     r -> n[VZ] = z;
 }
 
-// Vector substraction
+// Vector subtraction
 void CMSEXPORT _cmsVEC3minus(cmsVEC3* r, const cmsVEC3* a, const cmsVEC3* b)
 {
   r -> n[VX] = a -> n[VX] - b -> n[VX];
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
index 52e2d86..d1edeb4 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -121,7 +121,7 @@
 static
 cmsBool GrowMLUtable(cmsMLU* mlu)
 {
-    int AllocatedEntries;
+    cmsUInt32Number AllocatedEntries;
     _cmsMLUentry *NewPtr;
 
     // Sanity check
@@ -147,7 +147,7 @@
 static
 int SearchMLUEntry(cmsMLU* mlu, cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode)
 {
-    int i;
+    cmsUInt32Number i;
 
     // Sanity check
     if (mlu == NULL) return -1;
@@ -207,15 +207,42 @@
     return TRUE;
 }
 
+// Convert from a 3-char code to a cmsUInt16Number. It is done inthis way because some
+// compilers don't properly align beginning of strings
 
-// Add an ASCII entry.
+static
+cmsUInt16Number strTo16(const char str[3])
+{
+    cmsUInt16Number n = ((cmsUInt16Number) str[0] << 8) | str[1];
+
+    return n;  // Always big endian in this case
+}
+
+static
+void strFrom16(char str[3], cmsUInt16Number n)
+{
+    // Assiming this would be aligned
+    union {
+
+       cmsUInt16Number n;
+       char str[2];
+
+    } c;
+
+    c.n = n;  // Always big endian in this case
+
+    str[0] = c.str[0]; str[1] = c.str[1]; str[2] = 0;
+
+}
+
+// Add an ASCII entry. Do not add any \0 termination (ICC1v43_2010-12.pdf page 61)
 cmsBool CMSEXPORT cmsMLUsetASCII(cmsMLU* mlu, const char LanguageCode[3], const char CountryCode[3], const char* ASCIIString)
 {
-    cmsUInt32Number i, len = (cmsUInt32Number) strlen(ASCIIString)+1;
+    cmsUInt32Number i, len = (cmsUInt32Number) strlen(ASCIIString);
     wchar_t* WStr;
     cmsBool  rc;
-    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
-    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
+    cmsUInt16Number Lang  = strTo16(LanguageCode);
+    cmsUInt16Number Cntry = strTo16(CountryCode);
 
     if (mlu == NULL) return FALSE;
 
@@ -245,18 +272,17 @@
     return (cmsUInt32Number)(p - s);
 }
 
-
-// Add a wide entry
+// Add a wide entry. Do not add any \0 terminator (ICC1v43_2010-12.pdf page 61)
 cmsBool  CMSEXPORT cmsMLUsetWide(cmsMLU* mlu, const char Language[3], const char Country[3], const wchar_t* WideString)
 {
-    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) Language);
-    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) Country);
+    cmsUInt16Number Lang  = strTo16(Language);
+    cmsUInt16Number Cntry = strTo16(Country);
     cmsUInt32Number len;
 
     if (mlu == NULL) return FALSE;
     if (WideString == NULL) return FALSE;
 
-    len = (cmsUInt32Number) (mywcslen(WideString) + 1) * sizeof(wchar_t);
+    len = (cmsUInt32Number) (mywcslen(WideString)) * sizeof(wchar_t);
     return AddMLUBlock(mlu, len, WideString, Lang, Cntry);
 }
 
@@ -327,8 +353,8 @@
                               cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode,
                               cmsUInt16Number* UsedLanguageCode, cmsUInt16Number* UsedCountryCode)
 {
-    int i;
-    int Best = -1;
+    cmsUInt32Number i;
+    cmsInt32Number Best = -1;
     _cmsMLUentry* v;
 
     if (mlu == NULL) return NULL;
@@ -379,8 +405,8 @@
     cmsUInt32Number  StrLen = 0;
     cmsUInt32Number ASCIIlen, i;
 
-    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
-    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
+    cmsUInt16Number Lang  = strTo16(LanguageCode);
+    cmsUInt16Number Cntry = strTo16(CountryCode);
 
     // Sanitize
     if (mlu == NULL) return 0;
@@ -423,8 +449,8 @@
     const wchar_t *Wide;
     cmsUInt32Number  StrLen = 0;
 
-    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
-    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
+    cmsUInt16Number Lang  = strTo16(LanguageCode);
+    cmsUInt16Number Cntry = strTo16(CountryCode);
 
     // Sanitize
     if (mlu == NULL) return 0;
@@ -456,8 +482,8 @@
 {
     const wchar_t *Wide;
 
-    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
-    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
+    cmsUInt16Number Lang  = strTo16(LanguageCode);
+    cmsUInt16Number Cntry = strTo16(CountryCode);
     cmsUInt16Number ObtLang, ObtCode;
 
     // Sanitize
@@ -467,10 +493,9 @@
     if (Wide == NULL) return FALSE;
 
     // Get used language and code
-    *(cmsUInt16Number *)ObtainedLanguage = _cmsAdjustEndianess16(ObtLang);
-    *(cmsUInt16Number *)ObtainedCountry  = _cmsAdjustEndianess16(ObtCode);
+    strFrom16(ObtainedLanguage, ObtLang);
+    strFrom16(ObtainedCountry, ObtCode);
 
-    ObtainedLanguage[2] = ObtainedCountry[2] = 0;
     return TRUE;
 }
 
@@ -493,12 +518,12 @@
 
     if (mlu == NULL) return FALSE;
 
-    if (idx >= (cmsUInt32Number) mlu->UsedEntries) return FALSE;
+    if (idx >= mlu->UsedEntries) return FALSE;
 
     entry = &mlu->Entries[idx];
 
-    *(cmsUInt16Number *)LanguageCode = _cmsAdjustEndianess16(entry->Language);
-    *(cmsUInt16Number *)CountryCode  = _cmsAdjustEndianess16(entry->Country);
+    strFrom16(LanguageCode, entry->Language);
+    strFrom16(CountryCode, entry->Country);
 
     return TRUE;
 }
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
index b7783b2..a3ff2fc 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
@@ -27,11 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
-
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2011 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -258,11 +257,10 @@
 
                             // We can not get rid of full matrix
                             cmsStage* Multmat = cmsStageAllocMatrix(Lut->ContextID, 3, 3, (const cmsFloat64Number*) &res, NULL);
+                            if (Multmat == NULL) return FALSE;  // Should never happen
 
                             // Recover the chain
-                            if (Multmat != NULL) {
                             Multmat->Next = chain;
-                            }
                             *pt1 = Multmat;
                      }
 
@@ -560,7 +558,7 @@
             return TRUE;
 }
 
-// Auxiliar, to see if two values are equal or very different
+// Auxiliary, to see if two values are equal or very different
 static
 cmsBool WhitesAreEqual(int n, cmsUInt16Number White1[], cmsUInt16Number White2[] )
 {
@@ -568,7 +566,7 @@
 
     for (i=0; i < n; i++) {
 
-        if (abs(White1[i] - White2[i]) > 0xf000) return TRUE;  // Values are so extremly different that the fixup should be avoided
+        if (abs(White1[i] - White2[i]) > 0xf000) return TRUE;  // Values are so extremely different that the fixup should be avoided
         if (White1[i] != White2[i]) return FALSE;
     }
     return TRUE;
@@ -706,7 +704,7 @@
         cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src);
 
         // Check if suitable
-        if (PreLin ->Type == cmsSigCurveSetElemType) {
+        if (PreLin && PreLin ->Type == cmsSigCurveSetElemType) {
 
             // Maybe this is a linear tram, so we can avoid the whole stuff
             if (!AllCurvesAreLinear(PreLin)) {
@@ -739,7 +737,7 @@
         cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src);
 
         // Check if suitable
-        if (cmsStageType(PostLin) == cmsSigCurveSetElemType) {
+        if (PostLin && cmsStageType(PostLin) == cmsSigCurveSetElemType) {
 
             // Maybe this is a linear tram, so we can avoid the whole stuff
             if (!AllCurvesAreLinear(PostLin)) {
@@ -1041,8 +1039,8 @@
     }
 
     if (Zeros == 1 && Poles == 1) return FALSE;  // For linear tables
-    if (Zeros > (nEntries / 4)) return TRUE;  // Degenerated, mostly zeros
-    if (Poles > (nEntries / 4)) return TRUE;  // Degenerated, mostly poles
+    if (Zeros > (nEntries / 20)) return TRUE;  // Degenerated, many zeros
+    if (Poles > (nEntries / 20)) return TRUE;  // Degenerated, many poles
 
     return FALSE;
 }
@@ -1064,17 +1062,19 @@
     cmsColorSpaceSignature ColorSpace, OutputColorSpace;
     cmsStage* OptimizedPrelinMpe;
     cmsStage* mpe;
-    cmsToneCurve**   OptimizedPrelinCurves;
-    _cmsStageCLutData*     OptimizedPrelinCLUT;
+    cmsToneCurve** OptimizedPrelinCurves;
+    _cmsStageCLutData* OptimizedPrelinCLUT;
 
 
     // This is a loosy optimization! does not apply in floating-point cases
     if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
 
-    // Only on RGB
+    // Only on chunky RGB
     if (T_COLORSPACE(*InputFormat)  != PT_RGB) return FALSE;
-    if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;
+    if (T_PLANAR(*InputFormat)) return FALSE;
 
+    if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;
+    if (T_PLANAR(*OutputFormat)) return FALSE;
 
     // On 16 bits, user has to specify the feature
     if (!_cmsFormatterIs8bit(*InputFormat)) {
@@ -1098,6 +1098,22 @@
     memset(Trans, 0, sizeof(Trans));
     memset(TransReverse, 0, sizeof(TransReverse));
 
+    // If the last stage of the original lut are curves, and those curves are
+    // degenerated, it is likely the transform is squeezing and clipping
+    // the output from previous CLUT. We cannot optimize this case
+    {
+        cmsStage* last = cmsPipelineGetPtrToLastStage(OriginalLut);
+
+        if (cmsStageType(last) == cmsSigCurveSetElemType) {
+
+            _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*)cmsStageData(last);
+            for (i = 0; i < Data->nCurves; i++) {
+                if (IsDegenerated(Data->TheCurves[i]))
+                    goto Error;
+            }
+        }
+    }
+
     for (t = 0; t < OriginalLut ->InputChannels; t++) {
         Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL);
         if (Trans[t] == NULL) goto Error;
@@ -1431,7 +1447,10 @@
         GammaTables[i] = NULL;
     }
 
-    if (GammaTables != NULL) _cmsFree(Src ->ContextID, GammaTables);
+    if (GammaTables != NULL) {
+        _cmsFree(Src->ContextID, GammaTables);
+        GammaTables = NULL;
+    }
 
     // Maybe the curves are linear at the end
     if (!AllCurvesAreLinear(ObtainedCurves)) {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
index e389c4e..a9087f6 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2010 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -110,7 +110,7 @@
 #define ANYFLAVOR       FLAVOR_SH(1)
 
 
-// Supress waning about info never being used
+// Suppress waning about info never being used
 
 #ifdef _MSC_VER
 #pragma warning(disable : 4100)
@@ -3188,6 +3188,8 @@
     cmsUInt32Number i;
     cmsFormatter fr;
 
+    // Optimization is only a hint
+    dwInput &= ~OPTIMIZED_SH(1);
 
     switch (dwFlags)
     {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
index d4ef694..f2ebf53 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2010 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -337,7 +337,7 @@
     wLab[2] = ab2Fix4(Lab.b);
 }
 
-// Auxiliar: convert to Radians
+// Auxiliary: convert to Radians
 static
 cmsFloat64Number RADIANS(cmsFloat64Number deg)
 {
@@ -345,7 +345,7 @@
 }
 
 
-// Auxiliar: atan2 but operating in degrees and returning 0 if a==b==0
+// Auxiliary: atan2 but operating in degrees and returning 0 if a==b==0
 static
 cmsFloat64Number atan2deg(cmsFloat64Number a, cmsFloat64Number b)
 {
@@ -368,7 +368,7 @@
 }
 
 
-// Auxiliar: Square
+// Auxiliary: Square
 static
 cmsFloat64Number Sqr(cmsFloat64Number v)
 {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
index 4443820..683c830 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2010 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -136,7 +136,7 @@
 #endif
 }
 
-// Auxiliar -- read 8, 16 and 32-bit numbers
+// Auxiliary -- read 8, 16 and 32-bit numbers
 cmsBool CMSEXPORT  _cmsReadUInt8Number(cmsIOHANDLER* io, cmsUInt8Number* n)
 {
     cmsUInt8Number tmp;
@@ -201,13 +201,13 @@
 
     _cmsAssert(io != NULL);
 
-    if (io -> Read(io, &tmp, sizeof(cmsFloat32Number), 1) != 1)
+    if (io -> Read(io, &tmp, sizeof(cmsUInt32Number), 1) != 1)
             return FALSE;
 
     if (n != NULL) {
 
         tmp = _cmsAdjustEndianess32(tmp);
-        *n = *(cmsFloat32Number*) &tmp;
+        *n = *(cmsFloat32Number*) (void*) &tmp;
     }
     return TRUE;
 }
@@ -244,22 +244,6 @@
 }
 
 
-// Jun-21-2000: Some profiles (those that comes with W2K) comes
-// with the media white (media black?) x 100. Add a sanity check
-
-static
-void NormalizeXYZ(cmsCIEXYZ* Dest)
-{
-    while (Dest -> X > 2. &&
-           Dest -> Y > 2. &&
-           Dest -> Z > 2.) {
-
-               Dest -> X /= 10.;
-               Dest -> Y /= 10.;
-               Dest -> Z /= 10.;
-       }
-}
-
 cmsBool CMSEXPORT  _cmsReadXYZNumber(cmsIOHANDLER* io, cmsCIEXYZ* XYZ)
 {
     cmsEncodedXYZNumber xyz;
@@ -273,8 +257,6 @@
         XYZ->X = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.X));
         XYZ->Y = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.Y));
         XYZ->Z = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.Z));
-
-        NormalizeXYZ(XYZ);
     }
     return TRUE;
 }
@@ -336,7 +318,7 @@
 
     _cmsAssert(io != NULL);
 
-    tmp = *(cmsUInt32Number*) &n;
+    tmp = *(cmsUInt32Number*) (void*) &n;
     tmp = _cmsAdjustEndianess32(tmp);
     if (io -> Write(io, sizeof(cmsUInt32Number), &tmp) != 1)
             return FALSE;
@@ -532,7 +514,10 @@
     va_start(args, frm);
 
     len = vsnprintf((char*) Buffer, 2047, frm, args);
-    if (len < 0) return FALSE;   // Truncated, which is a fatal error for us
+    if (len < 0) {
+        va_end(args);
+        return FALSE;   // Truncated, which is a fatal error for us
+    }
 
     rc = io ->Write(io, len, Buffer);
 
@@ -554,6 +539,7 @@
         if (ContextID == NULL) {
 
             ctx->MemPool = _cmsCreateSubAlloc(0, 2*1024);
+            if (ctx->MemPool == NULL) return NULL;
         }
         else {
             cmsSignalError(ContextID, cmsERROR_CORRUPTION_DETECTED, "NULL memory pool on context");
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
index 22089d0..03d476b 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2011 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -608,7 +608,7 @@
 //
 //  Each row contains Pipeline values for all but first component. So, I
 //  detect row changing by keeping a copy of last value of first
-//  component. -1 is used to mark begining of whole block.
+//  component. -1 is used to mark beginning of whole block.
 
 static
 int OutputValueSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
@@ -1422,14 +1422,15 @@
     if (nColorant > cmsMAXCHANNELS)
         nColorant = cmsMAXCHANNELS;
 
-    for (j=0; j < nColorant; j++) {
+    for (j = 0; j < nColorant; j++) {
 
-                sprintf(Buff, "%.3f", Out[j] / 65535.0);
-                strcat(Colorant, Buff);
-                if (j < nColorant -1)
-                        strcat(Colorant, " ");
+        snprintf(Buff, 31, "%.3f", Out[j] / 65535.0);
+        Buff[31] = 0;
+        strcat(Colorant, Buff);
+        if (j < nColorant - 1)
+            strcat(Colorant, " ");
 
-        }
+    }
 }
 
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
index bcd9d50..b22c427 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2014 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssm.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssm.c
index 783f3c3..1923a02 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssm.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssm.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2011 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -247,7 +247,8 @@
 {
     cmsFloat64Number a, b, c, d, e, D;
     cmsFloat64Number sc, sN, sD;
-    cmsFloat64Number tc, tN, tD;
+    //cmsFloat64Number tc; // left for future use
+    cmsFloat64Number tN, tD;
     cmsVEC3 w0;
 
     _cmsVEC3minus(&w0, &line1 ->a, &line2 ->a);
@@ -315,7 +316,7 @@
     }
     // finally do the division to get sc and tc
     sc = (fabs(sN) < MATRIX_DET_TOLERANCE ? 0.0 : sN / sD);
-    tc = (fabs(tN) < MATRIX_DET_TOLERANCE ? 0.0 : tN / tD);
+    //tc = (fabs(tN) < MATRIX_DET_TOLERANCE ? 0.0 : tN / tD); // left for future use.
 
     GetPointOfLine(r, line1, sc);
     return TRUE;
@@ -346,7 +347,7 @@
 }
 
 
-// Auxiliar to retrieve a pointer to the segmentr containing the Lab value
+// Auxiliary to retrieve a pointer to the segmentr containing the Lab value
 static
 cmsGDBPoint* GetPoint(cmsGDB* gbd, const cmsCIELab* Lab, cmsSpherical* sp)
 {
@@ -358,7 +359,7 @@
     _cmsAssert(Lab != NULL);
     _cmsAssert(sp != NULL);
 
-    // Center L* by substracting half of its domain, that's 50
+    // Center L* by subtracting half of its domain, that's 50
     _cmsVEC3init(&v, Lab ->L - 50.0, Lab ->a, Lab ->b);
 
     // Convert to spherical coordinates
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
index 7519f45..95fe4d1 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2014 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -59,7 +59,7 @@
 // This file implements every single tag and tag type as described in the ICC spec. Some types
 // have been deprecated, like ncl and Data. There is no implementation for those types as there
 // are no profiles holding them. The programmer can also extend this list by defining his own types
-// by using the appropiate plug-in. There are three types of plug ins regarding that. First type
+// by using the appropriate plug-in. There are three types of plug ins regarding that. First type
 // allows to define new tags using any existing type. Next plug-in type allows to define new types
 // and the third one is very specific: allows to extend the number of elements in the multiprocessing
 // elements special type.
@@ -142,7 +142,7 @@
 }
 
 
-// Auxiliar to convert UTF-32 to UTF-16 in some cases
+// Auxiliary to convert UTF-32 to UTF-16 in some cases
 static
 cmsBool _cmsWriteWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, const wchar_t* Array)
 {
@@ -158,7 +158,7 @@
     return TRUE;
 }
 
-// Auxiliar to read an array of wchar_t
+// Auxiliary to read an array of wchar_t
 static
 cmsBool _cmsReadWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, wchar_t* Array)
 {
@@ -189,7 +189,7 @@
                                              cmsUInt32Number n,
                                              cmsUInt32Number SizeOfTag);
 
-// Helper function to deal with position tables as decribed in ICC spec 4.3
+// Helper function to deal with position tables as described in ICC spec 4.3
 // A table of n elements is readed, where first comes n records containing offsets and sizes and
 // then a block containing the data itself. This allows to reuse same data in more than one entry
 static
@@ -980,7 +980,7 @@
     cmsMLU* mlu = (cmsMLU*) Ptr;
     char *Text = NULL;
     wchar_t *Wide = NULL;
-    cmsUInt32Number len, len_aligned, len_filler_alignment;
+    cmsUInt32Number len, len_text, len_tag_requirement, len_aligned;
     cmsBool  rc = FALSE;
     char Filler[68];
 
@@ -990,17 +990,18 @@
     // Get the len of string
     len = cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, NULL, 0);
 
-    // From ICC3.4: It has been found that textDescriptionType can contain misaligned data
+    // Specification ICC.1:2001-04 (v2.4.0): It has been found that textDescriptionType can contain misaligned data
     //(see clause 4.1 for the definition of “aligned”). Because the Unicode language
     // code and Unicode count immediately follow the ASCII description, their
     // alignment is not correct if the ASCII count is not a multiple of four. The
     // ScriptCode code is misaligned when the ASCII count is odd. Profile reading and
     // writing software must be written carefully in order to handle these alignment
     // problems.
-
-    // Compute an aligned size
-    len_aligned = _cmsALIGNLONG(len);
-    len_filler_alignment = len_aligned - len;
+    //
+    // The above last sentence suggest to handle alignment issues in the
+    // parser. The provided example (Table 69 on Page 60) makes this clear.
+    // The padding only in the ASCII count is not sufficient for a aligned tag
+    // size, with the same text size in ASCII and Unicode.
 
     // Null strings
     if (len <= 0) {
@@ -1021,6 +1022,12 @@
         cmsMLUgetWide(mlu,  cmsNoLanguage, cmsNoCountry,  Wide, len * sizeof(wchar_t));
     }
 
+    // Tell the real text len including the null terminator and padding
+    len_text = (cmsUInt32Number) strlen(Text) + 1;
+    // Compute an total tag size requirement
+    len_tag_requirement = (8+4+len_text+4+4+2*len_text+2+1+67);
+    len_aligned = _cmsALIGNLONG(len_tag_requirement);
+
   // * cmsUInt32Number       count;          * Description length
   // * cmsInt8Number         desc[count]     * NULL terminated ascii string
   // * cmsUInt32Number       ucLangCode;     * UniCode language code
@@ -1030,20 +1037,14 @@
   // * cmsUInt8Number        scCount;        * ScriptCode count
   // * cmsInt8Number         scDesc[67];     * ScriptCode Description
 
-    if (!_cmsWriteUInt32Number(io, len_aligned)) goto Error;
-    if (!io ->Write(io, len, Text)) goto Error;
-    if (!io ->Write(io, len_filler_alignment, Filler)) goto Error;
+    if (!_cmsWriteUInt32Number(io, len_text)) goto Error;
+    if (!io ->Write(io, len_text, Text)) goto Error;
 
     if (!_cmsWriteUInt32Number(io, 0)) goto Error;  // ucLanguageCode
 
-    // This part is tricky: we need an aligned tag size, and the ScriptCode part
-    // takes 70 bytes, so we need 2 extra bytes to do the alignment
-
-    if (!_cmsWriteUInt32Number(io, len_aligned+1)) goto Error;
-
+    if (!_cmsWriteUInt32Number(io, len_text)) goto Error;
     // Note that in some compilers sizeof(cmsUInt16Number) != sizeof(wchar_t)
-    if (!_cmsWriteWCharArray(io, len, Wide)) goto Error;
-    if (!_cmsWriteUInt16Array(io, len_filler_alignment+1, (cmsUInt16Number*) Filler)) goto Error;
+    if (!_cmsWriteWCharArray(io, len_text, Wide)) goto Error;
 
     // ScriptCode Code & count (unused)
     if (!_cmsWriteUInt16Number(io, 0)) goto Error;
@@ -1051,6 +1052,10 @@
 
     if (!io ->Write(io, 67, Filler)) goto Error;
 
+    // possibly add pad at the end of tag
+    if(len_aligned - len_tag_requirement > 0)
+      if (!io ->Write(io, len_aligned - len_tag_requirement, Filler)) goto Error;
+
     rc = TRUE;
 
 Error:
@@ -1499,7 +1504,7 @@
             LargestPosition = EndOfThisString;
     }
 
-    // Now read the remaining of tag and fill all strings. Substract the directory
+    // Now read the remaining of tag and fill all strings. Subtract the directory
     SizeOfTag   = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
     if (SizeOfTag == 0)
     {
@@ -1533,7 +1538,7 @@
     cmsMLU* mlu =(cmsMLU*) Ptr;
     cmsUInt32Number HeaderSize;
     cmsUInt32Number  Len, Offset;
-    int i;
+    cmsUInt32Number i;
 
     if (Ptr == NULL) {
 
@@ -3134,6 +3139,8 @@
 
         memset(Colorant, 0, sizeof(Colorant));
         if (io -> Read(io, Root, 32, 1) != 1) return NULL;
+        Root[32] = 0;  // To prevent exploits
+
         if (!_cmsReadUInt16Array(io, 3, PCS)) goto Error;
         if (!_cmsReadUInt16Array(io, nDeviceCoords, Colorant)) goto Error;
 
@@ -3156,8 +3163,8 @@
 cmsBool Type_NamedColor_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
 {
     cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr;
-    char                prefix[32];     // Prefix for each color name
-    char                suffix[32];     // Suffix for each color name
+    char                prefix[33];     // Prefix for each color name
+    char                suffix[33];     // Suffix for each color name
     int i, nColors;
 
     nColors = cmsNamedColorCount(NamedColorList);
@@ -3169,7 +3176,7 @@
     strncpy(prefix, (const char*) NamedColorList->Prefix, 32);
     strncpy(suffix, (const char*) NamedColorList->Suffix, 32);
 
-    suffix[31] = prefix[31] = 0;
+    suffix[32] = prefix[32] = 0;
 
     if (!io ->Write(io, 32, prefix)) return FALSE;
     if (!io ->Write(io, 32, suffix)) return FALSE;
@@ -3181,6 +3188,7 @@
        char Root[33];
 
         if (!cmsNamedColorInfo(NamedColorList, i, Root, NULL, NULL, PCS, Colorant)) return 0;
+        Root[32] = 0;
         if (!io ->Write(io, 32 , Root)) return FALSE;
         if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE;
         if (!_cmsWriteUInt16Array(io, NamedColorList ->ColorantCount, Colorant)) return FALSE;
@@ -3631,7 +3639,7 @@
 
 
 
-// Auxiliar, read an string specified as count + string
+// Auxiliary, read an string specified as count + string
 static
 cmsBool  ReadCountAndSting(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* mlu, cmsUInt32Number* SizeOfTag, const char* Section)
 {
@@ -3880,7 +3888,7 @@
 static
 void* Type_ViewingConditions_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
 {
-   return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsScreening));
+   return _cmsDupMem(self->ContextID, Ptr, sizeof(cmsICCViewingConditions));
 
    cmsUNUSED_PARAMETER(n);
 }
@@ -4337,13 +4345,13 @@
 static
 cmsBool  Type_MPEclut_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
 {
-    cmsUInt8Number Dimensions8[16];
+    cmsUInt8Number Dimensions8[16];  // 16 because the spec says 16 and not max number of channels
     cmsUInt32Number i;
     cmsStage* mpe = (cmsStage*) Ptr;
     _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe ->Data;
 
-    // Check for maximum number of channels
-    if (mpe -> InputChannels > 15) return FALSE;
+    // Check for maximum number of channels supported by lcms
+    if (mpe -> InputChannels > MAX_INPUT_DIMENSIONS) return FALSE;
 
     // Only floats are supported in MPE
     if (clut ->HasFloatValues == FALSE) return FALSE;
@@ -5488,8 +5496,9 @@
     { cmsSigScreeningTag,           { 1, 1, { cmsSigScreeningType},          NULL }, &SupportedTags[59]},
     { cmsSigVcgtTag,                { 1, 1, { cmsSigVcgtType},               NULL }, &SupportedTags[60]},
     { cmsSigMetaTag,                { 1, 1, { cmsSigDictType},               NULL }, &SupportedTags[61]},
-    { cmsSigProfileSequenceIdTag,   { 1, 1, { cmsSigProfileSequenceIdType},  NULL },  &SupportedTags[62]},
-    { cmsSigProfileDescriptionMLTag,{ 1, 1, { cmsSigMultiLocalizedUnicodeType}, NULL}, NULL}
+    { cmsSigProfileSequenceIdTag,   { 1, 1, { cmsSigProfileSequenceIdType},  NULL }, &SupportedTags[62]},
+    { cmsSigProfileDescriptionMLTag,{ 1, 1, { cmsSigMultiLocalizedUnicodeType}, NULL}, &SupportedTags[63]},
+    { cmsSigArgyllArtsTag,          { 9, 1, { cmsSigS15Fixed16ArrayType},    NULL}, NULL}
 
 
 };
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
index 6c84f13..8d353b3 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2014 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -1167,15 +1167,20 @@
     // If no way, then force CLUT that for sure can be written
     if (AllowedLUT == NULL) {
 
+        cmsStage* FirstStage;
+        cmsStage* LastStage;
+
         dwFlags |= cmsFLAGS_FORCE_CLUT;
         _cmsOptimizePipeline(ContextID, &LUT, xform ->RenderingIntent, &FrmIn, &FrmOut, &dwFlags);
 
         // Put identity curves if needed
-        if (cmsPipelineGetPtrToFirstStage(LUT) ->Type != cmsSigCurveSetElemType)
+        FirstStage = cmsPipelineGetPtrToFirstStage(LUT);
+        if (FirstStage != NULL && FirstStage ->Type != cmsSigCurveSetElemType)
              if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, ChansIn)))
                  goto Error;
 
-        if (cmsPipelineGetPtrToLastStage(LUT) ->Type != cmsSigCurveSetElemType)
+        LastStage = cmsPipelineGetPtrToLastStage(LUT);
+        if (LastStage != NULL && LastStage ->Type != cmsSigCurveSetElemType)
              if (!cmsPipelineInsertStage(LUT, cmsAT_END,   _cmsStageAllocIdentityCurves(ContextID, ChansOut)))
                  goto Error;
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
index 1eb9a87..d23b29f 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2014 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
index c0a0693..dfedd7f 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2014 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -208,12 +208,18 @@
 
 {
     _cmsTRANSFORM* p = (_cmsTRANSFORM*) Transform;
+    cmsStride stride;
 
-    p -> xform(p, InputBuffer, OutputBuffer, Size, Size);
+    stride.BytesPerLineIn = 0;  // Not used
+    stride.BytesPerLineOut = 0;
+    stride.BytesPerPlaneIn = Size;
+    stride.BytesPerPlaneOut = Size;
+
+    p -> xform(p, InputBuffer, OutputBuffer, Size, 1, &stride);
 }
 
 
-// Apply transform.
+// This is a legacy stride for planar
 void CMSEXPORT cmsDoTransformStride(cmsHTRANSFORM  Transform,
                               const void* InputBuffer,
                               void* OutputBuffer,
@@ -221,10 +227,40 @@
 
 {
     _cmsTRANSFORM* p = (_cmsTRANSFORM*) Transform;
+    cmsStride stride;
 
-    p -> xform(p, InputBuffer, OutputBuffer, Size, Stride);
+    stride.BytesPerLineIn = 0;
+    stride.BytesPerLineOut = 0;
+    stride.BytesPerPlaneIn = Stride;
+    stride.BytesPerPlaneOut = Stride;
+
+    p -> xform(p, InputBuffer, OutputBuffer, Size, 1, &stride);
 }
 
+// This is the "fast" function for plugins
+void CMSEXPORT cmsDoTransformLineStride(cmsHTRANSFORM  Transform,
+                              const void* InputBuffer,
+                              void* OutputBuffer,
+                              cmsUInt32Number PixelsPerLine,
+                              cmsUInt32Number LineCount,
+                              cmsUInt32Number BytesPerLineIn,
+                              cmsUInt32Number BytesPerLineOut,
+                              cmsUInt32Number BytesPerPlaneIn,
+                              cmsUInt32Number BytesPerPlaneOut)
+
+{
+    _cmsTRANSFORM* p = (_cmsTRANSFORM*) Transform;
+    cmsStride stride;
+
+    stride.BytesPerLineIn = BytesPerLineIn;
+    stride.BytesPerLineOut = BytesPerLineOut;
+    stride.BytesPerPlaneIn = BytesPerPlaneIn;
+    stride.BytesPerPlaneOut = BytesPerPlaneOut;
+
+    p->xform(p, InputBuffer, OutputBuffer, PixelsPerLine, LineCount, &stride);
+}
+
+
 
 // Transform routines ----------------------------------------------------------------------------------------------------------
 
@@ -233,49 +269,64 @@
 static
 void FloatXFORM(_cmsTRANSFORM* p,
                 const void* in,
-                void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
+                void* out,
+                cmsUInt32Number PixelsPerLine,
+                cmsUInt32Number LineCount,
+                const cmsStride* Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsFloat32Number fIn[cmsMAXCHANNELS], fOut[cmsMAXCHANNELS];
     cmsFloat32Number OutOfGamut;
-    cmsUInt32Number i, j;
+    cmsUInt32Number i, j, c, strideIn, strideOut;
 
-    accum  = (cmsUInt8Number*)  in;
-    output = (cmsUInt8Number*)  out;
+    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
 
-    for (i=0; i < Size; i++) {
+    strideIn = 0;
+    strideOut = 0;
 
-        accum = p -> FromInputFloat(p, fIn, accum, Stride);
+    for (i = 0; i < LineCount; i++) {
 
-        // Any gamut chack to do?
-        if (p ->GamutCheck != NULL) {
+        accum = (cmsUInt8Number*)in + strideIn;
+        output = (cmsUInt8Number*)out + strideOut;
 
-            // Evaluate gamut marker.
-            cmsPipelineEvalFloat( fIn, &OutOfGamut, p ->GamutCheck);
+        for (j = 0; j < PixelsPerLine; j++) {
 
-            // Is current color out of gamut?
-            if (OutOfGamut > 0.0) {
+            accum = p->FromInputFloat(p, fIn, accum, Stride->BytesPerPlaneIn);
 
-                // Certainly, out of gamut
-                for (j=0; j < cmsMAXCHANNELS; j++)
-                    fOut[j] = -1.0;
+            // Any gamut chack to do?
+            if (p->GamutCheck != NULL) {
 
+                // Evaluate gamut marker.
+                cmsPipelineEvalFloat(fIn, &OutOfGamut, p->GamutCheck);
+
+                // Is current color out of gamut?
+                if (OutOfGamut > 0.0) {
+
+                    // Certainly, out of gamut
+                    for (c = 0; c < cmsMAXCHANNELS; c++)
+                        fOut[c] = -1.0;
+
+                }
+                else {
+                    // No, proceed normally
+                    cmsPipelineEvalFloat(fIn, fOut, p->Lut);
+                }
             }
             else {
-                // No, proceed normally
-                cmsPipelineEvalFloat(fIn, fOut, p -> Lut);
+
+                // No gamut check at all
+                cmsPipelineEvalFloat(fIn, fOut, p->Lut);
             }
-        }
-        else {
 
-            // No gamut check at all
-            cmsPipelineEvalFloat(fIn, fOut, p -> Lut);
+
+            output = p->ToOutputFloat(p, fOut, output, Stride->BytesPerPlaneOut);
         }
 
-        // Back to asked representation
-        output = p -> ToOutputFloat(p, fOut, output, Stride);
+        strideIn += Stride->BytesPerLineIn;
+        strideOut += Stride->BytesPerLineOut;
     }
+
 }
 
 
@@ -283,22 +334,34 @@
 void NullFloatXFORM(_cmsTRANSFORM* p,
                     const void* in,
                     void* out,
-                    cmsUInt32Number Size,
-                    cmsUInt32Number Stride)
+                    cmsUInt32Number PixelsPerLine,
+                    cmsUInt32Number LineCount,
+                    const cmsStride* Stride)
+
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsFloat32Number fIn[cmsMAXCHANNELS];
-    cmsUInt32Number i, n;
+    cmsUInt32Number i, j, strideIn, strideOut;
 
-    accum  = (cmsUInt8Number*)  in;
-    output = (cmsUInt8Number*)  out;
-    n = Size;
+    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
 
-    for (i=0; i < n; i++) {
+    strideIn = 0;
+    strideOut = 0;
 
-        accum  = p -> FromInputFloat(p, fIn, accum, Stride);
-        output = p -> ToOutputFloat(p, fIn, output, Stride);
+    for (i = 0; i < LineCount; i++) {
+
+           accum = (cmsUInt8Number*) in + strideIn;
+           output = (cmsUInt8Number*) out + strideOut;
+
+           for (j = 0; j < PixelsPerLine; j++) {
+
+                  accum = p->FromInputFloat(p, fIn, accum, Stride ->BytesPerPlaneIn);
+                  output = p->ToOutputFloat(p, fIn, output, Stride->BytesPerPlaneOut);
+           }
+
+           strideIn += Stride->BytesPerLineIn;
+           strideOut += Stride->BytesPerLineOut;
     }
 }
 
@@ -308,23 +371,36 @@
 static
 void NullXFORM(_cmsTRANSFORM* p,
                const void* in,
-               void* out, cmsUInt32Number Size,
-               cmsUInt32Number Stride)
+               void* out,
+               cmsUInt32Number PixelsPerLine,
+               cmsUInt32Number LineCount,
+               const cmsStride* Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsUInt16Number wIn[cmsMAXCHANNELS];
-    cmsUInt32Number i, n;
+    cmsUInt32Number i, j, strideIn, strideOut;
 
-    accum  = (cmsUInt8Number*)  in;
-    output = (cmsUInt8Number*)  out;
-    n = Size;                    // Buffer len
+    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
 
-    for (i=0; i < n; i++) {
+    strideIn = 0;
+    strideOut = 0;
 
-        accum  = p -> FromInput(p, wIn, accum, Stride);
-        output = p -> ToOutput(p, wIn, output, Stride);
+    for (i = 0; i < LineCount; i++) {
+
+           accum = (cmsUInt8Number*)in + strideIn;
+           output = (cmsUInt8Number*)out + strideOut;
+
+           for (j = 0; j < PixelsPerLine; j++) {
+
+                  accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
+                  output = p->ToOutput(p, wIn, output, Stride->BytesPerPlaneOut);
     }
+
+           strideIn += Stride->BytesPerLineIn;
+           strideOut += Stride->BytesPerLineOut;
+    }
+
 }
 
 
@@ -332,27 +408,41 @@
 static
 void PrecalculatedXFORM(_cmsTRANSFORM* p,
                         const void* in,
-                        void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
+                        void* out,
+                        cmsUInt32Number PixelsPerLine,
+                        cmsUInt32Number LineCount,
+                        const cmsStride* Stride)
 {
     register cmsUInt8Number* accum;
     register cmsUInt8Number* output;
     cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
-    cmsUInt32Number i, n;
+    cmsUInt32Number i, j, strideIn, strideOut;
 
-    accum  = (cmsUInt8Number*)  in;
-    output = (cmsUInt8Number*)  out;
-    n = Size;
+    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
 
-    for (i=0; i < n; i++) {
+    strideIn = 0;
+    strideOut = 0;
 
-        accum = p -> FromInput(p, wIn, accum, Stride);
-        p ->Lut ->Eval16Fn(wIn, wOut, p -> Lut->Data);
-        output = p -> ToOutput(p, wOut, output, Stride);
+    for (i = 0; i < LineCount; i++) {
+
+        accum = (cmsUInt8Number*)in + strideIn;
+        output = (cmsUInt8Number*)out + strideOut;
+
+        for (j = 0; j < PixelsPerLine; j++) {
+
+            accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
+            p->Lut->Eval16Fn(wIn, wOut, p->Lut->Data);
+            output = p->ToOutput(p, wOut, output, Stride->BytesPerPlaneOut);
+        }
+
+        strideIn += Stride->BytesPerLineIn;
+        strideOut += Stride->BytesPerLineOut;
     }
+
 }
 
 
-// Auxiliar: Handle precalculated gamut check. The retrieval of context may be alittle bit slow, but this function is not critical.
+// Auxiliary: Handle precalculated gamut check. The retrieval of context may be alittle bit slow, but this function is not critical.
 static
 void TransformOnePixelWithGamutCheck(_cmsTRANSFORM* p,
                                      const cmsUInt16Number wIn[],
@@ -379,22 +469,35 @@
 static
 void PrecalculatedXFORMGamutCheck(_cmsTRANSFORM* p,
                                   const void* in,
-                                  void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
+                                  void* out,
+                                  cmsUInt32Number PixelsPerLine,
+                                  cmsUInt32Number LineCount,
+                                  const cmsStride* Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
-    cmsUInt32Number i, n;
+    cmsUInt32Number i, j, strideIn, strideOut;
 
-    accum  = (cmsUInt8Number*)  in;
-    output = (cmsUInt8Number*)  out;
-    n = Size;                    // Buffer len
+    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
 
-    for (i=0; i < n; i++) {
+    strideIn = 0;
+    strideOut = 0;
 
-        accum = p -> FromInput(p, wIn, accum, Stride);
-        TransformOnePixelWithGamutCheck(p, wIn, wOut);
-        output = p -> ToOutput(p, wOut, output, Stride);
+    for (i = 0; i < LineCount; i++) {
+
+           accum = (cmsUInt8Number*)in + strideIn;
+           output = (cmsUInt8Number*)out + strideOut;
+
+           for (j = 0; j < PixelsPerLine; j++) {
+
+                  accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
+                  TransformOnePixelWithGamutCheck(p, wIn, wOut);
+                  output = p->ToOutput(p, wOut, output, Stride->BytesPerPlaneOut);
+           }
+
+           strideIn += Stride->BytesPerLineIn;
+           strideOut += Stride->BytesPerLineOut;
     }
 }
 
@@ -403,94 +506,120 @@
 static
 void CachedXFORM(_cmsTRANSFORM* p,
                  const void* in,
-                 void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
+                 void* out,
+                 cmsUInt32Number PixelsPerLine,
+                 cmsUInt32Number LineCount,
+                 const cmsStride* Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
-    cmsUInt32Number i, n;
     _cmsCACHE Cache;
+    cmsUInt32Number i, j, strideIn, strideOut;
 
-    accum  = (cmsUInt8Number*)  in;
-    output = (cmsUInt8Number*)  out;
-    n = Size;                    // Buffer len
+    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
 
     // Empty buffers for quick memcmp
-    memset(wIn,  0, sizeof(wIn));
+    memset(wIn, 0, sizeof(wIn));
     memset(wOut, 0, sizeof(wOut));
 
     // Get copy of zero cache
-    memcpy(&Cache, &p ->Cache, sizeof(Cache));
+    memcpy(&Cache, &p->Cache, sizeof(Cache));
 
-    for (i=0; i < n; i++) {
+    strideIn = 0;
+    strideOut = 0;
 
-        accum = p -> FromInput(p, wIn, accum, Stride);
+    for (i = 0; i < LineCount; i++) {
 
-        if (memcmp(wIn, Cache.CacheIn, sizeof(Cache.CacheIn)) == 0) {
+        accum = (cmsUInt8Number*)in + strideIn;
+        output = (cmsUInt8Number*)out + strideOut;
 
-            memcpy(wOut, Cache.CacheOut, sizeof(Cache.CacheOut));
-        }
-        else {
+        for (j = 0; j < PixelsPerLine; j++) {
 
-            p ->Lut ->Eval16Fn(wIn, wOut, p -> Lut->Data);
+            accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
 
-            memcpy(Cache.CacheIn,  wIn,  sizeof(Cache.CacheIn));
-            memcpy(Cache.CacheOut, wOut, sizeof(Cache.CacheOut));
+            if (memcmp(wIn, Cache.CacheIn, sizeof(Cache.CacheIn)) == 0) {
+
+                memcpy(wOut, Cache.CacheOut, sizeof(Cache.CacheOut));
+            }
+            else {
+                p->Lut->Eval16Fn(wIn, wOut, p->Lut->Data);
+
+                memcpy(Cache.CacheIn, wIn, sizeof(Cache.CacheIn));
+                memcpy(Cache.CacheOut, wOut, sizeof(Cache.CacheOut));
+            }
+
+            output = p->ToOutput(p, wOut, output, Stride->BytesPerPlaneOut);
         }
 
-        output = p -> ToOutput(p, wOut, output, Stride);
+        strideIn += Stride->BytesPerLineIn;
+        strideOut += Stride->BytesPerLineOut;
     }
-
 }
 
-
 // All those nice features together
 static
 void CachedXFORMGamutCheck(_cmsTRANSFORM* p,
                            const void* in,
-                           void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
+                           void* out,
+                           cmsUInt32Number PixelsPerLine,
+                           cmsUInt32Number LineCount,
+                           const cmsStride* Stride)
 {
-       cmsUInt8Number* accum;
-       cmsUInt8Number* output;
-       cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
-       cmsUInt32Number i, n;
-       _cmsCACHE Cache;
+    cmsUInt8Number* accum;
+    cmsUInt8Number* output;
+    cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
+    _cmsCACHE Cache;
+    cmsUInt32Number i, j, strideIn, strideOut;
 
-       accum  = (cmsUInt8Number*)  in;
-       output = (cmsUInt8Number*)  out;
-       n = Size;                    // Buffer len
+    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
 
-       // Empty buffers for quick memcmp
-       memset(wIn,  0, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
-       memset(wOut, 0, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
+    // Empty buffers for quick memcmp
+    memset(wIn, 0, sizeof(wIn));
+    memset(wOut, 0, sizeof(wOut));
 
-       // Get copy of zero cache
-       memcpy(&Cache, &p ->Cache, sizeof(Cache));
+    // Get copy of zero cache
+    memcpy(&Cache, &p->Cache, sizeof(Cache));
 
-       for (i=0; i < n; i++) {
+    strideIn = 0;
+    strideOut = 0;
 
-            accum = p -> FromInput(p, wIn, accum, Stride);
+    for (i = 0; i < LineCount; i++) {
+
+        accum = (cmsUInt8Number*)in + strideIn;
+        output = (cmsUInt8Number*)out + strideOut;
+
+        for (j = 0; j < PixelsPerLine; j++) {
+
+            accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
 
             if (memcmp(wIn, Cache.CacheIn, sizeof(Cache.CacheIn)) == 0) {
-                    memcpy(wOut, Cache.CacheOut, sizeof(Cache.CacheOut));
+
+                memcpy(wOut, Cache.CacheOut, sizeof(Cache.CacheOut));
             }
             else {
-                    TransformOnePixelWithGamutCheck(p, wIn, wOut);
-                    memcpy(Cache.CacheIn, wIn, sizeof(Cache.CacheIn));
-                    memcpy(Cache.CacheOut, wOut, sizeof(Cache.CacheOut));
+                TransformOnePixelWithGamutCheck(p, wIn, wOut);
+
+                memcpy(Cache.CacheIn, wIn, sizeof(Cache.CacheIn));
+                memcpy(Cache.CacheOut, wOut, sizeof(Cache.CacheOut));
             }
 
-            output = p -> ToOutput(p, wOut, output, Stride);
-       }
+            output = p->ToOutput(p, wOut, output, Stride->BytesPerPlaneOut);
+        }
 
+        strideIn += Stride->BytesPerLineIn;
+        strideOut += Stride->BytesPerLineOut;
+    }
 }
 
-// -------------------------------------------------------------------------------------------------------------
+// Transform plug-ins ----------------------------------------------------------------------------------------------------
 
 // List of used-defined transform factories
 typedef struct _cmsTransformCollection_st {
 
-    _cmsTransformFactory  Factory;
+    _cmsTransform2Factory  Factory;
+    cmsBool                OldXform;   // Factory returns xform function in the old style
+
     struct _cmsTransformCollection_st *Next;
 
 } _cmsTransformCollection;
@@ -533,6 +662,7 @@
   ctx ->chunks[TransformPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTransformPluginChunkType));
 }
 
+// Allocates memory for transform plugin factory
 void _cmsAllocTransformPluginChunk(struct _cmsContext_struct* ctx,
                                         const struct _cmsContext_struct* src)
 {
@@ -547,6 +677,35 @@
     }
 }
 
+// Adaptor for old versions of plug-in
+static
+void _cmsTransform2toTransformAdaptor(struct _cmstransform_struct *CMMcargo,
+                                      const void* InputBuffer,
+                                      void* OutputBuffer,
+                                      cmsUInt32Number PixelsPerLine,
+                                      cmsUInt32Number LineCount,
+                                      const cmsStride* Stride)
+{
+
+       cmsUInt32Number i, strideIn, strideOut;
+
+       _cmsHandleExtraChannels(CMMcargo, InputBuffer, OutputBuffer, PixelsPerLine, LineCount, Stride);
+
+       strideIn = 0;
+       strideOut = 0;
+
+       for (i = 0; i < LineCount; i++) {
+
+              void *accum = (cmsUInt8Number*)InputBuffer + strideIn;
+              void *output = (cmsUInt8Number*)OutputBuffer + strideOut;
+
+              CMMcargo->OldXform(CMMcargo, accum, output, PixelsPerLine, Stride->BytesPerPlaneIn);
+
+              strideIn += Stride->BytesPerLineIn;
+              strideOut += Stride->BytesPerLineOut;
+       }
+}
+
 
 
 // Register new ways to transform
@@ -564,14 +723,22 @@
     }
 
     // Factory callback is required
-    if (Plugin ->Factory == NULL) return FALSE;
+    if (Plugin->factories.xform == NULL) return FALSE;
 
 
     fl = (_cmsTransformCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsTransformCollection));
     if (fl == NULL) return FALSE;
 
+    // Check for full xform plug-ins previous to 2.8, we would need an adapter in that case
+    if (Plugin->base.ExpectedVersion < 2080) {
+
+           fl->OldXform = TRUE;
+    }
+    else
+           fl->OldXform = FALSE;
+
     // Copy the parameters
-    fl ->Factory = Plugin ->Factory;
+    fl->Factory = Plugin->factories.xform;
 
     // Keep linked list
     fl ->Next = ctx->TransformCollection;
@@ -656,6 +823,12 @@
                             p->FromInputFloat = _cmsGetFormatter(ContextID, *InputFormat, cmsFormatterInput, CMS_PACK_FLAGS_FLOAT).FmtFloat;
                             p->ToOutputFloat = _cmsGetFormatter(ContextID, *OutputFormat, cmsFormatterOutput, CMS_PACK_FLAGS_FLOAT).FmtFloat;
 
+                            // Save the day?
+                            if (Plugin->OldXform) {
+                                   p->OldXform = (_cmsTransformFn) p->xform;
+                                   p->xform = _cmsTransform2toTransformAdaptor;
+                            }
+
                             return p;
                      }
               }
@@ -816,6 +989,22 @@
 
 // ----------------------------------------------------------------------------------------------------------------
 
+// Jun-21-2000: Some profiles (those that comes with W2K) comes
+// with the media white (media black?) x 100. Add a sanity check
+
+static
+void NormalizeXYZ(cmsCIEXYZ* Dest)
+{
+    while (Dest -> X > 2. &&
+           Dest -> Y > 2. &&
+           Dest -> Z > 2.) {
+
+               Dest -> X /= 10.;
+               Dest -> Y /= 10.;
+               Dest -> Z /= 10.;
+       }
+}
+
 static
 void SetWhitePoint(cmsCIEXYZ* wtPt, const cmsCIEXYZ* src)
 {
@@ -828,6 +1017,8 @@
         wtPt ->X = src->X;
         wtPt ->Y = src->Y;
         wtPt ->Z = src->Z;
+
+        NormalizeXYZ(wtPt);
     }
 
 }
@@ -1138,7 +1329,6 @@
                                          cmsUInt32Number InputFormat,
                                          cmsUInt32Number OutputFormat)
 {
-
     _cmsTRANSFORM* xform = (_cmsTRANSFORM*) hTransform;
     cmsFormatter16 FromInput, ToOutput;
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
index eb2236c..cbca894 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2014 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -52,7 +52,7 @@
 //
 //---------------------------------------------------------------------------------
 //
-// Version 2.7
+// Version 2.8
 //
 
 #ifndef _lcms2_H
@@ -104,7 +104,7 @@
 #endif
 
 // Version/release
-#define LCMS_VERSION        2070
+#define LCMS_VERSION        2080
 
 // I will give the chance of redefining basic types for compilers that are not fully C99 compliant
 #ifndef CMS_BASIC_TYPES_ALREADY_DEFINED
@@ -202,43 +202,44 @@
 #  define CMS_IS_WINDOWS_ 1
 #endif
 
-// Try to detect big endian platforms. This list can be endless, so only some checks are performed over here.
-// you can pass this toggle to the compiler by using -DCMS_USE_BIG_ENDIAN or something similar
+// Try to detect big endian platforms. This list can be endless, so primarily rely on the configure script
+// on Unix-like systems, and allow it to be set on the compiler command line using
+// -DCMS_USE_BIG_ENDIAN or something similar
+#ifdef CMS_USE_BIG_ENDIAN // set at compiler command line takes overall precedence
 
-#if defined(__sgi__) || defined(__sgi) || defined(sparc)
-#   define CMS_USE_BIG_ENDIAN      1
-#endif
+#  if CMS_USE_BIG_ENDIAN == 0
+#    undef CMS_USE_BIG_ENDIAN
+#  endif
 
-#if defined(__s390__) || defined(__s390x__)
-#   define CMS_USE_BIG_ENDIAN   1
-#endif
+#else // CMS_USE_BIG_ENDIAN
 
+#  ifdef WORDS_BIGENDIAN // set by configure (or explicitly on compiler command line)
+#    define CMS_USE_BIG_ENDIAN 1
+#  else // WORDS_BIGENDIAN
+// Fall back to platform/compiler specific tests
+#    if defined(__sgi__) || defined(__sgi) || defined(sparc)
+#      define CMS_USE_BIG_ENDIAN      1
+#    endif
 
-#if defined(__powerpc__) || defined(__ppc__) || defined(TARGET_CPU_PPC)
-#  if __powerpc__ || __ppc__ || TARGET_CPU_PPC
-#   define CMS_USE_BIG_ENDIAN   1
-#   if defined (__GNUC__) && defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
-#       if __BYTE_ORDER__  == __ORDER_LITTLE_ENDIAN__
-                // Don't use big endian for PowerPC little endian mode
-#                undef CMS_USE_BIG_ENDIAN
-#       endif
-#     endif
-#   endif
-#endif
+#    if defined(__s390__) || defined(__s390x__)
+#      define CMS_USE_BIG_ENDIAN   1
+#    endif
 
-#ifdef macintosh
-# ifdef __BIG_ENDIAN__
-#   define CMS_USE_BIG_ENDIAN      1
-# endif
-# ifdef __LITTLE_ENDIAN__
-#   undef CMS_USE_BIG_ENDIAN
-# endif
-#endif
+#    ifdef macintosh
+#      ifdef __BIG_ENDIAN__
+#        define CMS_USE_BIG_ENDIAN      1
+#      endif
+#      ifdef __LITTLE_ENDIAN__
+#        undef CMS_USE_BIG_ENDIAN
+#      endif
+#    endif
+#  endif  // WORDS_BIGENDIAN
 
-// WORDS_BIGENDIAN takes precedence
-#if defined(_HOST_BIG_ENDIAN) || defined(__BIG_ENDIAN__) || defined(WORDS_BIGENDIAN)
-#   define CMS_USE_BIG_ENDIAN      1
-#endif
+#  if defined(_HOST_BIG_ENDIAN) || defined(__BIG_ENDIAN__)
+#    define CMS_USE_BIG_ENDIAN      1
+#  endif
+
+#endif  // CMS_USE_BIG_ENDIAN
 
 
 // Calling convention -- this is hardly platform and compiler dependent
@@ -248,7 +249,7 @@
 #        define CMSEXPORT       __stdcall _export
 #        define CMSAPI
 #     else
-#        define CMSEXPORT      _stdcall
+#        define CMSEXPORT      __stdcall
 #        ifdef CMS_DLL_BUILD
 #            define CMSAPI    __declspec(dllexport)
 #        else
@@ -410,7 +411,8 @@
     cmsSigViewingCondDescTag                = 0x76756564,  // 'vued'
     cmsSigViewingConditionsTag              = 0x76696577,  // 'view'
     cmsSigVcgtTag                           = 0x76636774,  // 'vcgt'
-    cmsSigMetaTag                           = 0x6D657461   // 'meta'
+    cmsSigMetaTag                           = 0x6D657461,  // 'meta'
+    cmsSigArgyllArtsTag                     = 0x61727473   // 'arts'
 
 } cmsTagSignature;
 
@@ -683,7 +685,7 @@
 //            T: Pixeltype
 //            F: Flavor  0=MinIsBlack(Chocolate) 1=MinIsWhite(Vanilla)
 //            P: Planar? 0=Chunky, 1=Planar
-//            X: swap 16 bps endianess?
+//            X: swap 16 bps endianness?
 //            S: Do swap? ie, BGR, KYMC
 //            E: Extra samples
 //            C: Channels (Samples per pixel)
@@ -926,7 +928,7 @@
 #define TYPE_ARGB_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(4)|SWAPFIRST_SH(1))
 #define TYPE_BGR_FLT          (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(4)|DOSWAP_SH(1))
 #define TYPE_BGRA_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(4)|DOSWAP_SH(1)|SWAPFIRST_SH(1))
-#define TYPE_ABGR_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(4)|DOSWAP_SH(1))
+#define TYPE_ABGR_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(4)|DOSWAP_SH(1))
 
 #define TYPE_CMYK_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(4))
 
@@ -1043,7 +1045,7 @@
 // Context handling --------------------------------------------------------------------------------------------------------
 
 // Each context holds its owns globals and its own plug-ins. There is a global context with the id = 0 for lecacy compatibility
-// though using the global context is not recomended. Proper context handling makes lcms more thread-safe.
+// though using the global context is not recommended. Proper context handling makes lcms more thread-safe.
 
 typedef struct _cmsContext_struct* cmsContext;
 
@@ -1412,7 +1414,7 @@
 typedef struct {
 
     cmsUInt32Number n;
-    cmsContext     ContextID;
+    cmsContext      ContextID;
     cmsPSEQDESC*    seq;
 
 } cmsSEQ;
@@ -1679,6 +1681,8 @@
 // Specific to unbounded mode
 #define cmsFLAGS_NONEGATIVES              0x8000    // Prevent negative numbers in floating point transforms
 
+// Copy alpha channels when transforming
+#define cmsFLAGS_COPY_ALPHA               0x04000000 // Alpha channels are copied on cmsDoTransform()
 
 // Fine-tune control over number of gridpoints
 #define cmsFLAGS_GRIDPOINTS(n)           (((n) & 0xFF) << 16)
@@ -1757,12 +1761,22 @@
                                                  void * OutputBuffer,
                                                  cmsUInt32Number Size);
 
-CMSAPI void             CMSEXPORT cmsDoTransformStride(cmsHTRANSFORM Transform,
+CMSAPI void             CMSEXPORT cmsDoTransformStride(cmsHTRANSFORM Transform,   // Deprecated
                                                  const void * InputBuffer,
                                                  void * OutputBuffer,
                                                  cmsUInt32Number Size,
                                                  cmsUInt32Number Stride);
 
+CMSAPI void             CMSEXPORT cmsDoTransformLineStride(cmsHTRANSFORM  Transform,
+                                                 const void* InputBuffer,
+                                                 void* OutputBuffer,
+                                                 cmsUInt32Number PixelsPerLine,
+                                                 cmsUInt32Number LineCount,
+                                                 cmsUInt32Number BytesPerLineIn,
+                                                 cmsUInt32Number BytesPerLineOut,
+                                                 cmsUInt32Number BytesPerPlaneIn,
+                                                 cmsUInt32Number BytesPerPlaneOut);
+
 
 CMSAPI void             CMSEXPORT cmsSetAlarmCodes(const cmsUInt16Number NewAlarm[cmsMAXCHANNELS]);
 CMSAPI void             CMSEXPORT cmsGetAlarmCodes(cmsUInt16Number NewAlarm[cmsMAXCHANNELS]);
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
index c6cfbd6..9009472 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
@@ -30,7 +30,7 @@
 
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2014 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -86,7 +86,15 @@
 #define _cmsALIGNLONG(x) (((x)+(sizeof(cmsUInt32Number)-1)) & ~(sizeof(cmsUInt32Number)-1))
 
 // Alignment to memory pointer
-#define _cmsALIGNMEM(x)  (((x)+(sizeof(void *) - 1)) & ~(sizeof(void *) - 1))
+
+// (Ultra)SPARC with gcc requires ptr alignment of 8 bytes
+// even though sizeof(void *) is only four: for greatest flexibility
+// allow the build to specify ptr alignment.
+#ifndef CMS_PTR_ALIGNMENT
+# define CMS_PTR_ALIGNMENT sizeof(void *)
+#endif
+
+#define _cmsALIGNMEM(x)  (((x)+(CMS_PTR_ALIGNMENT - 1)) & ~(CMS_PTR_ALIGNMENT - 1))
 
 // Maximum encodeable values in floating point
 #define MAX_ENCODEABLE_XYZ  (1.0 + 32767.0/32768.0)
@@ -122,7 +130,7 @@
 
 // A fast way to convert from/to 16 <-> 8 bits
 #define FROM_8_TO_16(rgb) (cmsUInt16Number) ((((cmsUInt16Number) (rgb)) << 8)|(rgb))
-#define FROM_16_TO_8(rgb) (cmsUInt8Number) ((((rgb) * 65281 + 8388608) >> 24) & 0xFF)
+#define FROM_16_TO_8(rgb) (cmsUInt8Number) ((((cmsUInt32Number)(rgb) * 65281U + 8388608U) >> 24) & 0xFFU)
 
 // Code analysis is broken on asserts
 #ifdef _MSC_VER
@@ -691,8 +699,8 @@
     cmsContext ContextID;
 
     // The directory
-    int AllocatedEntries;
-    int UsedEntries;
+    cmsUInt32Number  AllocatedEntries;
+    cmsUInt32Number  UsedEntries;
     _cmsMLUentry* Entries;     // Array of pointers to strings allocated in MemPool
 
     // The Pool
@@ -760,7 +768,7 @@
     // Dictionary
     cmsUInt32Number          TagCount;
     cmsTagSignature          TagNames[MAX_TABLE_TAG];
-    cmsTagSignature          TagLinked[MAX_TABLE_TAG];           // The tag to wich is linked (0=none)
+    cmsTagSignature          TagLinked[MAX_TABLE_TAG];           // The tag to which is linked (0=none)
     cmsUInt32Number          TagSizes[MAX_TABLE_TAG];            // Size on disk
     cmsUInt32Number          TagOffsets[MAX_TABLE_TAG];
     cmsBool                  TagSaveAsRaw[MAX_TABLE_TAG];        // True to write uncooked
@@ -988,7 +996,7 @@
     cmsUInt32Number InputFormat, OutputFormat; // Keep formats for further reference
 
     // Points to transform code
-    _cmsTransformFn xform;
+    _cmsTransform2Fn xform;
 
     // Formatters, cannot be embedded into LUT because cache
     cmsFormatter16 FromInput;
@@ -1034,9 +1042,20 @@
     void* UserData;
     _cmsFreeUserDataFn FreeUserData;
 
+    // A way to provide backwards compatibility with full xform plugins
+    _cmsTransformFn OldXform;
+
 } _cmsTRANSFORM;
 
-// --------------------------------------------------------------------------------------------------
+// Copies extra channels from input to output if the original flags in the transform structure
+// instructs to do so. This function is called on all standard transform functions.
+void _cmsHandleExtraChannels(_cmsTRANSFORM* p, const void* in,
+                             void* out,
+                             cmsUInt32Number PixelsPerLine,
+                             cmsUInt32Number LineCount,
+                             const cmsStride* Stride);
+
+// -----------------------------------------------------------------------------------------------------------------------
 
 cmsHTRANSFORM _cmsChain2Lab(cmsContext             ContextID,
                             cmsUInt32Number        nProfiles,
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h
index 77ff228..aff3b48 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2011 Marti Maria Saguer
+//  Copyright (c) 1998-2016 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -157,7 +157,7 @@
                                                                    const void* Buffer);
 };
 
-// Endianess adjust functions
+// Endianness adjust functions
 CMSAPI cmsUInt16Number   CMSEXPORT  _cmsAdjustEndianess16(cmsUInt16Number Word);
 CMSAPI cmsUInt32Number   CMSEXPORT  _cmsAdjustEndianess32(cmsUInt32Number Value);
 CMSAPI void              CMSEXPORT  _cmsAdjustEndianess64(cmsUInt64Number* Result, cmsUInt64Number* QWord);
@@ -371,8 +371,8 @@
 
 typedef cmsUInt8Number* (* cmsFormatter16)(register struct _cmstransform_struct* CMMcargo,
                                            register cmsUInt16Number Values[],
-                                           register cmsUInt8Number*  Buffer,
-                                           register cmsUInt32Number  Stride);
+                                           register cmsUInt8Number* Buffer,
+                                           register cmsUInt32Number Stride);
 
 typedef cmsUInt8Number* (* cmsFormatterFloat)(struct _cmstransform_struct* CMMcargo,
                                               cmsFloat32Number Values[],
@@ -600,11 +600,28 @@
 
 //----------------------------------------------------------------------------------------------------------
 // Full xform
-typedef void     (* _cmsTransformFn)(struct _cmstransform_struct *CMMcargo,
+
+typedef struct {
+       cmsUInt32Number BytesPerLineIn;
+       cmsUInt32Number BytesPerLineOut;
+       cmsUInt32Number BytesPerPlaneIn;
+       cmsUInt32Number BytesPerPlaneOut;
+
+} cmsStride;
+
+typedef void     (* _cmsTransformFn)(struct _cmstransform_struct *CMMcargo,   // Legacy function, handles just ONE scanline.
                                      const void* InputBuffer,
                                      void* OutputBuffer,
                                      cmsUInt32Number Size,
-                                     cmsUInt32Number Stride);
+                                     cmsUInt32Number Stride);                 // Stride in bytes to the next plana in planar formats
+
+
+typedef void     (*_cmsTransform2Fn)(struct _cmstransform_struct *CMMcargo,
+                                     const void* InputBuffer,
+                                     void* OutputBuffer,
+                                     cmsUInt32Number PixelsPerLine,
+                                     cmsUInt32Number LineCount,
+                                     const cmsStride* Stride);
 
 typedef cmsBool  (* _cmsTransformFactory)(_cmsTransformFn* xform,
                                          void** UserData,
@@ -614,6 +631,14 @@
                                          cmsUInt32Number* OutputFormat,
                                          cmsUInt32Number* dwFlags);
 
+typedef cmsBool  (* _cmsTransform2Factory)(_cmsTransform2Fn* xform,
+                                         void** UserData,
+                                         _cmsFreeUserDataFn* FreePrivateDataFn,
+                                         cmsPipeline** Lut,
+                                         cmsUInt32Number* InputFormat,
+                                         cmsUInt32Number* OutputFormat,
+                                         cmsUInt32Number* dwFlags);
+
 
 // Retrieve user data as specified by the factory
 CMSAPI void   CMSEXPORT _cmsSetTransformUserData(struct _cmstransform_struct *CMMcargo, void* ptr, _cmsFreeUserDataFn FreePrivateDataFn);
@@ -628,7 +653,10 @@
       cmsPluginBase     base;
 
       // Transform entry point
-      _cmsTransformFactory  Factory;
+      union {
+             _cmsTransformFactory        legacy_xform;
+             _cmsTransform2Factory       xform;
+      } factories;
 
 }  cmsPluginTransform;
 
diff --git a/jdk/src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.c b/jdk/src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.c
index 742dfeb..6a70d40 100644
--- a/jdk/src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.c
+++ b/jdk/src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.c
@@ -104,40 +104,47 @@
     {
         return;
     }
-    RegisterID = (*env)->GetStaticMethodID(env, GPMgr,
-                                           RegisterName, RegisterSig);
-    pNativePrimID = (*env)->GetFieldID(env, GP, "pNativePrim", "J");
-    pixelID = (*env)->GetFieldID(env, SG2D, "pixel", "I");
-    eargbID = (*env)->GetFieldID(env, SG2D, "eargb", "I");
-    clipRegionID = (*env)->GetFieldID(env, SG2D, "clipRegion",
-                                      "Lsun/java2d/pipe/Region;");
-    compositeID = (*env)->GetFieldID(env, SG2D, "composite",
-                                     "Ljava/awt/Composite;");
-    lcdTextContrastID =
-        (*env)->GetFieldID(env, SG2D, "lcdTextContrast", "I");
-    getRgbID = (*env)->GetMethodID(env, Color, "getRGB", "()I");
-    xorPixelID = (*env)->GetFieldID(env, XORComp, "xorPixel", "I");
-    xorColorID = (*env)->GetFieldID(env, XORComp, "xorColor",
-                                    "Ljava/awt/Color;");
-    alphaMaskID = (*env)->GetFieldID(env, XORComp, "alphaMask", "I");
-    ruleID = (*env)->GetFieldID(env, AlphaComp, "rule", "I");
-    extraAlphaID = (*env)->GetFieldID(env, AlphaComp, "extraAlpha", "F");
+    CHECK_NULL(RegisterID =
+        (*env)->GetStaticMethodID(env, GPMgr, RegisterName, RegisterSig));
+    CHECK_NULL(pNativePrimID = (*env)->GetFieldID(env, GP, "pNativePrim", "J"));
+    CHECK_NULL(pixelID = (*env)->GetFieldID(env, SG2D, "pixel", "I"));
+    CHECK_NULL(eargbID = (*env)->GetFieldID(env, SG2D, "eargb", "I"));
+    CHECK_NULL(clipRegionID =
+        (*env)->GetFieldID(env, SG2D, "clipRegion", "Lsun/java2d/pipe/Region;"));
+    CHECK_NULL(compositeID =
+        (*env)->GetFieldID(env, SG2D, "composite", "Ljava/awt/Composite;"));
+    CHECK_NULL(lcdTextContrastID =
+        (*env)->GetFieldID(env, SG2D, "lcdTextContrast", "I"));
+    CHECK_NULL(getRgbID = (*env)->GetMethodID(env, Color, "getRGB", "()I"));
+    CHECK_NULL(xorPixelID = (*env)->GetFieldID(env, XORComp, "xorPixel", "I"));
+    CHECK_NULL(xorColorID =
+        (*env)->GetFieldID(env, XORComp, "xorColor", "Ljava/awt/Color;"));
+    CHECK_NULL(alphaMaskID =
+        (*env)->GetFieldID(env, XORComp, "alphaMask", "I"));
+    CHECK_NULL(ruleID = (*env)->GetFieldID(env, AlphaComp, "rule", "I"));
+    CHECK_NULL(extraAlphaID =
+        (*env)->GetFieldID(env, AlphaComp, "extraAlpha", "F"));
 
 
-    m00ID = (*env)->GetFieldID(env, AT, "m00", "D");
-    m01ID = (*env)->GetFieldID(env, AT, "m01", "D");
-    m02ID = (*env)->GetFieldID(env, AT, "m02", "D");
-    m10ID = (*env)->GetFieldID(env, AT, "m10", "D");
-    m11ID = (*env)->GetFieldID(env, AT, "m11", "D");
-    m12ID = (*env)->GetFieldID(env, AT, "m12", "D");
+    CHECK_NULL(m00ID = (*env)->GetFieldID(env, AT, "m00", "D"));
+    CHECK_NULL(m01ID = (*env)->GetFieldID(env, AT, "m01", "D"));
+    CHECK_NULL(m02ID = (*env)->GetFieldID(env, AT, "m02", "D"));
+    CHECK_NULL(m10ID = (*env)->GetFieldID(env, AT, "m10", "D"));
+    CHECK_NULL(m11ID = (*env)->GetFieldID(env, AT, "m11", "D"));
+    CHECK_NULL(m12ID = (*env)->GetFieldID(env, AT, "m12", "D"));
 
-    path2DTypesID = (*env)->GetFieldID(env, Path2D, "pointTypes", "[B");
-    path2DNumTypesID = (*env)->GetFieldID(env, Path2D, "numTypes", "I");
-    path2DWindingRuleID = (*env)->GetFieldID(env, Path2D, "windingRule", "I");
-    path2DFloatCoordsID = (*env)->GetFieldID(env, Path2DFloat,
-                                             "floatCoords", "[F");
-    sg2dStrokeHintID = (*env)->GetFieldID(env, SG2D, "strokeHint", "I");
-    fid = (*env)->GetStaticFieldID(env, SHints, "INTVAL_STROKE_PURE", "I");
+    CHECK_NULL(path2DTypesID =
+        (*env)->GetFieldID(env, Path2D, "pointTypes", "[B"));
+    CHECK_NULL(path2DNumTypesID =
+        (*env)->GetFieldID(env, Path2D, "numTypes", "I"));
+    CHECK_NULL(path2DWindingRuleID =
+        (*env)->GetFieldID(env, Path2D, "windingRule", "I"));
+    CHECK_NULL(path2DFloatCoordsID =
+        (*env)->GetFieldID(env, Path2DFloat, "floatCoords", "[F"));
+    CHECK_NULL(sg2dStrokeHintID =
+        (*env)->GetFieldID(env, SG2D, "strokeHint", "I"));
+    CHECK_NULL(fid =
+        (*env)->GetStaticFieldID(env, SHints, "INTVAL_STROKE_PURE", "I"));
     sunHints_INTVAL_STROKE_PURE = (*env)->GetStaticIntField(env, SHints, fid);
 }
 
diff --git a/jdk/src/share/native/sun/misc/VMSupport.c b/jdk/src/share/native/sun/misc/VMSupport.c
index 35c9933..eb4ab4b 100644
--- a/jdk/src/share/native/sun/misc/VMSupport.c
+++ b/jdk/src/share/native/sun/misc/VMSupport.c
@@ -42,6 +42,7 @@
         if (!JDK_InitJvmHandle()) {
             JNU_ThrowInternalError(env,
                  "Handle for JVM not found for symbol lookup");
+            return NULL;
         }
         InitAgentProperties_fp = (INIT_AGENT_PROPERTIES_FN)
             JDK_FindJvmEntry("JVM_InitAgentProperties");
diff --git a/jdk/src/solaris/classes/sun/nio/fs/LinuxWatchService.java b/jdk/src/solaris/classes/sun/nio/fs/LinuxWatchService.java
index 123fab5..b40ee9c 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/LinuxWatchService.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/LinuxWatchService.java
@@ -322,19 +322,6 @@
                         bytesRead = 0;
                     }
 
-                    // process any pending requests
-                    if ((nReady > 1) || (nReady == 1 && bytesRead == 0)) {
-                        try {
-                            read(socketpair[0], address, BUFFER_SIZE);
-                            boolean shutdown = processRequests();
-                            if (shutdown)
-                                break;
-                        } catch (UnixException x) {
-                            if (x.errno() != UnixConstants.EAGAIN)
-                                throw x;
-                        }
-                    }
-
                     // iterate over buffer to decode events
                     int offset = 0;
                     while (offset < bytesRead) {
@@ -369,6 +356,19 @@
 
                         offset += (SIZEOF_INOTIFY_EVENT + len);
                     }
+
+                    // process any pending requests
+                    if ((nReady > 1) || (nReady == 1 && bytesRead == 0)) {
+                        try {
+                            read(socketpair[0], address, BUFFER_SIZE);
+                            boolean shutdown = processRequests();
+                            if (shutdown)
+                                break;
+                        } catch (UnixException x) {
+                            if (x.errno() != UnixConstants.EAGAIN)
+                                throw x;
+                        }
+                    }
                 }
             } catch (UnixException x) {
                 x.printStackTrace();
diff --git a/jdk/src/solaris/classes/sun/print/CUPSPrinter.java b/jdk/src/solaris/classes/sun/print/CUPSPrinter.java
index 1a941d0..ef33dde 100644
--- a/jdk/src/solaris/classes/sun/print/CUPSPrinter.java
+++ b/jdk/src/solaris/classes/sun/print/CUPSPrinter.java
@@ -51,6 +51,7 @@
     private boolean initialized;
     private static native String getCupsServer();
     private static native int getCupsPort();
+    private static native String getCupsDefaultPrinter();
     private static native boolean canConnect(String server, int port);
     private static native boolean initIDs();
     // These functions need to be synchronized as
@@ -250,6 +251,15 @@
      * Returns 2 values - index 0 is printer name, index 1 is the uri.
      */
     static String[] getDefaultPrinter() {
+        // Try to get user/lpoptions-defined printer name from CUPS
+        // if not user-set, then go for server default destination
+        String printerInfo[] = new String[2];
+        printerInfo[0] = getCupsDefaultPrinter();
+
+        if (printerInfo[0] != null) {
+            printerInfo[1] = null;
+            return printerInfo.clone();
+        }
         try {
             URL url = new URL("http", getServer(), getPort(), "");
             final HttpURLConnection urlConnection =
@@ -285,7 +295,7 @@
                                         attCl)) {
 
                     HashMap defaultMap = null;
-                    String[] printerInfo = new String[2];
+
                     InputStream is = urlConnection.getInputStream();
                     HashMap[] responseMap = IPPPrintService.readIPPResponse(
                                          is);
diff --git a/jdk/src/solaris/classes/sun/print/IPPPrintService.java b/jdk/src/solaris/classes/sun/print/IPPPrintService.java
index a355b17..ee8cf62 100644
--- a/jdk/src/solaris/classes/sun/print/IPPPrintService.java
+++ b/jdk/src/solaris/classes/sun/print/IPPPrintService.java
@@ -59,7 +59,8 @@
 
 import java.util.Iterator;
 import java.util.HashSet;
-
+import java.util.Map;
+import java.util.Set;
 
 public class IPPPrintService implements PrintService, SunPrinterJobService {
 
@@ -1698,6 +1699,20 @@
 
                     if (responseMap != null && responseMap.length > 0) {
                         getAttMap = responseMap[0];
+                        // If there is extra hashmap created due to duplicate
+                        // key/attribute present in IPPresponse, then use that
+                        // map too by appending to getAttMap after removing the
+                        // duplicate key/value
+                        if (responseMap.length > 1) {
+                            for (int i = 1; i < responseMap.length; i++) {
+                                Set<Map.Entry<String, AttributeClass>> entries = responseMap[i].entrySet();
+                                for (Map.Entry<String, AttributeClass> entry : entries) {
+                                    if (!getAttMap.containsKey(entry.getValue())) {
+                                        getAttMap.put(entry.getKey(), entry.getValue());
+                                    }
+                                }
+                            }
+                        }
                     }
                 } else {
                     debug_println(debugPrefix+"opGetAttributes - null input stream");
diff --git a/jdk/src/solaris/native/com/sun/security/auth/module/Solaris.c b/jdk/src/solaris/native/com/sun/security/auth/module/Solaris.c
index 12a7074..d94edc6 100644
--- a/jdk/src/solaris/native/com/sun/security/auth/module/Solaris.c
+++ b/jdk/src/solaris/native/com/sun/security/auth/module/Solaris.c
@@ -32,6 +32,12 @@
 #include <string.h>
 #include <pwd.h>
 
+static void throwIllegalArgumentException(JNIEnv *env, const char *msg) {
+    jclass clazz = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+    if (clazz != NULL)
+        (*env)->ThrowNew(env, clazz, msg);
+}
+
 JNIEXPORT void JNICALL
 Java_com_sun_security_auth_module_SolarisSystem_getSolarisInfo
                                                 (JNIEnv *env, jobject obj) {
@@ -51,7 +57,7 @@
 
     if (groups == NULL) {
         jclass cls = (*env)->FindClass(env,"java/lang/OutOfMemoryError");
-        if(cls != 0)
+        if (cls != NULL)
             (*env)->ThrowNew(env, cls, NULL);
         return;
     }
@@ -67,15 +73,13 @@
          */
         fid = (*env)->GetFieldID(env, cls, "username", "Ljava/lang/String;");
         if (fid == 0) {
-            jclass newExcCls =
-                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-            if (newExcCls == 0) {
-                /* Unable to find the new exception class, give up. */
-                return;
-            }
-            (*env)->ThrowNew(env, newExcCls, "invalid field: username");
+            (*env)->ExceptionClear(env);
+            throwIllegalArgumentException(env, "invalid field: username");
+            return;
         }
         jstr = (*env)->NewStringUTF(env, pwd.pw_name);
+        if (jstr == NULL)
+            return;
         (*env)->SetObjectField(env, obj, fid, jstr);
 
         /*
@@ -83,13 +87,9 @@
          */
         fid = (*env)->GetFieldID(env, cls, "uid", "J");
         if (fid == 0) {
-            jclass newExcCls =
-                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-            if (newExcCls == 0) {
-                /* Unable to find the new exception class, give up. */
-                return;
-            }
-            (*env)->ThrowNew(env, newExcCls, "invalid field: username");
+            (*env)->ExceptionClear(env);
+            throwIllegalArgumentException(env, "invalid field: uid");
+            return;
         }
         (*env)->SetLongField(env, obj, fid, pwd.pw_uid);
 
@@ -98,13 +98,9 @@
          */
         fid = (*env)->GetFieldID(env, cls, "gid", "J");
         if (fid == 0) {
-            jclass newExcCls =
-                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-            if (newExcCls == 0) {
-                /* Unable to find the new exception class, give up. */
-                return;
-            }
-            (*env)->ThrowNew(env, newExcCls, "invalid field: username");
+            (*env)->ExceptionClear(env);
+            throwIllegalArgumentException(env, "invalid field: gid");
+            return;
         }
         (*env)->SetLongField(env, obj, fid, pwd.pw_gid);
 
@@ -113,17 +109,17 @@
          */
         fid = (*env)->GetFieldID(env, cls, "groups", "[J");
         if (fid == 0) {
-            jclass newExcCls =
-                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-            if (newExcCls == 0) {
-                /* Unable to find the new exception class, give up. */
-                return;
-            }
-            (*env)->ThrowNew(env, newExcCls, "invalid field: username");
+            (*env)->ExceptionClear(env);
+            throwIllegalArgumentException(env, "invalid field: groups");
+            return;
         }
 
         jgroups = (*env)->NewLongArray(env, numSuppGroups);
+        if (jgroups == NULL)
+            return;
         jgroupsAsArray = (*env)->GetLongArrayElements(env, jgroups, 0);
+        if (jgroupsAsArray == NULL)
+            return;
         for (i = 0; i < numSuppGroups; i++)
             jgroupsAsArray[i] = groups[i];
         (*env)->ReleaseLongArrayElements(env, jgroups, jgroupsAsArray, 0);
diff --git a/jdk/src/solaris/native/com/sun/security/auth/module/Unix.c b/jdk/src/solaris/native/com/sun/security/auth/module/Unix.c
index 394ef7c..e4db557 100644
--- a/jdk/src/solaris/native/com/sun/security/auth/module/Unix.c
+++ b/jdk/src/solaris/native/com/sun/security/auth/module/Unix.c
@@ -60,7 +60,7 @@
     groups = (gid_t *)calloc(numSuppGroups, sizeof(gid_t));
     if (groups == NULL) {
         jclass cls = (*env)->FindClass(env,"java/lang/OutOfMemoryError");
-        if(cls != 0)
+        if (cls != NULL)
             (*env)->ThrowNew(env, cls, NULL);
         return;
     }
@@ -90,6 +90,8 @@
             goto cleanUpAndReturn;
 
         jstr = (*env)->NewStringUTF(env, pwd->pw_name);
+        if (jstr == NULL)
+            goto cleanUpAndReturn;
         (*env)->SetObjectField(env, obj, userNameID, jstr);
 
         (*env)->SetLongField(env, obj, userID, pwd->pw_uid);
@@ -97,7 +99,11 @@
         (*env)->SetLongField(env, obj, groupID, pwd->pw_gid);
 
         jgroups = (*env)->NewLongArray(env, numSuppGroups);
+        if (jgroups == NULL)
+            goto cleanUpAndReturn;
         jgroupsAsArray = (*env)->GetLongArrayElements(env, jgroups, 0);
+        if (jgroupsAsArray == NULL)
+            goto cleanUpAndReturn;
         for (i = 0; i < numSuppGroups; i++)
             jgroupsAsArray[i] = groups[i];
         (*env)->ReleaseLongArrayElements(env, jgroups, jgroupsAsArray, 0);
diff --git a/jdk/src/solaris/native/java/io/FileDescriptor_md.c b/jdk/src/solaris/native/java/io/FileDescriptor_md.c
index 7147a14..ba353cb 100644
--- a/jdk/src/solaris/native/java/io/FileDescriptor_md.c
+++ b/jdk/src/solaris/native/java/io/FileDescriptor_md.c
@@ -23,9 +23,11 @@
  * questions.
  */
 
+#include "jni.h"
+#include "jni_util.h"
 #include "jvm.h"
-#include "io_util_md.h"
 
+#include "io_util_md.h"
 #include "java_io_FileDescriptor.h"
 
 /*******************************************************************/
@@ -41,7 +43,7 @@
 
 JNIEXPORT void JNICALL
 Java_java_io_FileDescriptor_initIDs(JNIEnv *env, jclass fdClass) {
-    IO_fd_fdID = (*env)->GetFieldID(env, fdClass, "fd", "I");
+    CHECK_NULL(IO_fd_fdID = (*env)->GetFieldID(env, fdClass, "fd", "I"));
 }
 
 /**************************************************************
diff --git a/jdk/src/solaris/native/java/lang/ProcessEnvironment_md.c b/jdk/src/solaris/native/java/lang/ProcessEnvironment_md.c
index d692d38..46ccc5d 100644
--- a/jdk/src/solaris/native/java/lang/ProcessEnvironment_md.c
+++ b/jdk/src/solaris/native/java/lang/ProcessEnvironment_md.c
@@ -53,6 +53,7 @@
     jsize i, j;
     jobjectArray result;
     jclass byteArrCls = (*env)->FindClass(env, "[B");
+    CHECK_NULL_RETURN(byteArrCls, NULL);
 
     for (i = 0; environ[i]; i++) {
         /* Ignore corrupted environment variables */
@@ -61,7 +62,7 @@
     }
 
     result = (*env)->NewObjectArray(env, 2*count, byteArrCls, 0);
-    if (result == NULL) return NULL;
+    CHECK_NULL_RETURN(result, NULL);
 
     for (i = 0, j = 0; environ[i]; i++) {
         const char * varEnd = strchr(environ[i], '=');
@@ -72,9 +73,9 @@
             jsize varLength = varEnd - environ[i];
             jsize valLength = strlen(valBeg);
             var = (*env)->NewByteArray(env, varLength);
-            if (var == NULL) return NULL;
+            CHECK_NULL_RETURN(var, NULL);
             val = (*env)->NewByteArray(env, valLength);
-            if (val == NULL) return NULL;
+            CHECK_NULL_RETURN(val, NULL);
             (*env)->SetByteArrayRegion(env, var, 0, varLength,
                                        (jbyte*) environ[i]);
             (*env)->SetByteArrayRegion(env, val, 0, valLength,
diff --git a/jdk/src/solaris/native/java/lang/UNIXProcess_md.c b/jdk/src/solaris/native/java/lang/UNIXProcess_md.c
index 7df5d59..9b510ad 100644
--- a/jdk/src/solaris/native/java/lang/UNIXProcess_md.c
+++ b/jdk/src/solaris/native/java/lang/UNIXProcess_md.c
@@ -206,6 +206,7 @@
 Java_java_lang_UNIXProcess_init(JNIEnv *env, jclass clazz)
 {
     parentPathv = effectivePathv(env);
+    CHECK_NULL(parentPathv);
     setSIGCHLDHandler(env);
 }
 
diff --git a/jdk/src/solaris/native/java/lang/java_props_macosx.c b/jdk/src/solaris/native/java/lang/java_props_macosx.c
index 7482d6c..b11a4d0 100644
--- a/jdk/src/solaris/native/java/lang/java_props_macosx.c
+++ b/jdk/src/solaris/native/java/lang/java_props_macosx.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2017, 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,10 +23,10 @@
  * questions.
  */
 
-#include <dlfcn.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
+#include <objc/objc-runtime.h>
 
 #include <Security/AuthSession.h>
 #include <CoreFoundation/CoreFoundation.h>
@@ -35,16 +35,6 @@
 
 #include "java_props_macosx.h"
 
-
-// need dlopen/dlsym trick to avoid pulling in JavaRuntimeSupport before libjava.dylib is loaded
-static void *getJRSFramework() {
-    static void *jrsFwk = NULL;
-    if (jrsFwk == NULL) {
-       jrsFwk = dlopen("/System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/JavaRuntimeSupport", RTLD_LAZY | RTLD_LOCAL);
-    }
-    return jrsFwk;
-}
-
 char *getPosixLocale(int cat) {
     char *lc = setlocale(cat, NULL);
     if ((lc == NULL) || (strcmp(lc, "C") == 0)) {
@@ -56,48 +46,106 @@
 
 #define LOCALEIDLENGTH  128
 char *getMacOSXLocale(int cat) {
+    const char* retVal = NULL;
+
     switch (cat) {
     case LC_MESSAGES:
         {
-            void *jrsFwk = getJRSFramework();
-            if (jrsFwk == NULL) return NULL;
+            // get preferred language code
+            CFArrayRef languages = CFLocaleCopyPreferredLanguages();
+            if (languages == NULL) {
+                return NULL;
+            }
+            if (CFArrayGetCount(languages) <= 0) {
+                CFRelease(languages);
+                return NULL;
+            }
 
-            char *(*JRSCopyPrimaryLanguage)() = dlsym(jrsFwk, "JRSCopyPrimaryLanguage");
-            char *primaryLanguage = JRSCopyPrimaryLanguage ? JRSCopyPrimaryLanguage() : NULL;
-            if (primaryLanguage == NULL) return NULL;
+            CFStringRef primaryLanguage = (CFStringRef)CFArrayGetValueAtIndex(languages, 0);
+            if (primaryLanguage == NULL) {
+                CFRelease(languages);
+                return NULL;
+            }
+            char languageString[LOCALEIDLENGTH];
+            if (CFStringGetCString(primaryLanguage, languageString,
+                                   LOCALEIDLENGTH, CFStringGetSystemEncoding()) == false) {
+                CFRelease(languages);
+                return NULL;
+            }
+            CFRelease(languages);
 
-            char *(*JRSCopyCanonicalLanguageForPrimaryLanguage)(char *) = dlsym(jrsFwk, "JRSCopyCanonicalLanguageForPrimaryLanguage");
-            char *canonicalLanguage = JRSCopyCanonicalLanguageForPrimaryLanguage ?  JRSCopyCanonicalLanguageForPrimaryLanguage(primaryLanguage) : NULL;
-            free (primaryLanguage);
+            retVal = languageString;
 
-            return canonicalLanguage;
+            // Special case for Portuguese in Brazil:
+            // The language code needs the "_BR" region code (to distinguish it
+            // from Portuguese in Portugal), but this is missing when using the
+            // "Portuguese (Brazil)" language.
+            // If language is "pt" and the current locale is pt_BR, return pt_BR.
+            char localeString[LOCALEIDLENGTH];
+            if (strcmp(retVal, "pt") == 0 &&
+                    CFStringGetCString(CFLocaleGetIdentifier(CFLocaleCopyCurrent()),
+                                       localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding()) &&
+                    strcmp(localeString, "pt_BR") == 0) {
+                retVal = localeString;
+            }
         }
         break;
     default:
         {
             char localeString[LOCALEIDLENGTH];
-            if (CFStringGetCString(CFLocaleGetIdentifier(CFLocaleCopyCurrent()),
-                                   localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding())) {
-                return strdup(localeString);
+            if (!CFStringGetCString(CFLocaleGetIdentifier(CFLocaleCopyCurrent()),
+                                    localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding())) {
+                return NULL;
             }
+            retVal = localeString;
         }
         break;
     }
 
+    if (retVal != NULL) {
+        // Language IDs use the language designators and (optional) region
+        // and script designators of BCP 47.  So possible formats are:
+        //
+        // "en"         (language designator only)
+        // "haw"        (3-letter lanuage designator)
+        // "en-GB"      (language with alpha-2 region designator)
+        // "es-419"     (language with 3-digit UN M.49 area code)
+        // "zh-Hans"    (language with ISO 15924 script designator)
+        // "zh-Hans-US"  (language with ISO 15924 script designator and region)
+        // "zh-Hans-419" (language with ISO 15924 script designator and UN M.49)
+        //
+        // In the case of region designators (alpha-2 and/or UN M.49), we convert
+        // to our locale string format by changing '-' to '_'.  That is, if
+        // the '-' is followed by fewer than 4 chars.
+        char* scriptOrRegion = strchr(retVal, '-');
+        if (scriptOrRegion != NULL) {
+            int length = strlen(scriptOrRegion);
+            if (length > 5) {
+                // Region and script both exist. Honor the script for now
+                scriptOrRegion[5] = '\0';
+            } else if (length < 5) {
+                *scriptOrRegion = '_';
+
+                assert((length == 3 &&
+                    // '-' followed by a 2 character region designator
+                      isalpha(scriptOrRegion[1]) &&
+                      isalpha(scriptOrRegion[2])) ||
+                       (length == 4 &&
+                    // '-' followed by a 3-digit UN M.49 area code
+                      isdigit(scriptOrRegion[1]) &&
+                      isdigit(scriptOrRegion[2]) &&
+                      isdigit(scriptOrRegion[3])));
+            }
+        }
+
+        return strdup(retVal);
+    }
     return NULL;
 }
 
 char *setupMacOSXLocale(int cat) {
     char * ret = getMacOSXLocale(cat);
 
-    if (cat == LC_MESSAGES && ret != NULL) {
-        void *jrsFwk = getJRSFramework();
-        if (jrsFwk != NULL) {
-            void (*JRSSetDefaultLocalization)(char *) = dlsym(jrsFwk, "JRSSetDefaultLocalization");
-            if (JRSSetDefaultLocalization) JRSSetDefaultLocalization(ret);
-        }
-    }
-
     if (ret == NULL) {
         return getPosixLocale(cat);
     } else {
@@ -124,26 +172,57 @@
     return 0;
 }
 
+// 10.9 SDK does not include the NSOperatingSystemVersion struct.
+// For now, create our own
+typedef struct {
+        NSInteger majorVersion;
+        NSInteger minorVersion;
+        NSInteger patchVersion;
+} OSVerStruct;
+
 void setOSNameAndVersion(java_props_t *sprops) {
-    /* Don't rely on JRSCopyOSName because there's no guarantee the value will
-     * remain the same, or even if the JRS functions will continue to be part of
-     * Mac OS X.  So hardcode os_name, and fill in os_version if we can.
-     */
+    // Hardcode os_name, and fill in os_version
     sprops->os_name = strdup("Mac OS X");
 
-    void *jrsFwk = getJRSFramework();
-    if (jrsFwk != NULL) {
-        char *(*copyOSVersion)() = dlsym(jrsFwk, "JRSCopyOSVersion");
-        if (copyOSVersion != NULL) {
-            sprops->os_version = copyOSVersion();
-            return;
+    char* osVersionCStr = NULL;
+    // Mac OS 10.9 includes the [NSProcessInfo operatingSystemVersion] function,
+    // but it's not in the 10.9 SDK.  So, call it via objc_msgSend_stret.
+    if ([[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) {
+        OSVerStruct (*procInfoFn)(id rec, SEL sel) = (OSVerStruct(*)(id, SEL))objc_msgSend_stret;
+        OSVerStruct osVer = procInfoFn([NSProcessInfo processInfo],
+                                       @selector(operatingSystemVersion));
+        NSString *nsVerStr;
+        if (osVer.patchVersion == 0) { // Omit trailing ".0"
+            nsVerStr = [NSString stringWithFormat:@"%ld.%ld",
+                    (long)osVer.majorVersion, (long)osVer.minorVersion];
+        } else {
+            nsVerStr = [NSString stringWithFormat:@"%ld.%ld.%ld",
+                    (long)osVer.majorVersion, (long)osVer.minorVersion, (long)osVer.patchVersion];
+        }
+        // Copy out the char*
+        osVersionCStr = strdup([nsVerStr UTF8String]);
+    }
+    // Fallback if running on pre-10.9 Mac OS
+    if (osVersionCStr == NULL) {
+        NSDictionary *version = [NSDictionary dictionaryWithContentsOfFile :
+                                 @"/System/Library/CoreServices/SystemVersion.plist"];
+        if (version != NULL) {
+            NSString *nsVerStr = [version objectForKey : @"ProductVersion"];
+            if (nsVerStr != NULL) {
+                osVersionCStr = strdup([nsVerStr UTF8String]);
+            }
         }
     }
-    sprops->os_version = strdup("Unknown");
+    if (osVersionCStr == NULL) {
+        osVersionCStr = strdup("Unknown");
+    }
+    sprops->os_version = osVersionCStr;
 }
 
 
-static Boolean getProxyInfoForProtocol(CFDictionaryRef inDict, CFStringRef inEnabledKey, CFStringRef inHostKey, CFStringRef inPortKey, CFStringRef *outProxyHost, int *ioProxyPort) {
+static Boolean getProxyInfoForProtocol(CFDictionaryRef inDict, CFStringRef inEnabledKey,
+                                       CFStringRef inHostKey, CFStringRef inPortKey,
+                                       CFStringRef *outProxyHost, int *ioProxyPort) {
     /* See if the proxy is enabled. */
     CFNumberRef cf_enabled = CFDictionaryGetValue(inDict, inEnabledKey);
     if (cf_enabled == NULL) {
diff --git a/jdk/src/solaris/native/java/lang/java_props_md.c b/jdk/src/solaris/native/java/lang/java_props_md.c
index 1830b20..46f7642 100644
--- a/jdk/src/solaris/native/java/lang/java_props_md.c
+++ b/jdk/src/solaris/native/java/lang/java_props_md.c
@@ -91,46 +91,6 @@
     return 0;
 }
 
-/* This function sets an environment variable using envstring.
- * The format of envstring is "name=value".
- * If the name has already existed, it will append value to the name.
- */
-static void
-setPathEnvironment(char *envstring)
-{
-    char name[20], *value, *current;
-
-    value = strchr(envstring, '='); /* locate name and value separator */
-
-    if (! value)
-        return; /* not a valid environment setting */
-
-    /* copy first part as environment name */
-    strncpy(name, envstring, value - envstring);
-    name[value-envstring] = '\0';
-
-    value++; /* set value point to value of the envstring */
-
-    current = getenv(name);
-    if (current) {
-        if (! strstr(current, value)) {
-            /* value is not found in current environment, append it */
-            char *temp = malloc(strlen(envstring) + strlen(current) + 2);
-        strcpy(temp, name);
-        strcat(temp, "=");
-        strcat(temp, current);
-        strcat(temp, ":");
-        strcat(temp, value);
-        putenv(temp);
-        }
-        /* else the value has already been set, do nothing */
-    }
-    else {
-        /* environment variable is not found */
-        putenv(envstring);
-    }
-}
-
 #ifndef P_tmpdir
 #define P_tmpdir "/var/tmp"
 #endif
@@ -546,6 +506,9 @@
     sprops.display_country = sprops.country;
     sprops.display_variant = sprops.variant;
 
+    /* ParseLocale failed with OOME */
+    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+
 #ifdef MACOSX
     sprops.sun_jnu_encoding = "UTF-8";
 #else
@@ -612,16 +575,6 @@
     sprops.path_separator = ":";
     sprops.line_separator = "\n";
 
-#if !defined(_ALLBSD_SOURCE)
-    /* Append CDE message and resource search path to NLSPATH and
-     * XFILESEARCHPATH, in order to pick localized message for
-     * FileSelectionDialog window (Bug 4173641).
-     */
-    setPathEnvironment("NLSPATH=/usr/dt/lib/nls/msg/%L/%N.cat");
-    setPathEnvironment("XFILESEARCHPATH=/usr/dt/app-defaults/%L/Dt");
-#endif
-
-
 #ifdef MACOSX
     setProxyProperties(&sprops);
 #endif
diff --git a/jdk/src/solaris/native/java/lang/locale_str.h b/jdk/src/solaris/native/java/lang/locale_str.h
index 72a796c..684f796 100644
--- a/jdk/src/solaris/native/java/lang/locale_str.h
+++ b/jdk/src/solaris/native/java/lang/locale_str.h
@@ -135,6 +135,16 @@
     "sr_SP", "sr_YU",
     "tchinese", "zh_TW",
 #endif
+#ifdef MACOSX
+    "sr-Latn", "sr_CS",   // Mappings as done by old Apple JRS code
+    "tk", "tk-Cyrl",
+    "tt-Latn", "tt-Cyrl",
+    "uz", "uz_UZ",
+    "uz-Arab", "uz_UZ",
+    "uz-Latn", "uz_UZ",
+    "zh-Hans", "zh_CN",
+    "zh-Hant", "zh_TW",
+#endif
     "", "",
  };
 
diff --git a/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c b/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c
index 8b43e3d..0e0e3a0 100644
--- a/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c
+++ b/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c
@@ -88,6 +88,7 @@
     /* SocketFlow fields */
 
     c = (*env)->FindClass(env, "jdk/net/SocketFlow");
+    CHECK_NULL(c);
 
     /* status */
 
diff --git a/jdk/src/solaris/native/java/net/Inet4AddressImpl.c b/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
index c8fb987..ec4f97d 100644
--- a/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
+++ b/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
@@ -51,29 +51,6 @@
 #define HAS_GLIBC_GETHOSTBY_R   1
 #endif
 
-static jclass ni_iacls;
-static jclass ni_ia4cls;
-static jmethodID ni_ia4ctrID;
-
-static jboolean initializeInetClasses(JNIEnv *env)
-{
-    static int initialized = 0;
-    if (!initialized) {
-        ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
-        CHECK_NULL_RETURN(ni_iacls, JNI_FALSE);
-        ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
-        CHECK_NULL_RETURN(ni_iacls, JNI_FALSE);
-        ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
-        CHECK_NULL_RETURN(ni_ia4cls, JNI_FALSE);
-        ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
-        CHECK_NULL_RETURN(ni_ia4cls, JNI_FALSE);
-        ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
-        CHECK_NULL_RETURN(ni_ia4ctrID, JNI_FALSE);
-        initialized = 1;
-    }
-    return JNI_TRUE;
-}
-
 
 #if defined(_ALLBSD_SOURCE) && !defined(HAS_GLIBC_GETHOSTBY_R)
 extern jobjectArray lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6);
@@ -147,8 +124,8 @@
     int getaddrinfo_error=0;
     struct addrinfo hints, *res, *resNew = NULL;
 
-    if (!initializeInetClasses(env))
-        return NULL;
+    initInetAddressIDs(env);
+    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host is null");
@@ -242,7 +219,7 @@
           goto cleanupAndReturn;
         }
 
-        ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
+        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
             goto cleanupAndReturn;
@@ -252,7 +229,7 @@
             /* We need 4 bytes to store ipv4 address; */
             int len = 4;
 
-            jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+            jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (IS_NULL(iaObj)) {
                 /* we may have memory to free at the end of this */
                 ret = NULL;
@@ -408,8 +385,8 @@
     int error = 0;
     struct addrinfo hints, *res, *resNew = NULL;
 
-    if (!initializeInetClasses(env))
-        return NULL;
+    initInetAddressIDs(env);
+    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host is null");
@@ -487,7 +464,7 @@
         retLen = i;
         iterator = resNew;
 
-        ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
+        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
 
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
@@ -496,7 +473,7 @@
 
         i = 0;
         while (iterator != NULL) {
-            jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+            jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (IS_NULL(iaObj)) {
                 ret = NULL;
                 goto cleanupAndReturn;
diff --git a/jdk/src/solaris/native/java/net/Inet6AddressImpl.c b/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
index 9850bb3..e29a25d 100644
--- a/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
+++ b/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -75,18 +75,14 @@
     } else {
         // ensure null-terminated
         hostname[NI_MAXHOST] = '\0';
-#if defined(__linux__) || defined(_ALLBSD_SOURCE)
-        /* On Linux/FreeBSD gethostname() says "host.domain.sun.com".  On
-         * Solaris gethostname() says "host", so extra work is needed.
-         */
-#else
+
         /* Solaris doesn't want to give us a fully qualified domain name.
          * We do a reverse lookup to try and get one.  This works
          * if DNS occurs before NIS in /etc/resolv.conf, but fails
          * if NIS comes first (it still gets only a partial name).
          * We use thread-safe system calls.
          */
-#ifdef AF_INET6
+#if defined(__solaris__) && defined(AF_INET6)
         struct addrinfo  hints, *res;
         int error;
 
@@ -111,50 +107,11 @@
 
             freeaddrinfo(res);
         }
-#endif /* AF_INET6 */
-#endif /* __linux__ || _ALLBSD_SOURCE */
+#endif
     }
     return (*env)->NewStringUTF(env, hostname);
 }
 
-static jclass ni_iacls;
-static jclass ni_ia4cls;
-static jclass ni_ia6cls;
-static jmethodID ni_ia4ctrID;
-static jmethodID ni_ia6ctrID;
-static jboolean preferIPv6Address;
-
-static jboolean initializeInetClasses(JNIEnv *env)
-{
-    jfieldID ni_preferIPv6AddressID;
-    static int initialized = 0;
-    if (!initialized) {
-        ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
-        CHECK_NULL_RETURN(ni_iacls, JNI_FALSE);
-        ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
-        CHECK_NULL_RETURN(ni_iacls, JNI_FALSE);
-        ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
-        CHECK_NULL_RETURN(ni_ia4cls, JNI_FALSE);
-        ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
-        CHECK_NULL_RETURN(ni_ia4cls, JNI_FALSE);
-        ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
-        CHECK_NULL_RETURN(ni_ia6cls, JNI_FALSE);
-        ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
-        CHECK_NULL_RETURN(ni_ia6cls, JNI_FALSE);
-        ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
-        CHECK_NULL_RETURN(ni_ia4ctrID, JNI_FALSE);
-        ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
-        CHECK_NULL_RETURN(ni_ia6ctrID, JNI_FALSE);
-        ni_preferIPv6AddressID =
-            (*env)->GetStaticFieldID(env, ni_iacls, "preferIPv6Address", "Z");
-        CHECK_NULL_RETURN(ni_preferIPv6AddressID, JNI_FALSE);
-        preferIPv6Address =
-            (*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID);
-        initialized = 1;
-    }
-    return JNI_TRUE;
-}
-
 #ifdef MACOSX
 /* also called from Inet4AddressImpl.c */
 __private_extern__ jobjectArray
@@ -169,9 +126,8 @@
     jboolean includeLoopback = JNI_FALSE;
     jobject name;
 
-    // Make sure static variables we need are set.
-    if (!initializeInetClasses(env))
-        return NULL;
+    initInetAddressIDs(env);
+    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 
     /* If the requested name matches this host's hostname, return IP addresses
      * from all attached interfaces. (#2844683 et al) This prevents undesired
@@ -234,10 +190,10 @@
     /* Create and fill the Java array. */
     int arraySize = addrs4 + addrs6 -
         (includeLoopback ? 0 : (numV4Loopbacks + numV6Loopbacks));
-    result = (*env)->NewObjectArray(env, arraySize, ni_iacls, NULL);
+    result = (*env)->NewObjectArray(env, arraySize, ia_class, NULL);
     if (!result) goto done;
 
-    if (preferIPv6Address) {
+    if ((*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID)) {
         i = includeLoopback ? addrs6 : (addrs6 - numV6Loopbacks);
         j = 0;
     } else {
@@ -301,8 +257,8 @@
     struct addrinfo hints, *res, *resNew = NULL;
 #endif /* AF_INET6 */
 
-    if (!initializeInetClasses(env))
-        return NULL;
+    initInetAddressIDs(env);
+    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host is null");
@@ -429,14 +385,14 @@
         retLen = i;
         iterator = resNew;
 
-        ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
+        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
 
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
             goto cleanupAndReturn;
         }
 
-        if (preferIPv6Address) {
+        if ((*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID)) {
             /* AF_INET addresses will be offset by inet6Count */
             inetIndex = inet6Count;
             inet6Index = 0;
@@ -449,7 +405,7 @@
         while (iterator != NULL) {
             int ret1;
             if (iterator->ai_family == AF_INET) {
-                jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+                jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
                 if (IS_NULL(iaObj)) {
                     ret = NULL;
                     goto cleanupAndReturn;
@@ -461,7 +417,7 @@
             } else if (iterator->ai_family == AF_INET6) {
                 jint scope = 0;
 
-                jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
+                jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
                 if (IS_NULL(iaObj)) {
                     ret = NULL;
                     goto cleanupAndReturn;
@@ -555,6 +511,7 @@
 
     if (!error) {
         ret = (*env)->NewStringUTF(env, host);
+        CHECK_NULL_RETURN(ret, NULL);
     }
 #endif /* AF_INET6 */
 
diff --git a/jdk/src/solaris/native/java/net/NetworkInterface.c b/jdk/src/solaris/native/java/net/NetworkInterface.c
index cb00494..9db36ae 100644
--- a/jdk/src/solaris/native/java/net/NetworkInterface.c
+++ b/jdk/src/solaris/native/java/net/NetworkInterface.c
@@ -25,9 +25,6 @@
 
 #include <errno.h>
 #include <strings.h>
-#if defined(_ALLBSD_SOURCE) && defined(__OpenBSD__)
-#include <sys/types.h>
-#endif
 #include <netinet/in.h>
 #include <stdlib.h>
 #include <string.h>
@@ -46,7 +43,6 @@
 
 #if defined(__linux__)
 #include <sys/ioctl.h>
-#include <bits/ioctls.h>
 #include <sys/utsname.h>
 #include <stdio.h>
 #endif
@@ -76,9 +72,29 @@
 #include "net_util.h"
 
 #if defined(__linux__)
-#define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
+    #define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
+#elif defined(__solaris__)
+    #ifndef SIOCGLIFHWADDR
+        #define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
+    #endif
+    #define DEV_PREFIX "/dev/"
 #endif
 
+#ifdef LIFNAMSIZ
+    #define IFNAMESIZE LIFNAMSIZ
+#else
+    #define IFNAMESIZE IFNAMSIZ
+#endif
+
+#define CHECKED_MALLOC3(_pointer, _type, _size) \
+    do { \
+        _pointer = (_type)malloc(_size); \
+        if (_pointer == NULL) { \
+            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
+            return ifs; /* return untouched list */ \
+        } \
+    } while(0)
+
 typedef struct _netaddr  {
     struct sockaddr *addr;
     struct sockaddr *brdcast;
@@ -117,12 +133,7 @@
 jfieldID ni_defaultIndexID;
 jmethodID ni_ctrID;
 
-static jclass ni_iacls;
-static jclass ni_ia4cls;
-static jclass ni_ia6cls;
 static jclass ni_ibcls;
-static jmethodID ni_ia4ctrID;
-static jmethodID ni_ia6ctrID;
 static jmethodID ni_ibctrID;
 static jfieldID ni_ibaddressID;
 static jfieldID ni_ib4broadcastID;
@@ -135,38 +146,31 @@
 static netif  *enumInterfaces(JNIEnv *env);
 static netif  *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs);
 
-#ifdef AF_INET6
+#if defined(AF_INET6)
 static netif  *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs);
 #endif
 
 static netif  *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
-                     struct sockaddr *ifr_addrP, int family, short prefix);
+                     struct sockaddr *ifr_addrP,
+                     struct sockaddr *ifr_broadaddrP,
+                     int family, short prefix);
 static void    freeif(netif *ifs);
 
 static int     openSocket(JNIEnv *env, int proto);
 static int     openSocketWithFallback(JNIEnv *env, const char *ifname);
 
+static short   translateIPv4AddressToPrefix(struct sockaddr_in *addr);
+static short   translateIPv6AddressToPrefix(struct sockaddr_in6 *addr);
 
-static struct  sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name,
-                                      struct sockaddr *brdcast_store);
-static short   getSubnet(JNIEnv *env, int sock, const char *ifname);
 static int     getIndex(int sock, const char *ifname);
-
 static int     getFlags(int sock, const char *ifname, int *flags);
-static int     getMacAddress(JNIEnv *env, int sock,  const char *ifname,
+static int     getMacAddress(JNIEnv *env, const char *ifname,
                              const struct in_addr *addr, unsigned char *buf);
 static int     getMTU(JNIEnv *env, int sock, const char *ifname);
 
-
 #if defined(__solaris__)
-static netif  *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family);
 static int     getMacFromDevice(JNIEnv *env, const char *ifname,
                                 unsigned char *retbuf);
-
-#ifndef SIOCGLIFHWADDR
-#define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
-#endif
-
 #endif
 
 /******************* Java entry points *****************************/
@@ -206,26 +210,10 @@
     CHECK_NULL(ni_parentID);
     ni_ctrID = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
     CHECK_NULL(ni_ctrID);
-    ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
-    CHECK_NULL(ni_iacls);
-    ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
-    CHECK_NULL(ni_iacls);
-    ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
-    CHECK_NULL(ni_ia4cls);
-    ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
-    CHECK_NULL(ni_ia4cls);
-    ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
-    CHECK_NULL(ni_ia6cls);
-    ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
-    CHECK_NULL(ni_ia6cls);
     ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
     CHECK_NULL(ni_ibcls);
     ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
     CHECK_NULL(ni_ibcls);
-    ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
-    CHECK_NULL(ni_ia4ctrID);
-    ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
-    CHECK_NULL(ni_ia6ctrID);
     ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
     CHECK_NULL(ni_ibctrID);
     ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address",
@@ -238,6 +226,9 @@
     CHECK_NULL(ni_ib4maskID);
     ni_defaultIndexID = (*env)->GetStaticFieldID(env, ni_class, "defaultIndex",
                                                  "I");
+    CHECK_NULL(ni_defaultIndexID);
+
+    initInetAddressIDs(env);
 }
 
 /*
@@ -253,20 +244,25 @@
     const char* name_utf;
     jobject obj = NULL;
 
+    if (name != NULL) {
+        name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
+    } else {
+        JNU_ThrowNullPointerException(env, "network interface name is NULL");
+        return NULL;
+    }
+
+    if (name_utf == NULL) {
+        if (!(*env)->ExceptionCheck(env))
+            JNU_ThrowOutOfMemoryError(env, NULL);
+        return NULL;
+    }
+
     ifs = enumInterfaces(env);
     if (ifs == NULL) {
         return NULL;
     }
 
-    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
-    if (name_utf == NULL) {
-       if (!(*env)->ExceptionCheck(env))
-           JNU_ThrowOutOfMemoryError(env, NULL);
-       freeif(ifs);
-       return NULL;
-    }
-
-    // Search the list of interface based on name
+    // search the list of interfaces based on name
     curr = ifs;
     while (curr != NULL) {
         if (strcmp(name_utf, curr->name) == 0) {
@@ -276,7 +272,7 @@
     }
 
     // if found create a NetworkInterface
-    if (curr != NULL) {;
+    if (curr != NULL) {
         obj = createNetworkInterface(env, curr);
     }
 
@@ -307,7 +303,7 @@
         return NULL;
     }
 
-    // Search the list of interface based on index
+    // search the list of interfaces based on index
     curr = ifs;
     while (curr != NULL) {
         if (index == curr->index) {
@@ -317,11 +313,13 @@
     }
 
     // if found create a NetworkInterface
-    if (curr != NULL) {;
+    if (curr != NULL) {
         obj = createNetworkInterface(env, curr);
     }
 
+    // release the interface list
     freeif(ifs);
+
     return obj;
 }
 
@@ -334,13 +332,11 @@
   (JNIEnv *env, jclass cls, jobject iaObj)
 {
     netif *ifs, *curr;
-
-#ifdef AF_INET6
+#if defined(AF_INET6)
     int family = (getInetAddress_family(env, iaObj) == IPv4) ? AF_INET : AF_INET6;
 #else
     int family =  AF_INET;
 #endif
-
     jobject obj = NULL;
     jboolean match = JNI_FALSE;
 
@@ -353,13 +349,13 @@
     while (curr != NULL) {
         netaddr *addrP = curr->addr;
 
-        // Iterate through each address on the interface
+        // iterate through each address on the interface
         while (addrP != NULL) {
 
             if (family == addrP->family) {
                 if (family == AF_INET) {
                     int address1 = htonl(
-                        ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr);
+                        ((struct sockaddr_in *)addrP->addr)->sin_addr.s_addr);
                     int address2 = getInetAddress_addr(env, iaObj);
 
                     if (address1 == address2) {
@@ -367,8 +363,7 @@
                         break;
                     }
                 }
-
-#ifdef AF_INET6
+#if defined(AF_INET6)
                 if (family == AF_INET6) {
                     jbyte *bytes = (jbyte *)&(
                         ((struct sockaddr_in6*)addrP->addr)->sin6_addr);
@@ -403,11 +398,13 @@
     }
 
     // if found create a NetworkInterface
-    if (match) {;
+    if (match) {
         obj = createNetworkInterface(env, curr);
     }
 
+    // release the interface list
     freeif(ifs);
+
     return obj;
 }
 
@@ -428,7 +425,7 @@
         return NULL;
     }
 
-    // count the interface
+    // count the interfaces
     ifCount = 0;
     curr = ifs;
     while (curr != NULL) {
@@ -443,8 +440,8 @@
         return NULL;
     }
 
-    // Iterate through the interfaces, create a NetworkInterface instance
-    // for each array element and populate the object.
+    // iterate through the interfaces, create a NetworkInterface instance
+    // for each array element and populate the object
     curr = ifs;
     arr_index = 0;
     while (curr != NULL) {
@@ -462,7 +459,9 @@
         curr = curr->next;
     }
 
+    // release the interface list
     freeif(ifs);
+
     return netIFArr;
 }
 
@@ -528,46 +527,45 @@
     jbyteArray ret = NULL;
     unsigned char mac[16];
     int len;
-    int sock;
     jboolean isCopy;
-    const char* name_utf;
+    const char *name_utf;
 
-    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
-    if (name_utf == NULL) {
-       if (!(*env)->ExceptionCheck(env))
-           JNU_ThrowOutOfMemoryError(env, NULL);
-       return NULL;
+    if (name != NULL) {
+        name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
+    } else {
+        JNU_ThrowNullPointerException(env, "network interface name is NULL");
+        return NULL;
     }
-    if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
-       (*env)->ReleaseStringUTFChars(env, name, name_utf);
-       return NULL;
+
+    if (name_utf == NULL) {
+        if (!(*env)->ExceptionCheck(env))
+            JNU_ThrowOutOfMemoryError(env, NULL);
+        return NULL;
     }
 
     if (!IS_NULL(addrArray)) {
-       (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
-       addr = ((caddr[0]<<24) & 0xff000000);
-       addr |= ((caddr[1] <<16) & 0xff0000);
-       addr |= ((caddr[2] <<8) & 0xff00);
-       addr |= (caddr[3] & 0xff);
-       iaddr.s_addr = htonl(addr);
-       len = getMacAddress(env, sock, name_utf, &iaddr, mac);
+        (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
+        addr = ((caddr[0]<<24) & 0xff000000);
+        addr |= ((caddr[1] <<16) & 0xff0000);
+        addr |= ((caddr[2] <<8) & 0xff00);
+        addr |= (caddr[3] & 0xff);
+        iaddr.s_addr = htonl(addr);
+        len = getMacAddress(env, name_utf, &iaddr, mac);
     } else {
-       len = getMacAddress(env, sock, name_utf, NULL, mac);
+        len = getMacAddress(env, name_utf, NULL, mac);
     }
-    if (len > 0) {
-       ret = (*env)->NewByteArray(env, len);
-       if (IS_NULL(ret)) {
-          /* we may have memory to free at the end of this */
-          goto fexit;
-       }
-       (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *)(mac));
-    }
- fexit:
-   // release the UTF string and interface list
-   (*env)->ReleaseStringUTFChars(env, name, name_utf);
 
-   close(sock);
-   return ret;
+    if (len > 0) {
+        ret = (*env)->NewByteArray(env, len);
+        if (!IS_NULL(ret)) {
+            (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *)(mac));
+        }
+    }
+
+    // release the UTF string and interface list
+    (*env)->ReleaseStringUTFChars(env, name, name_utf);
+
+    return ret;
 }
 
 /*
@@ -579,8 +577,7 @@
   (JNIEnv *env, jclass cls, jstring name, jint index)
 {
     jboolean isCopy;
-    int ret = -1;
-    int sock;
+    int sock, ret = -1;
     const char* name_utf = NULL;
 
     if (name != NULL) {
@@ -589,15 +586,16 @@
         JNU_ThrowNullPointerException(env, "network interface name is NULL");
         return ret;
     }
+
     if (name_utf == NULL) {
-       if (!(*env)->ExceptionCheck(env))
-           JNU_ThrowOutOfMemoryError(env, NULL);
-       return ret;
+        if (!(*env)->ExceptionCheck(env))
+            JNU_ThrowOutOfMemoryError(env, NULL);
+        return ret;
     }
 
     if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
-       (*env)->ReleaseStringUTFChars(env, name, name_utf);
-       return JNI_FALSE;
+        (*env)->ReleaseStringUTFChars(env, name, name_utf);
+        return JNI_FALSE;
     }
 
     ret = getMTU(env, sock, name_utf);
@@ -612,9 +610,8 @@
 
 static int getFlags0(JNIEnv *env, jstring name) {
     jboolean isCopy;
-    int ret, sock;
-    const char* name_utf;
-    int flags = 0;
+    int ret, sock, flags = 0;
+    const char *name_utf;
 
     if (name != NULL) {
         name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
@@ -622,10 +619,11 @@
         JNU_ThrowNullPointerException(env, "network interface name is NULL");
         return -1;
     }
+
     if (name_utf == NULL) {
-       if (!(*env)->ExceptionCheck(env))
-           JNU_ThrowOutOfMemoryError(env, NULL);
-       return -1;
+        if (!(*env)->ExceptionCheck(env))
+            JNU_ThrowOutOfMemoryError(env, NULL);
+        return -1;
     }
     if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
         (*env)->ReleaseStringUTFChars(env, name, name_utf);
@@ -638,8 +636,8 @@
     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 
     if (ret < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGLIFFLAGS failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "getFlags() failed");
         return -1;
     }
 
@@ -651,7 +649,7 @@
  * populates the InetAddress array based on the IP addresses for this
  * interface.
  */
-jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
+static jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
     jobject netifObj;
     jobject name;
     jobjectArray addrArr;
@@ -664,7 +662,7 @@
     netif *childP;
     jobject tmp;
 
-    // Create a NetworkInterface object and populate it
+    // create a NetworkInterface object and populate it
     netifObj = (*env)->NewObject(env, ni_class, ni_ctrID);
     CHECK_NULL_RETURN(netifObj, NULL);
     name = (*env)->NewStringUTF(env, ifs->name);
@@ -675,7 +673,7 @@
     (*env)->SetBooleanField(env, netifObj, ni_virutalID,
                             ifs->virtual ? JNI_TRUE : JNI_FALSE);
 
-    //Count the number of address on this interface
+    // count the number of addresses on this interface
     addr_count = 0;
     addrP = ifs->addr;
     while (addrP != NULL) {
@@ -683,8 +681,8 @@
         addrP = addrP->next;
     }
 
-    // Create the array of InetAddresses
-    addrArr = (*env)->NewObjectArray(env, addr_count, ni_iacls, NULL);
+    // create the array of InetAddresses
+    addrArr = (*env)->NewObjectArray(env, addr_count,  ia_class, NULL);
     if (addrArr == NULL) {
         return NULL;
     }
@@ -701,38 +699,37 @@
         jobject ibObj = NULL;
 
         if (addrP->family == AF_INET) {
-            iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (iaObj) {
-                 setInetAddress_addr(env, iaObj, htonl(
-                     ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
+                setInetAddress_addr(env, iaObj, htonl(
+                    ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
             } else {
                 return NULL;
             }
             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
             if (ibObj) {
-                 (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
-                 if (addrP->brdcast) {
+                (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
+                if (addrP->brdcast) {
                     jobject ia2Obj = NULL;
-                    ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+                    ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
                     if (ia2Obj) {
-                       setInetAddress_addr(env, ia2Obj, htonl(
-                           ((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
-                       (*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
+                        setInetAddress_addr(env, ia2Obj, htonl(
+                            ((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
+                        (*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
                     } else {
                         return NULL;
                     }
-                 }
-                 (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
-                 (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
+                }
+                (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
+                (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
             } else {
                 return NULL;
             }
         }
-
-#ifdef AF_INET6
+#if defined(AF_INET6)
         if (addrP->family == AF_INET6) {
             int scope=0;
-            iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
+            iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
             if (iaObj) {
                 jboolean ret = setInet6Address_ipaddress(env, iaObj,
                     (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
@@ -764,7 +761,7 @@
         addrP = addrP->next;
     }
 
-    // See if there is any virtual interface attached to this one.
+    // see if there is any virtual interface attached to this one.
     child_count = 0;
     childP = ifs->childs;
     while (childP) {
@@ -777,17 +774,17 @@
         return NULL;
     }
 
-    // Create the NetworkInterface instances for the sub-interfaces as well.
+    // create the NetworkInterface instances for the sub-interfaces as well
     child_index = 0;
     childP = ifs->childs;
     while(childP) {
-      tmp = createNetworkInterface(env, childP);
-      if (tmp == NULL) {
-         return NULL;
-      }
-      (*env)->SetObjectField(env, tmp, ni_parentID, netifObj);
-      (*env)->SetObjectArrayElement(env, childArr, child_index++, tmp);
-      childP = childP->next;
+        tmp = createNetworkInterface(env, childP);
+        if (tmp == NULL) {
+            return NULL;
+        }
+        (*env)->SetObjectField(env, tmp, ni_parentID, netifObj);
+        (*env)->SetObjectArrayElement(env, childArr, child_index++, tmp);
+        childP = childP->next;
     }
     (*env)->SetObjectField(env, netifObj, ni_addrsID, addrArr);
     (*env)->SetObjectField(env, netifObj, ni_bindsID, bindArr);
@@ -801,65 +798,51 @@
  * Enumerates all interfaces
  */
 static netif *enumInterfaces(JNIEnv *env) {
-    netif *ifs;
+    netif *ifs = NULL;
     int sock;
 
-    // Enumerate IPv4 addresses
     sock = openSocket(env, AF_INET);
     if (sock < 0 && (*env)->ExceptionOccurred(env)) {
         return NULL;
     }
 
+    // enumerate IPv4 addresses
     ifs = enumIPv4Interfaces(env, sock, NULL);
     close(sock);
 
+    // return partial list if an exception occurs in the middle of process ???
     if (ifs == NULL && (*env)->ExceptionOccurred(env)) {
         return NULL;
     }
 
-    // return partial list if an exception occurs in the middle of process ???
-
     // If IPv6 is available then enumerate IPv6 addresses.
-#ifdef AF_INET6
-
+#if defined(AF_INET6)
         // User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
         // so we have to call ipv6_available()
         if (ipv6_available()) {
+            sock = openSocket(env, AF_INET6);
+            if (sock < 0 && (*env)->ExceptionOccurred(env)) {
+                freeif(ifs);
+                return NULL;
+            }
 
-           sock = openSocket(env, AF_INET6);
-           if (sock < 0 && (*env)->ExceptionOccurred(env)) {
-               freeif(ifs);
-               return NULL;
-           }
+            ifs = enumIPv6Interfaces(env, sock, ifs);
+            close(sock);
 
-           ifs = enumIPv6Interfaces(env, sock, ifs);
-           close(sock);
-
-           if ((*env)->ExceptionOccurred(env)) {
-              freeif(ifs);
-              return NULL;
-           }
-
-       }
+            if ((*env)->ExceptionOccurred(env)) {
+                freeif(ifs);
+                return NULL;
+            }
+        }
 #endif
 
     return ifs;
 }
 
-#define CHECKED_MALLOC3(_pointer, _type, _size) \
-    do { \
-        _pointer = (_type)malloc(_size); \
-        if (_pointer == NULL) { \
-            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
-            return ifs; /* return untouched list */ \
-        } \
-    } while(0)
-
-
 /*
- * Frees an interface list (including any attached addresses)
+ * Frees an interface list (including any attached addresses).
  */
-void freeif(netif *ifs) {
+static void freeif(netif *ifs) {
     netif *currif = ifs;
     netif *child = NULL;
 
@@ -871,7 +854,7 @@
             addrP = next;
         }
 
-        // Don't forget to free the sub-interfaces.
+        // don't forget to free the sub-interfaces
         if (currif->childs != NULL) {
             freeif(currif->childs);
         }
@@ -882,40 +865,32 @@
     }
 }
 
-netif *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
-             struct sockaddr *ifr_addrP, int family, short prefix)
+static netif *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
+                    struct sockaddr *ifr_addrP,
+                    struct sockaddr *ifr_broadaddrP,
+                    int family, short prefix)
 {
     netif *currif = ifs, *parent;
     netaddr *addrP;
-
-#ifdef LIFNAMSIZ
-    int ifnam_size = LIFNAMSIZ;
-    char name[LIFNAMSIZ], vname[LIFNAMSIZ];
-#else
-    int ifnam_size = IFNAMSIZ;
-    char name[IFNAMSIZ], vname[IFNAMSIZ];
-#endif
-
+    char name[IFNAMESIZE], vname[IFNAMESIZE];
     char *name_colonP;
-    int mask;
     int isVirtual = 0;
     int addr_size;
-    int flags = 0;
 
     // If the interface name is a logical interface then we remove the unit
     // number so that we have the physical interface (eg: hme0:1 -> hme0).
     // NetworkInterface currently doesn't have any concept of physical vs.
     // logical interfaces.
-    strncpy(name, if_name, ifnam_size);
-    name[ifnam_size - 1] = '\0';
+    strncpy(name, if_name, IFNAMESIZE);
+    name[IFNAMESIZE - 1] = '\0';
     *vname = 0;
 
-     // Create and populate the netaddr node. If allocation fails
-     // return an un-updated list.
+    // Create and populate the netaddr node. If allocation fails
+    // return an un-updated list.
 
-     // Allocate for addr and brdcast at once
+    // Allocate for addr and brdcast at once
 
-#ifdef AF_INET6
+#if defined(AF_INET6)
     addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in)
                                     : sizeof(struct sockaddr_in6);
 #else
@@ -927,41 +902,36 @@
     memcpy(addrP->addr, ifr_addrP, addr_size);
 
     addrP->family = family;
-    addrP->brdcast = NULL;
     addrP->mask = prefix;
     addrP->next = 0;
-    if (family == AF_INET) {
-       // Deal with broadcast addr & subnet mask
-       struct sockaddr *brdcast_to =
-              (struct sockaddr *) ((char *)addrP + sizeof(netaddr) + addr_size);
-       addrP->brdcast = getBroadcast(env, sock, name, brdcast_to);
-       if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
-           return ifs;
-       }
-       if ((mask = getSubnet(env, sock, name)) != -1) {
-           addrP->mask = mask;
-       } else if((*env)->ExceptionCheck(env)) {
-           return ifs;
-       }
-     }
+
+    // for IPv4 add broadcast address
+    if (family == AF_INET && ifr_broadaddrP != NULL) {
+        addrP->brdcast = (struct sockaddr *)
+                             ((char *)addrP + sizeof(netaddr) + addr_size);
+        memcpy(addrP->brdcast, ifr_broadaddrP, addr_size);
+    } else {
+        addrP->brdcast = NULL;
+    }
 
     // Deal with virtual interface with colon notation e.g. eth0:1
     name_colonP = strchr(name, ':');
     if (name_colonP != NULL) {
+        int flags = 0;
         // This is a virtual interface. If we are able to access the parent
         // we need to create a new entry if it doesn't exist yet *and* update
         // the 'parent' interface with the new records.
         *name_colonP = 0;
         if (getFlags(sock, name, &flags) < 0 || flags < 0) {
-             // failed to access parent interface do not create parent.
-             // We are a virtual interface with no parent.
-             isVirtual = 1;
-             *name_colonP = ':';
+            // failed to access parent interface do not create parent.
+            // We are a virtual interface with no parent.
+            isVirtual = 1;
+            *name_colonP = ':';
         } else {
-             // Got access to parent, so create it if necessary.
-             // Save original name to vname and truncate name by ':'
-             memcpy(vname, name, sizeof(vname) );
-             vname[name_colonP - name] = ':';
+            // Got access to parent, so create it if necessary.
+            // Save original name to vname and truncate name by ':'
+            memcpy(vname, name, sizeof(vname));
+            vname[name_colonP - name] = ':';
         }
     }
 
@@ -974,12 +944,12 @@
         currif = currif->next;
     }
 
-    // If "new" then create an netif structure and insert it into the list.
+    // If "new" then create a netif structure and insert it into the list.
     if (currif == NULL) {
-         CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
+         CHECKED_MALLOC3(currif, netif *, sizeof(netif) + IFNAMESIZE);
          currif->name = (char *)currif + sizeof(netif);
-         strncpy(currif->name, name, ifnam_size);
-         currif->name[ifnam_size - 1] = '\0';
+         strncpy(currif->name, name, IFNAMESIZE);
+         currif->name[IFNAMESIZE - 1] = '\0';
          currif->index = getIndex(sock, name);
          currif->addr = NULL;
          currif->childs = NULL;
@@ -1008,13 +978,12 @@
         }
 
         if (currif == NULL) {
-            CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
+            CHECKED_MALLOC3(currif, netif *, sizeof(netif) + IFNAMESIZE);
             currif->name = (char *)currif + sizeof(netif);
-            strncpy(currif->name, vname, ifnam_size);
-            currif->name[ifnam_size - 1] = '\0';
+            strncpy(currif->name, vname, IFNAMESIZE);
+            currif->name[IFNAMESIZE - 1] = '\0';
             currif->index = getIndex(sock, vname);
-            currif->addr = NULL;
-            // Need to duplicate the addr entry?
+            currif->addr = NULL; // Need to duplicate the addr entry?
             currif->virtual = 1;
             currif->childs = NULL;
             currif->next = parent->childs;
@@ -1043,6 +1012,57 @@
 }
 
 /*
+ * Determines the prefix value for an AF_INET subnet address.
+ */
+static short translateIPv4AddressToPrefix(struct sockaddr_in *addr) {
+    short prefix = 0;
+    unsigned int mask = ntohl(addr->sin_addr.s_addr);
+    while (mask) {
+        mask <<= 1;
+        prefix++;
+    }
+    return prefix;
+}
+
+/*
+ * Determines the prefix value for an AF_INET6 subnet address.
+ */
+static short translateIPv6AddressToPrefix(struct sockaddr_in6 *addr) {
+    short prefix = 0;
+    u_char *addrBytes = (u_char *)&(addr->sin6_addr);
+    unsigned int byte, bit;
+
+    for (byte = 0; byte < sizeof(struct in6_addr); byte++, prefix += 8) {
+        if (addrBytes[byte] != 0xff) {
+            break;
+        }
+    }
+    if (byte != sizeof(struct in6_addr)) {
+        for (bit = 7; bit != 0; bit--, prefix++) {
+            if (!(addrBytes[byte] & (1 << bit))) {
+                break;
+            }
+        }
+        for (; bit != 0; bit--) {
+            if (addrBytes[byte] & (1 << bit)) {
+                prefix = 0;
+                break;
+            }
+        }
+        if (prefix > 0) {
+            byte++;
+            for (; byte < sizeof(struct in6_addr); byte++) {
+                if (addrBytes[byte]) {
+                    prefix = 0;
+                }
+            }
+        }
+    }
+
+    return prefix;
+}
+
+/*
  * Opens a socket for further ioct calls. proto is one of AF_INET or AF_INET6.
  */
 static int openSocket(JNIEnv *env, int proto) {
@@ -1052,8 +1072,8 @@
         // If EPROTONOSUPPORT is returned it means we don't have
         // support for this proto so don't throw an exception.
         if (errno != EPROTONOSUPPORT) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                         "Socket creation failed");
+            NET_ThrowByNameWithLastError
+                (env, JNU_JAVANETPKG "SocketException", "Socket creation failed");
         }
         return -1;
     }
@@ -1061,30 +1081,27 @@
     return sock;
 }
 
+/** Linux **/
+#if defined(__linux__)
 
-/** Linux, AIX **/
-#if defined(__linux__) || defined(_AIX)
-
-#ifdef AF_INET6
+#if defined(AF_INET6)
 /*
- * Opens a socket for further ioct calls. Tries AF_INET socket first and
- * if it falls return AF_INET6 socket.
+ * Opens a socket for further ioctl calls. Tries AF_INET socket first and
+ * if it fails return AF_INET6 socket.
  */
-// unused arg ifname and struct if2
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock;
-    struct ifreq if2;
 
     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
         if (errno == EPROTONOSUPPORT) {
             if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                             "IPV6 Socket creation failed");
+                NET_ThrowByNameWithLastError
+                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
                 return -1;
             }
         } else { // errno is not NOSUPPORT
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                         "IPV4 Socket creation failed");
+            NET_ThrowByNameWithLastError
+                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
             return -1;
         }
     }
@@ -1093,63 +1110,82 @@
     // IPv6 socket regardless of type of address of an interface.
     return sock;
 }
-
 #else
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env,AF_INET);
+    return openSocket(env, AF_INET);
 }
 #endif
 
+/*
+ * Enumerates and returns all IPv4 interfaces on Linux.
+ */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifconf ifc;
     struct ifreq *ifreqP;
     char *buf = NULL;
-    int numifs;
     unsigned i;
-    int siocgifconfRequest = SIOCGIFCONF;
 
-#if defined(__linux__)
-    // need to do a dummy SIOCGIFCONF to determine the buffer size.
+    // do a dummy SIOCGIFCONF to determine the buffer size
     // SIOCGIFCOUNT doesn't work
     ifc.ifc_buf = NULL;
     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGIFCONF failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
         return ifs;
     }
-#elif defined(_AIX)
-    ifc.ifc_buf = NULL;
-    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGSIZIFCONF failed");
-        return ifs;
-    }
-#endif /* __linux__ */
 
+    // call SIOCGIFCONF to enumerate the interfaces
     CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
-
     ifc.ifc_buf = buf;
-#if defined(_AIX)
-    siocgifconfRequest = CSIOCGIFCONF;
-#endif
-    if (ioctl(sock, siocgifconfRequest, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGIFCONF failed");
+    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
         free(buf);
         return ifs;
     }
 
-    // Iterate through each interface
+    // iterate through each interface
     ifreqP = ifc.ifc_req;
     for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
-#if defined(_AIX)
-        if (ifreqP->ifr_addr.sa_family != AF_INET) continue;
-#endif
-        // Add to the list
-        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
-                    (struct sockaddr *)&(ifreqP->ifr_addr), AF_INET, 0);
+        struct sockaddr addr, broadaddr, *broadaddrP = NULL;
+        short prefix = 0;
 
-        // If an exception occurred then free the list
+        // ignore non IPv4 addresses
+        if (ifreqP->ifr_addr.sa_family != AF_INET) {
+            continue;
+        }
+
+        // save socket address
+        memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
+
+        // determine broadcast address, if applicable
+        if ((ioctl(sock, SIOCGIFFLAGS, ifreqP) == 0) &&
+            ifreqP->ifr_flags & IFF_BROADCAST) {
+
+            // restore socket address to ifreqP
+            memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
+
+            if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
+                memcpy(&broadaddr, &(ifreqP->ifr_broadaddr),
+                       sizeof(struct sockaddr));
+                broadaddrP = &broadaddr;
+            }
+        }
+
+        // restore socket address to ifreqP
+        memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
+
+        // determine netmask
+        if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
+            prefix = translateIPv4AddressToPrefix(
+                         (struct sockaddr_in *)&(ifreqP->ifr_netmask));
+        }
+
+        // add interface to the list
+        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
+                    &addr, broadaddrP, AF_INET, prefix);
+
+        // in case of exception, free interface list and buffer and return NULL
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             freeif(ifs);
@@ -1157,23 +1193,20 @@
         }
     }
 
-    // Free socket and buffer
+    // free buffer
     free(buf);
     return ifs;
 }
 
-
-#if defined(AF_INET6) && defined(__linux__)
+#if defined(AF_INET6)
 
 /*
  * Enumerates and returns all IPv6 interfaces on Linux.
  */
 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
     FILE *f;
-    char addr6[40], devname[21];
-    char addr6p[8][5];
+    char devname[21], addr6p[8][5];
     int prefix, scope, dad_status, if_idx;
-    uint8_t ipv6addr[16];
 
     if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
         while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
@@ -1181,127 +1214,39 @@
                       addr6p[4], addr6p[5], addr6p[6], addr6p[7],
                       &if_idx, &prefix, &scope, &dad_status, devname) != EOF) {
 
-            struct netif *ifs_ptr = NULL;
-            struct netif *last_ptr = NULL;
+            char addr6[40];
             struct sockaddr_in6 addr;
 
             sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
                     addr6p[0], addr6p[1], addr6p[2], addr6p[3],
                     addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
-            inet_pton(AF_INET6, addr6, ipv6addr);
 
             memset(&addr, 0, sizeof(struct sockaddr_in6));
-            memcpy((void*)addr.sin6_addr.s6_addr, (const void*)ipv6addr, 16);
+            inet_pton(AF_INET6, addr6, (void*)addr.sin6_addr.s6_addr);
 
+            // set scope ID to interface index
             addr.sin6_scope_id = if_idx;
 
+            // add interface to the list
             ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr,
-                        AF_INET6, (short)prefix);
+                        NULL, AF_INET6, (short)prefix);
 
-            // If an exception occurred then return the list as is.
+            // if an exception occurred then return the list as is
             if ((*env)->ExceptionOccurred(env)) {
-                fclose(f);
-                return ifs;
+                break;
             }
        }
        fclose(f);
     }
     return ifs;
 }
-#endif
 
-
-#if defined(AF_INET6) && defined(_AIX)
+#endif /* AF_INET6 */
 
 /*
- * Enumerates and returns all IPv6 interfaces on AIX.
+ * Try to get the interface index.
  */
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    struct ifconf ifc;
-    struct ifreq *ifreqP;
-    char *buf;
-    int numifs;
-    unsigned i;
-    unsigned bufsize;
-    char *cp, *cplimit;
-
-    // use SIOCGSIZIFCONF to get size for  SIOCGIFCONF
-
-    ifc.ifc_buf = NULL;
-    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                    "ioctl SIOCGSIZIFCONF failed");
-        return ifs;
-    }
-    bufsize = ifc.ifc_len;
-
-    buf = (char *)malloc(bufsize);
-    if (!buf) {
-        JNU_ThrowOutOfMemoryError(env, "Network interface native buffer allocation failed");
-        return ifs;
-    }
-    ifc.ifc_len = bufsize;
-    ifc.ifc_buf = buf;
-    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl CSIOCGIFCONF failed");
-        free(buf);
-        return ifs;
-    }
-
-    // Iterate through each interface
-    ifreqP = ifc.ifc_req;
-    cp = (char *)ifc.ifc_req;
-    cplimit = cp + ifc.ifc_len;
-
-    for (; cp < cplimit;
-        cp += (sizeof(ifreqP->ifr_name) +
-               MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr))))
-    {
-        ifreqP = (struct ifreq *)cp;
-        struct ifreq if2;
-        memset((char *)&if2, 0, sizeof(if2));
-        strncpy(if2.ifr_name, ifreqP->ifr_name, sizeof(if2.ifr_name) - 1);
-
-        // Skip interface that aren't UP
-        if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) >= 0) {
-            if (!(if2.ifr_flags & IFF_UP)) {
-                continue;
-            }
-        }
-
-        if (ifreqP->ifr_addr.sa_family != AF_INET6)
-            continue;
-
-        if (ioctl(sock, SIOCGIFSITE6, (char *)&if2) >= 0) {
-            struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifreqP->ifr_addr);
-            s6->sin6_scope_id = if2.ifr_site6;
-        }
-
-        // Add to the list
-        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
-                    (struct sockaddr *)&(ifreqP->ifr_addr), AF_INET6, 0);
-
-        // If an exception occurred then free the list
-        if ((*env)->ExceptionOccurred(env)) {
-            free(buf);
-            freeif(ifs);
-            return NULL;
-        }
-    }
-
-    // Free socket and buffer
-    free(buf);
-    return ifs;
-}
-#endif
-
-
 static int getIndex(int sock, const char *name) {
-     // Try to get the interface index
-#if defined(_AIX)
-    return if_nametoindex(name);
-#else
     struct ifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
@@ -1311,68 +1256,6 @@
     }
 
     return if2.ifr_ifindex;
-#endif
-}
-
-/*
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast
-  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
-{
-    struct sockaddr *ret = NULL;
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    // Let's make sure the interface does have a broadcast address.
-    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2)  < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGIFFLAGS failed");
-        return ret;
-    }
-
-    if (if2.ifr_flags & IFF_BROADCAST) {
-        // It does, let's retrieve it
-        if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                         "ioctl SIOCGIFBRDADDR failed");
-            return ret;
-        }
-
-        ret = brdcast_store;
-        memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
-    }
-
-    return ret;
-}
-
-/*
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
-    unsigned int mask;
-    short ret;
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGIFNETMASK failed");
-        return -1;
-    }
-
-    mask = ntohl(((struct sockaddr_in*)&(if2.ifr_addr))->sin_addr.s_addr);
-    ret = 0;
-    while (mask) {
-       mask <<= 1;
-       ret++;
-    }
-
-    return ret;
 }
 
 /*
@@ -1381,10 +1264,280 @@
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
 static int getMacAddress
-  (JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr,
+  (JNIEnv *env, const char *ifname, const struct in_addr *addr,
    unsigned char *buf)
 {
-#if defined (_AIX)
+    struct ifreq ifr;
+    int i, sock;
+
+    if ((sock = openSocketWithFallback(env, ifname)) < 0) {
+        return -1;
+    }
+
+    memset((char *)&ifr, 0, sizeof(ifr));
+    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
+    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFHWADDR) failed");
+        close(sock);
+        return -1;
+    }
+
+    close(sock);
+    memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
+
+    // all bytes to 0 means no hardware address
+    for (i = 0; i < IFHWADDRLEN; i++) {
+        if (buf[i] != 0)
+            return IFHWADDRLEN;
+    }
+
+    return -1;
+}
+
+static int getMTU(JNIEnv *env, int sock, const char *ifname) {
+    struct ifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+
+    if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
+        return -1;
+    }
+
+    return if2.ifr_mtu;
+}
+
+static int getFlags(int sock, const char *ifname, int *flags) {
+    struct ifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+
+    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
+        return -1;
+    }
+
+    if (sizeof(if2.ifr_flags) == sizeof(short)) {
+        *flags = (if2.ifr_flags & 0xffff);
+    } else {
+        *flags = if2.ifr_flags;
+    }
+    return 0;
+}
+
+#endif /* __linux__ */
+
+/** AIX **/
+#if defined(_AIX)
+
+#if defined(AF_INET6)
+/*
+ * Opens a socket for further ioctl calls. Tries AF_INET socket first and
+ * if it fails return AF_INET6 socket.
+ */
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
+    int sock;
+
+    if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+        if (errno == EPROTONOSUPPORT) {
+            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
+                NET_ThrowByNameWithLastError
+                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+                return -1;
+            }
+        } else { // errno is not NOSUPPORT
+            NET_ThrowByNameWithLastError
+                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
+            return -1;
+        }
+    }
+
+    return sock;
+}
+#else
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
+    return openSocket(env, AF_INET);
+}
+#endif
+
+/*
+ * Enumerates and returns all IPv4 interfaces on AIX.
+ */
+static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    struct ifconf ifc;
+    struct ifreq *ifreqP;
+    char *buf = NULL;
+    unsigned i;
+
+    // call SIOCGSIZIFCONF to get the size of SIOCGIFCONF buffer
+    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
+        return ifs;
+    }
+
+    // call CSIOCGIFCONF instead of SIOCGIFCONF where interface
+    // records will always have sizeof(struct ifreq) length.
+    // Be aware that only IPv4 data is complete this way.
+    CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
+    ifc.ifc_buf = buf;
+    if (ioctl(sock, CSIOCGIFCONF, (char *)&ifc) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(CSIOCGIFCONF) failed");
+        free(buf);
+        return ifs;
+    }
+
+    // iterate through each interface
+    ifreqP = ifc.ifc_req;
+    for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
+        struct sockaddr addr, broadaddr, *broadaddrP = NULL;
+        short prefix = 0;
+
+        // ignore non IPv4 addresses
+        if (ifreqP->ifr_addr.sa_family != AF_INET) {
+            continue;
+        }
+
+        // save socket address
+        memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
+
+        // determine broadcast address, if applicable
+        if ((ioctl(sock, SIOCGIFFLAGS, ifreqP) == 0) &&
+            ifreqP->ifr_flags & IFF_BROADCAST) {
+
+            // restore socket address to ifreqP
+            memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
+
+            if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
+                memcpy(&broadaddr, &(ifreqP->ifr_broadaddr),
+                       sizeof(struct sockaddr));
+                broadaddrP = &broadaddr;
+            }
+        }
+
+        // restore socket address to ifreqP
+        memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
+
+        // determine netmask
+        if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
+            prefix = translateIPv4AddressToPrefix(
+                         (struct sockaddr_in *)&(ifreqP->ifr_addr));
+        }
+
+        // add interface to the list
+        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
+                    &addr, broadaddrP, AF_INET, prefix);
+
+        // in case of exception, free interface list and buffer and return NULL
+        if ((*env)->ExceptionOccurred(env)) {
+            free(buf);
+            freeif(ifs);
+            return NULL;
+        }
+    }
+
+    // free buffer
+    free(buf);
+    return ifs;
+}
+
+#if defined(AF_INET6)
+
+/*
+ * Enumerates and returns all IPv6 interfaces on AIX.
+ */
+static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    struct ifconf ifc;
+    struct ifreq *ifreqP;
+    char *buf, *cp, *cplimit;
+
+    // call SIOCGSIZIFCONF to get size for SIOCGIFCONF buffer
+    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
+        return ifs;
+    }
+
+    // call SIOCGIFCONF to enumerate the interfaces
+    CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
+    ifc.ifc_buf = buf;
+    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
+        free(buf);
+        return ifs;
+    }
+
+    // iterate through each interface
+    ifreqP = ifc.ifc_req;
+    cp = (char *)ifc.ifc_req;
+    cplimit = cp + ifc.ifc_len;
+
+    for (; cp < cplimit;
+         cp += (sizeof(ifreqP->ifr_name) +
+                MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr))))
+    {
+        ifreqP = (struct ifreq *)cp;
+        short prefix = 0;
+
+        // ignore non IPv6 addresses
+        if (ifreqP->ifr_addr.sa_family != AF_INET6) {
+            continue;
+        }
+
+        // determine netmask
+        struct in6_ifreq if6;
+        memset((char *)&if6, 0, sizeof(if6));
+        strncpy(if6.ifr_name, ifreqP->ifr_name, sizeof(if6.ifr_name) - 1);
+        memcpy(&(if6.ifr_Addr), &(ifreqP->ifr_addr),
+               sizeof(struct sockaddr_in6));
+        if (ioctl(sock, SIOCGIFNETMASK6, (char *)&if6) >= 0) {
+            prefix = translateIPv6AddressToPrefix(&(if6.ifr_Addr));
+        }
+
+        // set scope ID to interface index
+        ((struct sockaddr_in6 *)&(ifreqP->ifr_addr))->sin6_scope_id =
+            getIndex(sock, ifreqP->ifr_name);
+
+        // add interface to the list
+        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
+                    (struct sockaddr *)&(ifreqP->ifr_addr),
+                    NULL, AF_INET6, prefix);
+
+        // if an exception occurred then free the list
+        if ((*env)->ExceptionOccurred(env)) {
+            free(buf);
+            freeif(ifs);
+            return NULL;
+        }
+    }
+
+    // free buffer
+    free(buf);
+    return ifs;
+}
+
+#endif /* AF_INET6 */
+
+/*
+ * Try to get the interface index.
+ */
+static int getIndex(int sock, const char *name) {
+    int index = if_nametoindex(name);
+    return (index == 0) ? -1 : index;
+}
+
+/*
+ * Gets the Hardware address (usually MAC address) for the named interface.
+ * On return puts the data in buf, and returns the length, in byte, of the
+ * MAC address. Returns -1 if there is no hardware address on that interface.
+ */
+static int getMacAddress
+  (JNIEnv *env, const char *ifname, const struct in_addr *addr,
+   unsigned char *buf)
+{
     int size;
     struct kinfo_ndd *nddp;
     void *end;
@@ -1424,77 +1577,49 @@
     }
 
     return -1;
-#elif defined(__linux__)
-    static struct ifreq ifr;
-    int i;
-    memset((char *)&ifr, 0, sizeof(ifr));
-    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
-    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGIFHWADDR failed");
-        return -1;
-    }
-
-    memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
-
-    // All bytes to 0 means no hardware address.
-
-    for (i = 0; i < IFHWADDRLEN; i++) {
-        if (buf[i] != 0)
-            return IFHWADDRLEN;
-    }
-
-    return -1;
-#endif
 }
 
-static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
+static int getMTU(JNIEnv *env, int sock, const char *ifname) {
     struct ifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
-
-    if (ifname != NULL) {
-        strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-    } else {
-        JNU_ThrowNullPointerException(env, "network interface name is NULL");
-        return -1;
-    }
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "IOCTL SIOCGIFMTU failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
         return -1;
     }
 
-    return  if2.ifr_mtu;
+    return if2.ifr_mtu;
 }
 
 static int getFlags(int sock, const char *ifname, int *flags) {
-  struct ifreq if2;
-  memset((char *)&if2, 0, sizeof(if2));
-  strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+    struct ifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
-  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
-      return -1;
-  }
+    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
+        return -1;
+    }
 
-  if (sizeof(if2.ifr_flags) == sizeof(short)) {
-      *flags = (if2.ifr_flags & 0xffff);
-  } else {
-      *flags = if2.ifr_flags;
-  }
-  return 0;
+    if (sizeof(if2.ifr_flags) == sizeof(short)) {
+        *flags = (if2.ifr_flags & 0xffff);
+    } else {
+        *flags = if2.ifr_flags;
+    }
+    return 0;
 }
 
-#endif  /* defined(__linux__) || defined(_AIX) */
+#endif /* _AIX */
 
 /** Solaris **/
 #if defined(__solaris__)
 
+#if defined(AF_INET6)
 /*
- * Opens a socket for further ioct calls. Tries AF_INET socket first and
- * if it falls return AF_INET6 socket.
+ * Opens a socket for further ioctl calls. Tries AF_INET socket first and
+ * if it fails return AF_INET6 socket.
  */
-#ifdef AF_INET6
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock, alreadyV6 = 0;
     struct lifreq if2;
@@ -1502,35 +1627,32 @@
     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
         if (errno == EPROTONOSUPPORT) {
             if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                             "IPV6 Socket creation failed");
+                NET_ThrowByNameWithLastError
+                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
                 return -1;
             }
-
-            alreadyV6=1;
+            alreadyV6 = 1;
         } else { // errno is not NOSUPPORT
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                         "IPV4 Socket creation failed");
+            NET_ThrowByNameWithLastError
+                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
             return -1;
         }
     }
 
-
     // Solaris requires that we have an IPv6 socket to query an  interface
     // without an IPv4 address - check it here. POSIX 1 require the kernel to
     // return ENOTTY if the call is inappropriate for a device e.g. the NETMASK
     // for a device having IPv6 only address but not all devices follow the
     // standard so fall back on any error. It's not an ecologically friendly
     // gesture but more reliable.
-
     if (!alreadyV6) {
         memset((char *)&if2, 0, sizeof(if2));
         strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
         if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
             close(sock);
             if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                             "IPV6 Socket creation failed");
+                NET_ThrowByNameWithLastError
+                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
                 return -1;
             }
         }
@@ -1538,99 +1660,157 @@
 
     return sock;
 }
-
 #else
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env,AF_INET);
+    return openSocket(env, AF_INET);
 }
 #endif
 
 /*
- * Enumerates and returns all IPv4 interfaces.
+ * Enumerates and returns all IPv4 interfaces on Solaris.
  */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    return enumIPvXInterfaces(env,sock, ifs, AF_INET);
-}
-
-#ifdef AF_INET6
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    return enumIPvXInterfaces(env,sock, ifs, AF_INET6);
-}
-#endif
-
-/*
- * Enumerates and returns all interfaces on Solaris.
- * Uses the same code for IPv4 and IPv6.
- */
-static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family) {
     struct lifconf ifc;
-    struct lifreq *ifr;
-    int n;
-    char *buf;
+    struct lifreq *ifreqP;
     struct lifnum numifs;
-    unsigned bufsize;
+    char *buf = NULL;
+    unsigned i;
 
-    // Get the interface count
-    numifs.lifn_family = family;
+    // call SIOCGLIFNUM to get the interface count
+    numifs.lifn_family = AF_INET;
     numifs.lifn_flags = 0;
     if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGLIFNUM failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFNUM) failed");
         return ifs;
     }
 
-    //  Enumerate the interface configurations
-    bufsize = numifs.lifn_count * sizeof (struct lifreq);
-    CHECKED_MALLOC3(buf, char *, bufsize);
-
-    ifc.lifc_family = family;
-    ifc.lifc_flags = 0;
-    ifc.lifc_len = bufsize;
+    // call SIOCGLIFCONF to enumerate the interfaces
+    ifc.lifc_len = numifs.lifn_count * sizeof(struct lifreq);
+    CHECKED_MALLOC3(buf, char *, ifc.lifc_len);
     ifc.lifc_buf = buf;
+    ifc.lifc_family = AF_INET;
+    ifc.lifc_flags = 0;
     if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGLIFCONF failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFCONF) failed");
         free(buf);
         return ifs;
     }
 
-    // Iterate through each interface
-    ifr = ifc.lifc_req;
-    for (n=0; n<numifs.lifn_count; n++, ifr++) {
-        int index = -1;
-        struct lifreq if2;
+    // iterate through each interface
+    ifreqP = ifc.lifc_req;
+    for (i = 0; i < numifs.lifn_count; i++, ifreqP++) {
+        struct sockaddr addr, *broadaddrP = NULL;
 
-        // Ignore either IPv4 or IPv6 addresses
-        if (ifr->lifr_addr.ss_family != family) {
+        // ignore non IPv4 addresses
+        if (ifreqP->lifr_addr.ss_family != AF_INET) {
             continue;
         }
 
-#ifdef AF_INET6
-        if (ifr->lifr_addr.ss_family == AF_INET6) {
-            struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifr->lifr_addr);
-            s6->sin6_scope_id = getIndex(sock, ifr->lifr_name);
+        // save socket address
+        memcpy(&addr, &(ifreqP->lifr_addr), sizeof(struct sockaddr));
+
+        // determine broadcast address, if applicable
+        if ((ioctl(sock, SIOCGLIFFLAGS, ifreqP) == 0) &&
+            ifreqP->lifr_flags & IFF_BROADCAST) {
+
+            // restore socket address to ifreqP
+            memcpy(&(ifreqP->lifr_addr), &addr, sizeof(struct sockaddr));
+
+            // query broadcast address and set pointer to it
+            if (ioctl(sock, SIOCGLIFBRDADDR, ifreqP) == 0) {
+                broadaddrP = (struct sockaddr *)&(ifreqP->lifr_broadaddr);
+            }
         }
-#endif
 
         // add to the list
-        ifs = addif(env, sock,ifr->lifr_name, ifs,
-                    (struct sockaddr *)&(ifr->lifr_addr), family,
-                    (short)ifr->lifr_addrlen);
+        ifs = addif(env, sock, ifreqP->lifr_name, ifs,
+                    &addr, broadaddrP, AF_INET, (short)ifreqP->lifr_addrlen);
 
-        // If an exception occurred we return immediately
+        // if an exception occurred we return immediately
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             return ifs;
         }
-
    }
 
+    // free buffer
     free(buf);
     return ifs;
 }
 
+#if defined(AF_INET6)
+
+/*
+ * Enumerates and returns all IPv6 interfaces on Solaris.
+ */
+static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    struct lifconf ifc;
+    struct lifreq *ifreqP;
+    struct lifnum numifs;
+    char *buf = NULL;
+    unsigned i;
+
+    // call SIOCGLIFNUM to get the interface count
+    numifs.lifn_family = AF_INET6;
+    numifs.lifn_flags = 0;
+    if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFNUM) failed");
+        return ifs;
+    }
+
+    // call SIOCGLIFCONF to enumerate the interfaces
+    ifc.lifc_len = numifs.lifn_count * sizeof(struct lifreq);
+    CHECKED_MALLOC3(buf, char *, ifc.lifc_len);
+    ifc.lifc_buf = buf;
+    ifc.lifc_family = AF_INET6;
+    ifc.lifc_flags = 0;
+    if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFCONF) failed");
+        free(buf);
+        return ifs;
+    }
+
+    // iterate through each interface
+    ifreqP = ifc.lifc_req;
+    for (i = 0; i < numifs.lifn_count; i++, ifreqP++) {
+
+        // ignore non IPv6 addresses
+        if (ifreqP->lifr_addr.ss_family != AF_INET6) {
+            continue;
+        }
+
+        // set scope ID to interface index
+        ((struct sockaddr_in6 *)&(ifreqP->lifr_addr))->sin6_scope_id =
+            getIndex(sock, ifreqP->lifr_name);
+
+        // add to the list
+        ifs = addif(env, sock, ifreqP->lifr_name, ifs,
+                    (struct sockaddr *)&(ifreqP->lifr_addr),
+                    NULL, AF_INET6, (short)ifreqP->lifr_addrlen);
+
+        // if an exception occurred we return immediately
+        if ((*env)->ExceptionOccurred(env)) {
+            free(buf);
+            return ifs;
+        }
+    }
+
+    // free buffer
+    free(buf);
+    return ifs;
+}
+
+#endif /* AF_INET6 */
+
+/*
+ * Try to get the interface index.
+ * (Not supported on Solaris 2.6 or 7)
+ */
 static int getIndex(int sock, const char *name) {
-    // Try to get the interface index.  (Not supported on Solaris 2.6 or 7)
     struct lifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.lifr_name, name, sizeof(if2.lifr_name) - 1);
@@ -1643,77 +1823,12 @@
 }
 
 /*
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast
-  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
-{
-    struct sockaddr *ret = NULL;
-    struct lifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
-
-    // Let's make sure the interface does have a broadcast address
-    if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2)  < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGLIFFLAGS failed");
-        return ret;
-    }
-
-    if (if2.lifr_flags & IFF_BROADCAST) {
-        // It does, let's retrieve it
-        if (ioctl(sock, SIOCGLIFBRDADDR, (char *)&if2) < 0) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                         "ioctl SIOCGLIFBRDADDR failed");
-            return ret;
-        }
-
-        ret = brdcast_store;
-        memcpy(ret, &if2.lifr_broadaddr, sizeof(struct sockaddr));
-    }
-
-    return ret;
-}
-
-/*
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
-    unsigned int mask;
-    short ret;
-    struct lifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
-
-    if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGLIFNETMASK failed");
-        return -1;
-    }
-
-    mask = ntohl(((struct sockaddr_in*)&(if2.lifr_addr))->sin_addr.s_addr);
-    ret = 0;
-
-    while (mask) {
-       mask <<= 1;
-       ret++;
-    }
-
-    return ret;
-}
-
-
-#define DEV_PREFIX  "/dev/"
-
-/*
  * Solaris specific DLPI code to get hardware address from a device.
  * Unfortunately, at least up to Solaris X, you have to have special
  * privileges (i.e. be root).
  */
 static int getMacFromDevice
-  (JNIEnv *env, const char* ifname, unsigned char* retbuf)
+  (JNIEnv *env, const char *ifname, unsigned char *retbuf)
 {
     char style1dev[MAXPATHLEN];
     int fd;
@@ -1727,9 +1842,9 @@
     strcpy(style1dev, DEV_PREFIX);
     strcat(style1dev, ifname);
     if ((fd = open(style1dev, O_RDWR)) < 0) {
-         // Can't open it. We probably are missing the privilege.
-         // We'll have to try something else
-         return 0;
+        // Can't open it. We probably are missing the privilege.
+        // We'll have to try something else
+        return 0;
     }
 
     dlpareq.dl_primitive = DL_PHYS_ADDR_REQ;
@@ -1739,8 +1854,8 @@
     msg.len = DL_PHYS_ADDR_REQ_SIZE;
 
     if (putmsg(fd, &msg, NULL, 0) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "putmsg failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "putmsg() failed");
         return -1;
     }
 
@@ -1750,8 +1865,8 @@
     msg.len = 0;
     msg.maxlen = sizeof (buf);
     if (getmsg(fd, &msg, NULL, &flags) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "getmsg failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "getmsg() failed");
         return -1;
     }
 
@@ -1771,72 +1886,73 @@
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
 static int getMacAddress
-  (JNIEnv *env, int sock, const char *ifname, const struct in_addr* addr,
+  (JNIEnv *env, const char *ifname, const struct in_addr *addr,
    unsigned char *buf)
 {
-    struct arpreq arpreq;
-    struct sockaddr_in* sin;
-    struct sockaddr_in ipAddr;
-    int len, i;
-    struct lifreq lif;
+    struct lifreq if2;
+    int len, i, sock;
+
+    if ((sock = openSocketWithFallback(env, ifname)) < 0) {
+        return -1;
+    }
 
     // First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
     // try the old way.
-    memset(&lif, 0, sizeof(lif));
-    strlcpy(lif.lifr_name, ifname, sizeof(lif.lifr_name));
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
 
-    if (ioctl(sock, SIOCGLIFHWADDR, &lif) != -1) {
+    if (ioctl(sock, SIOCGLIFHWADDR, &if2) != -1) {
         struct sockaddr_dl *sp;
-        sp = (struct sockaddr_dl *)&lif.lifr_addr;
+        sp = (struct sockaddr_dl *)&if2.lifr_addr;
         memcpy(buf, &sp->sdl_data[0], sp->sdl_alen);
+        close(sock);
         return sp->sdl_alen;
     }
 
     // On Solaris we have to use DLPI, but it will only work if we have
     // privileged access (i.e. root). If that fails, we try a lookup
     // in the ARP table, which requires an IPv4 address.
-    if ((len = getMacFromDevice(env, ifname, buf))  == 0) {
-        // DLPI failed - trying to do arp lookup
+    if (((len = getMacFromDevice(env, ifname, buf)) == 0) && (addr != NULL)) {
+        struct arpreq arpreq;
+        struct sockaddr_in *sin;
+        struct sockaddr_in ipAddr;
 
-        if (addr == NULL) {
-             // No IPv4 address for that interface, so can't do an ARP lookup.
-             return -1;
-         }
+        len = 6; //???
 
-         len = 6; //???
+        sin = (struct sockaddr_in *)&arpreq.arp_pa;
+        memset((char *)&arpreq, 0, sizeof(struct arpreq));
+        ipAddr.sin_port = 0;
+        ipAddr.sin_family = AF_INET;
+        memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
+        memcpy(&arpreq.arp_pa, &ipAddr, sizeof(struct sockaddr_in));
+        arpreq.arp_flags= ATF_PUBL;
 
-         sin = (struct sockaddr_in *) &arpreq.arp_pa;
-         memset((char *) &arpreq, 0, sizeof(struct arpreq));
-         ipAddr.sin_port = 0;
-         ipAddr.sin_family = AF_INET;
-         memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
-         memcpy(&arpreq.arp_pa, &ipAddr, sizeof(struct sockaddr_in));
-         arpreq.arp_flags= ATF_PUBL;
+        if (ioctl(sock, SIOCGARP, &arpreq) < 0) {
+            close(sock);
+            return -1;
+        }
 
-         if (ioctl(sock, SIOCGARP, &arpreq) < 0) {
-             return -1;
-         }
-
-         memcpy(buf, &arpreq.arp_ha.sa_data[0], len );
+        memcpy(buf, &arpreq.arp_ha.sa_data[0], len);
     }
+    close(sock);
 
-    // All bytes to 0 means no hardware address.
+    // all bytes to 0 means no hardware address
     for (i = 0; i < len; i++) {
-      if (buf[i] != 0)
-         return len;
+        if (buf[i] != 0)
+            return len;
     }
 
     return -1;
 }
 
-static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
+static int getMTU(JNIEnv *env, int sock, const char *ifname) {
     struct lifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
 
     if (ioctl(sock, SIOCGLIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                    "ioctl SIOCGLIFMTU failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFMTU) failed");
         return -1;
     }
 
@@ -1856,67 +1972,73 @@
     return 0;
 }
 
-
-#endif  /* __solaris__ */
-
+#endif /* __solaris__ */
 
 /** BSD **/
-#ifdef _ALLBSD_SOURCE
+#if defined(_ALLBSD_SOURCE)
 
+#if defined(AF_INET6)
 /*
- * Opens a socket for further ioct calls. Tries AF_INET socket first and
- * if it falls return AF_INET6 socket.
+ * Opens a socket for further ioctl calls. Tries AF_INET socket first and
+ * if it fails return AF_INET6 socket.
  */
-#ifdef AF_INET6
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock;
-    struct ifreq if2;
 
-     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-         if (errno == EPROTONOSUPPORT) {
-              if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                              "IPV6 Socket creation failed");
-                 return -1;
-              }
-         } else { // errno is not NOSUPPORT
-             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                          "IPV4 Socket creation failed");
-             return -1;
-         }
-   }
+    if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+        if (errno == EPROTONOSUPPORT) {
+            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
+                NET_ThrowByNameWithLastError
+                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+                return -1;
+            }
+        } else { // errno is not NOSUPPORT
+            NET_ThrowByNameWithLastError
+                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
+            return -1;
+        }
+    }
 
-   return sock;
+    return sock;
 }
-
 #else
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env,AF_INET);
+    return openSocket(env, AF_INET);
 }
 #endif
 
 /*
- * Enumerates and returns all IPv4 interfaces.
+ * Enumerates and returns all IPv4 interfaces on BSD.
  */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifaddrs *ifa, *origifa;
 
     if (getifaddrs(&origifa) != 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "getifaddrs() function failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "getifaddrs() failed");
         return ifs;
     }
 
     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
+        struct sockaddr *broadaddrP = NULL;
 
-        // Skip non-AF_INET entries.
+        // ignore non IPv4 addresses
         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
             continue;
 
-        // Add to the list.
-        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET, 0);
+        // set ifa_broadaddr, if there is one
+        if ((ifa->ifa_flags & IFF_POINTOPOINT) == 0 &&
+            ifa->ifa_flags & IFF_BROADCAST) {
+            broadaddrP = ifa->ifa_dstaddr;
+        }
 
-        // If an exception occurred then free the list.
+        // add interface to the list
+        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr,
+                    broadaddrP, AF_INET,
+                    translateIPv4AddressToPrefix((struct sockaddr_in *)
+                                                 ifa->ifa_netmask));
+
+        // if an exception occurred then free the list
         if ((*env)->ExceptionOccurred(env)) {
             freeifaddrs(origifa);
             freeif(ifs);
@@ -1924,76 +2046,41 @@
         }
     }
 
-    // Free socket and buffer
+    // free ifaddrs buffer
     freeifaddrs(origifa);
     return ifs;
 }
 
-#ifdef AF_INET6
-/*
- * Determines the prefix on BSD for IPv6 interfaces.
- */
-static int prefix(void *val, int size) {
-    u_char *name = (u_char *)val;
-    int byte, bit, prefix = 0;
-
-    for (byte = 0; byte < size; byte++, prefix += 8)
-        if (name[byte] != 0xff)
-            break;
-    if (byte == size)
-        return prefix;
-    for (bit = 7; bit != 0; bit--, prefix++)
-        if (!(name[byte] & (1 << bit)))
-            break;
-    for (; bit != 0; bit--)
-        if (name[byte] & (1 << bit))
-            return (0);
-    byte++;
-    for (; byte < size; byte++)
-        if (name[byte])
-            return (0);
-    return prefix;
-}
+#if defined(AF_INET6)
 
 /*
  * Enumerates and returns all IPv6 interfaces on BSD.
  */
 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifaddrs *ifa, *origifa;
-    struct sockaddr_in6 *sin6;
-    struct in6_ifreq ifr6;
 
     if (getifaddrs(&origifa) != 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "getifaddrs() function failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "getifaddrs() failed");
         return ifs;
     }
 
     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
-
-        // Skip non-AF_INET6 entries.
+        // ignore non IPv6 addresses
         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET6)
             continue;
 
-        memset(&ifr6, 0, sizeof(ifr6));
-        strlcpy(ifr6.ifr_name, ifa->ifa_name, sizeof(ifr6.ifr_name));
-        memcpy(&ifr6.ifr_addr, ifa->ifa_addr,
-               MIN(sizeof(ifr6.ifr_addr), ifa->ifa_addr->sa_len));
+        // set scope ID to interface index
+        ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id =
+            getIndex(sock, ifa->ifa_name);
 
-        if (ioctl(sock, SIOCGIFNETMASK_IN6, (caddr_t)&ifr6) < 0) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                         "ioctl SIOCGIFNETMASK_IN6 failed");
-            freeifaddrs(origifa);
-            freeif(ifs);
-            return NULL;
-        }
+        // add interface to the list
+        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, NULL,
+                    AF_INET6,
+                    translateIPv6AddressToPrefix((struct sockaddr_in6 *)
+                                                 ifa->ifa_netmask));
 
-        // Add to the list.
-        sin6 = (struct sockaddr_in6 *)&ifr6.ifr_addr;
-        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET6,
-            (short)prefix(&sin6->sin6_addr, sizeof(struct in6_addr)));
-
-        // If an exception occurred then free the list.
+        // if an exception occurred then free the list
         if ((*env)->ExceptionOccurred(env)) {
             freeifaddrs(origifa);
             freeif(ifs);
@@ -2001,16 +2088,21 @@
         }
     }
 
-    // Free socket and ifaddrs buffer
+    // free ifaddrs buffer
     freeifaddrs(origifa);
     return ifs;
 }
-#endif
 
+#endif /* AF_INET6 */
+
+/*
+ * Try to get the interface index.
+ */
 static int getIndex(int sock, const char *name) {
-#ifdef __FreeBSD__
-    // Try to get the interface index
-    // (Not supported on Solaris 2.6 or 7)
+#if !defined(__FreeBSD__)
+    int index = if_nametoindex(name);
+    return (index == 0) ? -1 : index;
+#else
     struct ifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
@@ -2020,96 +2112,31 @@
     }
 
     return if2.ifr_index;
-#else
-    // Try to get the interface index using BSD specific if_nametoindex
-    int index = if_nametoindex(name);
-    return (index == 0) ? -1 : index;
 #endif
 }
 
 /*
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast
-  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
-{
-    struct sockaddr *ret = NULL;
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    // Make sure the interface does have a broadcast address
-    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGIFFLAGS failed");
-        return ret;
-    }
-
-    if (if2.ifr_flags & IFF_BROADCAST) {
-        // It does, let's retrieve it
-        if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                         "ioctl SIOCGIFBRDADDR failed");
-            return ret;
-        }
-
-        ret = brdcast_store;
-        memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
-    }
-
-    return ret;
-}
-
-/*
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
-    unsigned int mask;
-    short ret;
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGIFNETMASK failed");
-        return -1;
-    }
-
-    mask = ntohl(((struct sockaddr_in*)&(if2.ifr_addr))->sin_addr.s_addr);
-    ret = 0;
-    while (mask) {
-       mask <<= 1;
-       ret++;
-    }
-
-    return ret;
-}
-
-/*
  * Gets the Hardware address (usually MAC address) for the named interface.
- * return puts the data in buf, and returns the length, in byte, of the
+ * On return puts the data in buf, and returns the length, in byte, of the
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
 static int getMacAddress
-  (JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr,
+  (JNIEnv *env, const char *ifname, const struct in_addr *addr,
    unsigned char *buf)
 {
     struct ifaddrs *ifa0, *ifa;
     struct sockaddr *saddr;
     int i;
 
-    // Grab the interface list
+    // grab the interface list
     if (!getifaddrs(&ifa0)) {
-        // Cycle through the interfaces
+        // cycle through the interfaces
         for (i = 0, ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next, i++) {
             saddr = ifa->ifa_addr;
-            // Link layer contains the MAC address
+            // link layer contains the MAC address
             if (saddr->sa_family == AF_LINK && !strcmp(ifname, ifa->ifa_name)) {
                 struct sockaddr_dl *sadl = (struct sockaddr_dl *) saddr;
-                // Check the address is the correct length
+                // check the address has the correct length
                 if (sadl->sdl_alen == ETHER_ADDR_LEN) {
                     memcpy(buf, (sadl->sdl_data + sadl->sdl_nlen), ETHER_ADDR_LEN);
                     freeifaddrs(ifa0);
@@ -2123,23 +2150,22 @@
     return -1;
 }
 
-static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
+static int getMTU(JNIEnv *env, int sock, const char *ifname) {
     struct ifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
-                                     "ioctl SIOCGIFMTU failed");
+        NET_ThrowByNameWithLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
         return -1;
     }
 
-    return  if2.ifr_mtu;
+    return if2.ifr_mtu;
 }
 
 static int getFlags(int sock, const char *ifname, int *flags) {
     struct ifreq if2;
-    int ret = -1;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
@@ -2154,4 +2180,4 @@
     }
     return 0;
 }
-#endif /* __ALLBSD_SOURCE__ */
+#endif /* _ALLBSD_SOURCE */
diff --git a/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c b/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
index 406654d..c48d115 100644
--- a/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
+++ b/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
@@ -174,9 +174,8 @@
     IO_fd_fdID = NET_GetFileDescriptorID(env);
     CHECK_NULL(IO_fd_fdID);
 
-    Java_java_net_InetAddress_init(env, 0);
-    Java_java_net_Inet4Address_init(env, 0);
-    Java_java_net_Inet6Address_init(env, 0);
+    initInetAddressIDs(env);
+    JNU_CHECK_EXCEPTION(env);
     Java_java_net_NetworkInterface_init(env, 0);
 
 }
diff --git a/jdk/src/solaris/native/java/net/PlainSocketImpl.c b/jdk/src/solaris/native/java/net/PlainSocketImpl.c
index 724c1cf..71cbdf8 100644
--- a/jdk/src/solaris/native/java/net/PlainSocketImpl.c
+++ b/jdk/src/solaris/native/java/net/PlainSocketImpl.c
@@ -162,6 +162,9 @@
     IO_fd_fdID = NET_GetFileDescriptorID(env);
     CHECK_NULL(IO_fd_fdID);
 
+    initInetAddressIDs(env);
+    JNU_CHECK_EXCEPTION(env);
+
     /* Create the marker fd used for dup2 */
     marker_fd = getMarkerFD();
 }
diff --git a/jdk/src/solaris/native/java/net/net_util_md.c b/jdk/src/solaris/native/java/net/net_util_md.c
index 14aa8ad..eae347c 100644
--- a/jdk/src/solaris/native/java/net/net_util_md.c
+++ b/jdk/src/solaris/native/java/net/net_util_md.c
@@ -334,6 +334,7 @@
     if (getsockname(0, (struct sockaddr *)&sa, &sa_len) == 0) {
         struct sockaddr *saP = (struct sockaddr *)&sa;
         if (saP->sa_family != AF_INET6) {
+            close(fd);
             return JNI_FALSE;
         }
     }
@@ -1208,16 +1209,10 @@
                int *len)
 {
     int rv;
+    socklen_t socklen = *len;
 
-#ifdef __solaris__
-    rv = getsockopt(fd, level, opt, result, len);
-#else
-    {
-        socklen_t socklen = *len;
-        rv = getsockopt(fd, level, opt, result, &socklen);
-        *len = socklen;
-    }
-#endif
+    rv = getsockopt(fd, level, opt, result, &socklen);
+    *len = socklen;
 
     if (rv < 0) {
         return rv;
diff --git a/jdk/src/solaris/native/sun/awt/CUPSfuncs.c b/jdk/src/solaris/native/sun/awt/CUPSfuncs.c
index d7d9896..ce8350d 100644
--- a/jdk/src/solaris/native/sun/awt/CUPSfuncs.c
+++ b/jdk/src/solaris/native/sun/awt/CUPSfuncs.c
@@ -43,6 +43,10 @@
 typedef http_t* (*fn_httpConnect)(const char *, int);
 typedef void (*fn_httpClose)(http_t *);
 typedef char* (*fn_cupsGetPPD)(const char *);
+typedef cups_dest_t* (*fn_cupsGetDest)(const char *name,
+    const char *instance, int num_dests, cups_dest_t *dests);
+typedef int (*fn_cupsGetDests)(cups_dest_t **dests);
+typedef void (*fn_cupsFreeDests)(int num_dests, cups_dest_t *dests);
 typedef ppd_file_t* (*fn_ppdOpenFile)(const char *);
 typedef void (*fn_ppdClose)(ppd_file_t *);
 typedef ppd_option_t* (*fn_ppdFindOption)(ppd_file_t *, const char *);
@@ -53,6 +57,9 @@
 fn_httpConnect j2d_httpConnect;
 fn_httpClose j2d_httpClose;
 fn_cupsGetPPD j2d_cupsGetPPD;
+fn_cupsGetDest j2d_cupsGetDest;
+fn_cupsGetDests j2d_cupsGetDests;
+fn_cupsFreeDests j2d_cupsFreeDests;
 fn_ppdOpenFile j2d_ppdOpenFile;
 fn_ppdClose j2d_ppdClose;
 fn_ppdFindOption j2d_ppdFindOption;
@@ -106,6 +113,24 @@
     return JNI_FALSE;
   }
 
+  j2d_cupsGetDest = (fn_cupsGetDest)dlsym(handle, "cupsGetDest");
+  if (j2d_cupsGetDest == NULL) {
+    dlclose(handle);
+    return JNI_FALSE;
+  }
+
+  j2d_cupsGetDests = (fn_cupsGetDests)dlsym(handle, "cupsGetDests");
+  if (j2d_cupsGetDests == NULL) {
+    dlclose(handle);
+    return JNI_FALSE;
+  }
+
+  j2d_cupsFreeDests = (fn_cupsFreeDests)dlsym(handle, "cupsFreeDests");
+  if (j2d_cupsFreeDests == NULL) {
+    dlclose(handle);
+    return JNI_FALSE;
+  }
+
   j2d_ppdOpenFile = (fn_ppdOpenFile)dlsym(handle, "ppdOpenFile");
   if (j2d_ppdOpenFile == NULL) {
     dlclose(handle);
@@ -170,6 +195,30 @@
 
 
 /*
+ * Gets CUPS default printer name.
+ *
+ */
+JNIEXPORT jstring JNICALL
+Java_sun_print_CUPSPrinter_getCupsDefaultPrinter(JNIEnv *env,
+                                                  jobject printObj)
+{
+    jstring cDefPrinter = NULL;
+    cups_dest_t *dests;
+    char *defaultPrinter = NULL;
+    int num_dests = j2d_cupsGetDests(&dests);
+    int i = 0;
+    cups_dest_t *dest = j2d_cupsGetDest(NULL, NULL, num_dests, dests);
+    if (dest != NULL) {
+        defaultPrinter = dest->name;
+        if (defaultPrinter != NULL) {
+            cDefPrinter = JNU_NewStringPlatform(env, defaultPrinter);
+        }
+    }
+    j2d_cupsFreeDests(num_dests, dests);
+    return cDefPrinter;
+}
+
+/*
  * Checks if connection can be made to the server.
  *
  */
diff --git a/jdk/src/solaris/native/sun/awt/awt_Robot.c b/jdk/src/solaris/native/sun/awt/awt_Robot.c
index 89f282c..b8f1b75 100644
--- a/jdk/src/solaris/native/sun/awt/awt_Robot.c
+++ b/jdk/src/solaris/native/sun/awt/awt_Robot.c
@@ -61,9 +61,9 @@
 
     /* check if XTest is available */
     isXTestAvailable = XQueryExtension(awt_display, XTestExtensionName, &major_opcode, &first_event, &first_error);
-    DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XTEST) returns major_opcode = %d, first_event = %d, first_error = %d",
-                    major_opcode, first_event, first_error);
     if (isXTestAvailable) {
+        DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XTEST) returns major_opcode = %d, first_event = %d, first_error = %d",
+                        major_opcode, first_event, first_error);
         /* check if XTest version is OK */
         XTestQueryExtension(awt_display, &event_basep, &error_basep, &majorp, &minorp);
         DTRACE_PRINTLN4("RobotPeer: XTestQueryExtension returns event_basep = %d, error_basep = %d, majorp = %d, minorp = %d",
diff --git a/jdk/src/solaris/native/sun/awt/fontpath.c b/jdk/src/solaris/native/sun/awt/fontpath.c
index 3d1d020..4ebf381 100644
--- a/jdk/src/solaris/native/sun/awt/fontpath.c
+++ b/jdk/src/solaris/native/sun/awt/fontpath.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -804,30 +804,36 @@
     pattern = (*FcPatternBuild)(NULL, FC_OUTLINE, FcTypeBool, FcTrue, NULL);
     objset = (*FcObjectSetBuild)(FC_FILE, NULL);
     fontSet = (*FcFontList)(NULL, pattern, objset);
-    fontdirs = (char**)calloc(fontSet->nfont+1, sizeof(char*));
-    for (f=0; f < fontSet->nfont; f++) {
-        FcChar8 *file;
-        FcChar8 *dir;
-        if ((*FcPatternGetString)(fontSet->fonts[f], FC_FILE, 0, &file) ==
-                                  FcResultMatch) {
-            dir = (*FcStrDirname)(file);
-            found = 0;
-            for (i=0;i<numdirs; i++) {
-                if (strcmp(fontdirs[i], (char*)dir) == 0) {
-                    found = 1;
-                    break;
+    if (fontSet == NULL) {
+        /* FcFontList() may return NULL if fonts are not installed. */
+        fontdirs = NULL;
+    } else {
+        fontdirs = (char**)calloc(fontSet->nfont+1, sizeof(char*));
+        for (f=0; f < fontSet->nfont; f++) {
+            FcChar8 *file;
+            FcChar8 *dir;
+            if ((*FcPatternGetString)(fontSet->fonts[f], FC_FILE, 0, &file) ==
+                                      FcResultMatch) {
+                dir = (*FcStrDirname)(file);
+                found = 0;
+                for (i=0;i<numdirs; i++) {
+                    if (strcmp(fontdirs[i], (char*)dir) == 0) {
+                        found = 1;
+                        break;
+                    }
+                }
+                if (!found) {
+                    fontdirs[numdirs++] = (char*)dir;
+                } else {
+                    free((char*)dir);
                 }
             }
-            if (!found) {
-                fontdirs[numdirs++] = (char*)dir;
-            } else {
-                free((char*)dir);
-            }
         }
+        /* Free fontset if one was returned */
+        (*FcFontSetDestroy)(fontSet);
     }
 
     /* Free memory and close the ".so" */
-    (*FcFontSetDestroy)(fontSet);
     (*FcPatternDestroy)(pattern);
     closeFontConfig(libfontconfig, JNI_TRUE);
     return fontdirs;
diff --git a/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c b/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c
index f5dd361..bf7d578 100644
--- a/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c
+++ b/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c
@@ -201,7 +201,7 @@
     }
     if (senderAddr == NULL) {
         jobject isa = NULL;
-        int port;
+        int port = 0;
         jobject ia = NET_SockaddrToInetAddress(env, (struct sockaddr *)&sa, &port);
         if (ia != NULL) {
             isa = (*env)->NewObject(env, isa_class, isa_ctorID, ia, port);
diff --git a/jdk/src/solaris/native/sun/nio/ch/IOUtil.c b/jdk/src/solaris/native/sun/nio/ch/IOUtil.c
index 438bf41..d8bbe84 100644
--- a/jdk/src/solaris/native/sun/nio/ch/IOUtil.c
+++ b/jdk/src/solaris/native/sun/nio/ch/IOUtil.c
@@ -35,6 +35,7 @@
 #include "java_lang_Integer.h"
 #include "nio.h"
 #include "nio_util.h"
+#include "net_util.h"
 
 static jfieldID fd_fdID;        /* for jint 'fd' in java.io.FileDescriptor */
 
@@ -44,6 +45,7 @@
 {
     CHECK_NULL(clazz = (*env)->FindClass(env, "java/io/FileDescriptor"));
     CHECK_NULL(fd_fdID = (*env)->GetFieldID(env, clazz, "fd", "I"));
+    initInetAddressIDs(env);
 }
 
 JNIEXPORT jboolean JNICALL
diff --git a/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c b/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c
index e96c9b0..04a400a 100644
--- a/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c
+++ b/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c
@@ -84,7 +84,7 @@
     int alloc_len;
     jobject remote_ia = 0;
     jobject isa;
-    jint remote_port;
+    jint remote_port = 0;
 
     NET_AllocSockaddr(&sa, &alloc_len);
     if (sa == NULL) {
diff --git a/jdk/src/solaris/native/sun/nio/ch/sctp/SctpNet.c b/jdk/src/solaris/native/sun/nio/ch/sctp/SctpNet.c
index 1b700bb..9c3efc0 100644
--- a/jdk/src/solaris/native/sun/nio/ch/sctp/SctpNet.c
+++ b/jdk/src/solaris/native/sun/nio/ch/sctp/SctpNet.c
@@ -157,6 +157,7 @@
     }
     preCloseFD = sp[0];
     close(sp[1]);
+    initInetAddressIDs(env);
 }
 
 /*
@@ -430,7 +431,7 @@
     paddr = addr_buf;
     for (i=0; i<addrCount; i++) {
         jobject ia, isa = NULL;
-        int port;
+        int port = 0;
         sap = (struct sockaddr*)addr_buf;
         ia = NET_SockaddrToInetAddress(env, sap, &port);
         if (ia != NULL)
@@ -542,6 +543,7 @@
     void *arg;
     int arglen;
 
+    memset((char *) &linger, 0, sizeof(linger));
     if (mapSocketOption(opt, &klevel, &kopt) < 0) {
         JNU_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
                                      "Unsupported socket option");
@@ -599,7 +601,7 @@
   (JNIEnv *env, jclass klass, jint fd, jint assocId, jobject iaObj, jint port) {
     struct sctp_setprim prim;
     struct sockaddr* sap = (struct sockaddr*)&prim.ssp_addr;
-    int sap_len;
+    int sap_len = sizeof(sap);
 
     if (NET_InetAddressToSockaddr(env, iaObj, port, sap,
                                   &sap_len, JNI_TRUE) != 0) {
@@ -624,7 +626,7 @@
    jobject iaObj, jint port, jboolean preferIPv6) {
     struct sctp_setpeerprim prim;
     struct sockaddr* sap = (struct sockaddr*)&prim.sspp_addr;
-    int sap_len;
+    int sap_len = sizeof(sap);
 
     if (NET_InetAddressToSockaddr(env, iaObj, port, sap,
                                   &sap_len, preferIPv6) != 0) {
diff --git a/jdk/src/solaris/native/sun/nio/fs/MacOSXNativeDispatcher.c b/jdk/src/solaris/native/sun/nio/fs/MacOSXNativeDispatcher.c
index f3602b8..5c75293 100644
--- a/jdk/src/solaris/native/sun/nio/fs/MacOSXNativeDispatcher.c
+++ b/jdk/src/solaris/native/sun/nio/fs/MacOSXNativeDispatcher.c
@@ -39,12 +39,15 @@
                                                      jint form)
 {
     jcharArray result = NULL;
-    char chars_buf[(PATH_MAX + 1) * 2];     // utf16 + zero padding
+    char *chars;
     CFMutableStringRef csref = CFStringCreateMutable(NULL, 0);
     if (csref == NULL) {
         JNU_ThrowOutOfMemoryError(env, "native heap");
-    } else {
-        char *chars = (char*)(*env)->GetPrimitiveArrayCritical(env, path, 0);
+        return NULL;
+    }
+    chars = (char*)(*env)->GetPrimitiveArrayCritical(env, path, 0);
+    if (chars != NULL) {
+        char chars_buf[(PATH_MAX + 1) * 2];     // utf16 + zero padding
         jsize len = (*env)->GetArrayLength(env, path);
         CFStringAppendCharacters(csref, (const UniChar*)chars, len);
         (*env)->ReleasePrimitiveArrayCritical(env, path, chars, 0);
@@ -53,24 +56,26 @@
         if (len < PATH_MAX) {
             if (CFStringGetCString(csref, chars_buf, sizeof(chars_buf), kCFStringEncodingUTF16)) {
                 result = (*env)->NewCharArray(env, len);
-                (*env)->SetCharArrayRegion(env, result, 0, len, (jchar*)&chars_buf);
+                if (result != NULL) {
+                    (*env)->SetCharArrayRegion(env, result, 0, len, (jchar*)&chars_buf);
+                }
             }
         } else {
             int ulen = (len + 1) * 2;
             chars = malloc(ulen);
             if (chars == NULL) {
-                CFRelease(csref);
                 JNU_ThrowOutOfMemoryError(env, "native heap");
-                return result;
             } else {
                 if (CFStringGetCString(csref, chars, ulen, kCFStringEncodingUTF16)) {
                     result = (*env)->NewCharArray(env, len);
-                    (*env)->SetCharArrayRegion(env, result, 0, len, (jchar*)chars);
+                    if (result != NULL) {
+                        (*env)->SetCharArrayRegion(env, result, 0, len, (jchar*)chars);
+                    }
                 }
                 free(chars);
             }
         }
-        CFRelease(csref);
     }
+    CFRelease(csref);
     return result;
 }
diff --git a/jdk/src/solaris/native/sun/xawt/XToolkit.c b/jdk/src/solaris/native/sun/xawt/XToolkit.c
index 099c167..71d41f3 100644
--- a/jdk/src/solaris/native/sun/xawt/XToolkit.c
+++ b/jdk/src/solaris/native/sun/xawt/XToolkit.c
@@ -1020,9 +1020,9 @@
      * before calling XTestFakeButtonEvent().
      */
     xinputAvailable = XQueryExtension(awt_display, INAME, &major_opcode, &first_event, &first_error);
-    DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XINPUT) returns major_opcode = %d, first_event = %d, first_error = %d",
-                    major_opcode, first_event, first_error);
     if (xinputAvailable) {
+        DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XINPUT) returns major_opcode = %d, first_event = %d, first_error = %d",
+                        major_opcode, first_event, first_error);
         devices = XListInputDevices(awt_display, &numDevices);
         for (devIdx = 0; devIdx < numDevices; devIdx++) {
             aDevice = &(devices[devIdx]);
diff --git a/jdk/src/windows/classes/com/sun/java/accessibility/AccessBridge.java b/jdk/src/windows/classes/com/sun/java/accessibility/AccessBridge.java
index 3b176da..f2802f6 100644
--- a/jdk/src/windows/classes/com/sun/java/accessibility/AccessBridge.java
+++ b/jdk/src/windows/classes/com/sun/java/accessibility/AccessBridge.java
@@ -807,7 +807,7 @@
             }
 
             if (false == bExtendedSearch) {
-                debugString ("bk -- getVirtualAccessibleNameFromContext will not use the extended name search algorithm.  role = " + role.toDisplayString (Locale.US) );
+                debugString ("bk -- getVirtualAccessibleNameFromContext will not use the extended name search algorithm.  role = " + ( role != null ? role.toDisplayString(Locale.US) : "null") );
                 /*
                 Step 3:
                 =======
@@ -4625,6 +4625,10 @@
     private void _getVisibleChildrenCount(final AccessibleContext ac) {
         if (ac == null)
             return;
+        if(ac instanceof AccessibleExtendedTable) {
+            _getVisibleChildrenCount((AccessibleExtendedTable)ac);
+            return;
+        }
         int numChildren = InvocationUtils.invokeAndWait(new Callable<Integer>() {
             @Override
             public Integer call() throws Exception {
@@ -4666,6 +4670,83 @@
         }
     }
 
+    /*
+    * Recursively descends AccessibleContext and gets the number
+    * of visible children. Stops search if get to invisible part of table.
+    */
+    private void _getVisibleChildrenCount(final AccessibleExtendedTable acTable) {
+        if (acTable == null)
+            return;
+        int lastVisibleRow = -1;
+        int lastVisibleColumn = -1;
+        boolean foundVisible = false;
+        int rowCount = InvocationUtils.invokeAndWait(new Callable<Integer>() {
+            @Override
+            public Integer call() throws Exception {
+                return acTable.getAccessibleRowCount();
+            }
+        }, acTable);
+        int columnCount = InvocationUtils.invokeAndWait(new Callable<Integer>() {
+            @Override
+            public Integer call() throws Exception {
+                return acTable.getAccessibleColumnCount();
+            }
+        }, acTable);
+        for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) {
+            for (int columnIdx = 0; columnIdx < columnCount; columnIdx++) {
+                if (lastVisibleRow != -1 && rowIdx > lastVisibleRow) {
+                    continue;
+                }
+                if (lastVisibleColumn != -1 && columnIdx > lastVisibleColumn) {
+                    continue;
+                }
+                int finalRowIdx = rowIdx;
+                int finalColumnIdx = columnIdx;
+                final AccessibleContext ac2 = InvocationUtils.invokeAndWait(new Callable<AccessibleContext>() {
+                    @Override
+                    public AccessibleContext call() throws Exception {
+                        Accessible a = acTable.getAccessibleAt(finalRowIdx, finalColumnIdx);
+                        if (a == null)
+                            return null;
+                        else
+                            return a.getAccessibleContext();
+                    }
+                }, acTable);
+                if (ac2 == null ||
+                        (!InvocationUtils.invokeAndWait(new Callable<Boolean>() {
+                            @Override
+                            public Boolean call() throws Exception {
+                                return ac2.getAccessibleStateSet().contains(AccessibleState.SHOWING);
+                            }
+                        }, acTable))
+                        ) {
+                    if (foundVisible) {
+                        if (columnIdx != 0 && lastVisibleColumn == -1) {
+                            //the same row, so we found the last visible column
+                            lastVisibleColumn = columnIdx - 1;
+                        } else if (columnIdx == 0 && lastVisibleRow == -1) {
+                            lastVisibleRow = rowIdx - 1;
+                        }
+                    }
+                    continue;
+                }
+
+                foundVisible = true;
+
+                _visibleChildrenCount++;
+
+                if (InvocationUtils.invokeAndWait(new Callable<Integer>() {
+                    @Override
+                    public Integer call() throws Exception {
+                        return ac2.getAccessibleChildrenCount();
+                    }
+                }, acTable) > 0) {
+                    _getVisibleChildrenCount(ac2);
+                }
+            }
+        }
+    }
+
     /**
      * Gets the visible child of an AccessibleContext at the
      * specified index
@@ -4702,7 +4783,10 @@
         if (_visibleChild != null) {
             return;
         }
-
+        if(ac instanceof AccessibleExtendedTable) {
+            _getVisibleChild((AccessibleExtendedTable)ac, index);
+            return;
+        }
         int numChildren = InvocationUtils.invokeAndWait(new Callable<Integer>() {
             @Override
             public Integer call() throws Exception {
@@ -4711,7 +4795,7 @@
         }, ac);
         for (int i = 0; i < numChildren; i++) {
             final int idx=i;
-            final AccessibleContext ac2=InvocationUtils.invokeAndWait(new Callable<AccessibleContext>() {
+            final AccessibleContext ac2 = InvocationUtils.invokeAndWait(new Callable<AccessibleContext>() {
                 @Override
                 public AccessibleContext call() throws Exception {
                     Accessible a = ac.getAccessibleChild(idx);
@@ -4748,6 +4832,82 @@
         }
     }
 
+    private void _getVisibleChild(final AccessibleExtendedTable acTable, final int index) {
+        if (_visibleChild != null) {
+            return;
+        }
+        int lastVisibleRow = -1;
+        int lastVisibleColumn = -1;
+        boolean foundVisible = false;
+        int rowCount = InvocationUtils.invokeAndWait(new Callable<Integer>() {
+            @Override
+            public Integer call() throws Exception {
+                return acTable.getAccessibleRowCount();
+            }
+        }, acTable);
+        int columnCount = InvocationUtils.invokeAndWait(new Callable<Integer>() {
+            @Override
+            public Integer call() throws Exception {
+                return acTable.getAccessibleColumnCount();
+            }
+        }, acTable);
+        for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) {
+            for (int columnIdx = 0; columnIdx < columnCount; columnIdx++) {
+                if (lastVisibleRow != -1 && rowIdx > lastVisibleRow) {
+                    continue;
+                }
+                if (lastVisibleColumn != -1 && columnIdx > lastVisibleColumn) {
+                    continue;
+                }
+                int finalRowIdx = rowIdx;
+                int finalColumnIdx = columnIdx;
+                final AccessibleContext ac2 = InvocationUtils.invokeAndWait(new Callable<AccessibleContext>() {
+                    @Override
+                    public AccessibleContext call() throws Exception {
+                        Accessible a = acTable.getAccessibleAt(finalRowIdx, finalColumnIdx);
+                        if (a == null)
+                            return null;
+                        else
+                            return a.getAccessibleContext();
+                    }
+                }, acTable);
+                if (ac2 == null ||
+                        (!InvocationUtils.invokeAndWait(new Callable<Boolean>() {
+                            @Override
+                            public Boolean call() throws Exception {
+                                return ac2.getAccessibleStateSet().contains(AccessibleState.SHOWING);
+                            }
+                        }, acTable))) {
+                    if (foundVisible) {
+                        if (columnIdx != 0 && lastVisibleColumn == -1) {
+                            //the same row, so we found the last visible column
+                            lastVisibleColumn = columnIdx - 1;
+                        } else if (columnIdx == 0 && lastVisibleRow == -1) {
+                            lastVisibleRow = rowIdx - 1;
+                        }
+                    }
+                    continue;
+                }
+                foundVisible = true;
+
+                if (!_foundVisibleChild && _currentVisibleIndex == index) {
+                    _visibleChild = ac2;
+                    _foundVisibleChild = true;
+                    return;
+                }
+                _currentVisibleIndex++;
+
+                if (InvocationUtils.invokeAndWait(new Callable<Integer>() {
+                    @Override
+                    public Integer call() throws Exception {
+                        return ac2.getAccessibleChildrenCount();
+                    }
+                }, acTable) > 0) {
+                    _getVisibleChild(ac2, index);
+                }
+            }
+        }
+    }
 
     /* ===== Java object memory management code ===== */
 
@@ -7128,6 +7288,25 @@
          * and waits for it to finish blocking the caller thread.
          *
          * @param callable   the {@code Callable} to invoke
+         * @param accessibleTable the {@code AccessibleExtendedTable} which would be used to find the right context
+         *                   for the task execution
+         * @param <T> type parameter for the result value
+         *
+         * @return the result of the {@code Callable} execution
+         */
+        public static <T> T invokeAndWait(final Callable<T> callable,
+                                          final AccessibleExtendedTable accessibleTable) {
+            if (accessibleTable instanceof AccessibleContext) {
+                return invokeAndWait(callable, (AccessibleContext)accessibleTable);
+            }
+            throw new RuntimeException("Unmapped AccessibleContext used to dispatch event: " + accessibleTable);
+        }
+
+        /**
+         * Invokes a {@code Callable} in the {@code AppContext} of the given {@code Accessible}
+         * and waits for it to finish blocking the caller thread.
+         *
+         * @param callable   the {@code Callable} to invoke
          * @param accessible the {@code Accessible} which would be used to find the right context
          *                   for the task execution
          * @param <T> type parameter for the result value
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsWatchService.java b/jdk/src/windows/classes/sun/nio/fs/WindowsWatchService.java
index cf3a6de..2201a24 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsWatchService.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsWatchService.java
@@ -113,6 +113,10 @@
         // completion key (used to map I/O completion to WatchKey)
         private int completionKey;
 
+        // flag indicates that ReadDirectoryChangesW failed
+        // and overlapped I/O operation wasn't started
+        private boolean errorStartingOverlapped;
+
         WindowsWatchKey(Path dir,
                         AbstractWatchService watcher,
                         FileKey fileKey)
@@ -175,6 +179,14 @@
             return completionKey;
         }
 
+        void setErrorStartingOverlapped(boolean value) {
+            errorStartingOverlapped = value;
+        }
+
+        boolean isErrorStartingOverlapped() {
+            return errorStartingOverlapped;
+        }
+
         // Invalidate the key, assumes that resources have been released
         void invalidate() {
             ((WindowsWatchService)watcher()).poller.releaseResources(this);
@@ -182,6 +194,7 @@
             buffer = null;
             countAddress = 0;
             overlappedAddress = 0;
+            errorStartingOverlapped = false;
         }
 
         @Override
@@ -455,11 +468,13 @@
          * resources.
          */
         private void releaseResources(WindowsWatchKey key) {
-            try {
-                CancelIo(key.handle());
-                GetOverlappedResult(key.handle(), key.overlappedAddress());
-            } catch (WindowsException expected) {
-                // expected as I/O operation has been cancelled
+            if (!key.isErrorStartingOverlapped()) {
+                try {
+                    CancelIo(key.handle());
+                    GetOverlappedResult(key.handle(), key.overlappedAddress());
+                } catch (WindowsException expected) {
+                    // expected as I/O operation has been cancelled
+                }
             }
             CloseHandle(key.handle());
             closeAttachedEvent(key.overlappedAddress());
@@ -628,6 +643,7 @@
                     } catch (WindowsException x) {
                         // no choice but to cancel key
                         criticalError = true;
+                        key.setErrorStartingOverlapped(true);
                     }
                 }
                 if (criticalError) {
diff --git a/jdk/src/windows/classes/sun/security/mscapi/Key.java b/jdk/src/windows/classes/sun/security/mscapi/Key.java
index 0124ffb..8154c48 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/Key.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/Key.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,6 @@
 /**
  * The handle for an RSA or DSA key using the Microsoft Crypto API.
  *
- * @see DSAPrivateKey
  * @see RSAPrivateKey
  * @see RSAPublicKey
  *
@@ -41,9 +40,35 @@
 {
     private static final long serialVersionUID = -1088859394025049194L;
 
-    // Native handle
-    protected long hCryptProv = 0;
-    protected long hCryptKey = 0;
+    static class NativeHandles {
+        long hCryptProv = 0;
+        long hCryptKey = 0;
+
+        public NativeHandles(long hCryptProv, long hCryptKey) {
+            this.hCryptProv = hCryptProv;
+            this.hCryptKey = hCryptKey;
+        }
+
+        /**
+         * Finalization method
+         */
+        protected void finalize() throws Throwable
+        {
+            try {
+                synchronized(this)
+                {
+                    cleanUp(hCryptProv, hCryptKey);
+                    hCryptProv = 0;
+                    hCryptKey = 0;
+                }
+
+            } finally {
+                super.finalize();
+            }
+        }
+    }
+
+    protected NativeHandles handles;
 
     // Key length
     protected int keyLength = 0;
@@ -51,32 +76,13 @@
     /**
      * Construct a Key object.
      */
-    protected Key(long hCryptProv, long hCryptKey, int keyLength)
+    protected Key(NativeHandles handles, int keyLength)
     {
-        this.hCryptProv = hCryptProv;
-        this.hCryptKey = hCryptKey;
+        this.handles = handles;
         this.keyLength = keyLength;
     }
 
     /**
-     * Finalization method
-     */
-    protected void finalize() throws Throwable
-    {
-        try {
-            synchronized(this)
-            {
-                cleanUp(hCryptProv, hCryptKey);
-                hCryptProv = 0;
-                hCryptKey = 0;
-            }
-
-        } finally {
-            super.finalize();
-        }
-    }
-
-    /**
      * Native method to cleanup the key handle.
      */
     private native static void cleanUp(long hCryptProv, long hCryptKey);
@@ -96,7 +102,7 @@
      */
     public long getHCryptKey()
     {
-        return hCryptKey;
+        return handles.hCryptKey;
     }
 
     /**
@@ -104,12 +110,12 @@
      */
     public long getHCryptProvider()
     {
-        return hCryptProv;
+        return handles.hCryptProv;
     }
 
     /**
      * Returns the standard algorithm name for this key. For
-     * example, "DSA" would indicate that this key is a DSA key.
+     * example, "RSA" would indicate that this key is a RSA key.
      * See Appendix A in the <a href=
      * "../../../guide/security/CryptoSpec.html#AppA">
      * Java Cryptography Architecture API Specification &amp; Reference </a>
diff --git a/jdk/src/windows/classes/sun/security/mscapi/KeyStore.java b/jdk/src/windows/classes/sun/security/mscapi/KeyStore.java
index cbf4240..075ac78 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/KeyStore.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/KeyStore.java
@@ -169,7 +169,7 @@
             }
             certChain = chain;
         }
-    };
+    }
 
     /*
      * An X.509 certificate factory.
@@ -800,7 +800,8 @@
             }
 
             storeWithUniqueAlias(alias, new KeyEntry(alias,
-                    new RSAPrivateKey(hCryptProv, hCryptKey, keyLength),
+                    new RSAPrivateKey(new Key.NativeHandles(hCryptProv,
+                            hCryptKey), keyLength),
                     certChain));
         }
         catch (Throwable e)
@@ -856,7 +857,6 @@
      * Load keys and/or certificates from keystore into Collection.
      *
      * @param name Name of keystore.
-     * @param entries Collection of key/certificate.
      */
     private native void loadKeysOrCertificateChains(String name)
             throws KeyStoreException;
diff --git a/jdk/src/windows/classes/sun/security/mscapi/RSAKeyPair.java b/jdk/src/windows/classes/sun/security/mscapi/RSAKeyPair.java
index 6fba2a2..0880c20 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/RSAKeyPair.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/RSAKeyPair.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,8 +41,9 @@
      */
     RSAKeyPair(long hCryptProv, long hCryptKey, int keyLength)
     {
-        privateKey = new RSAPrivateKey(hCryptProv, hCryptKey, keyLength);
-        publicKey = new RSAPublicKey(hCryptProv, hCryptKey, keyLength);
+        Key.NativeHandles handles = new Key.NativeHandles(hCryptProv, hCryptKey);
+        privateKey = new RSAPrivateKey(handles, keyLength);
+        publicKey = new RSAPublicKey(handles, keyLength);
     }
 
     public RSAPrivateKey getPrivate() {
diff --git a/jdk/src/windows/classes/sun/security/mscapi/RSAPrivateKey.java b/jdk/src/windows/classes/sun/security/mscapi/RSAPrivateKey.java
index bc530f5..ca692df 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/RSAPrivateKey.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/RSAPrivateKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,15 @@
      */
     RSAPrivateKey(long hCryptProv, long hCryptKey, int keyLength)
     {
-        super(hCryptProv, hCryptKey, keyLength);
+        super(new NativeHandles(hCryptProv, hCryptKey), keyLength);
+    }
+
+    /**
+     * Construct an RSAPrivateKey object.
+     */
+    RSAPrivateKey(NativeHandles handles, int keyLength)
+    {
+        super(handles, keyLength);
     }
 
     /**
@@ -63,8 +71,8 @@
     public String toString()
     {
         return "RSAPrivateKey [size=" + keyLength + " bits, type=" +
-            getKeyType(hCryptKey) + ", container=" +
-            getContainerName(hCryptProv) + "]";
+            getKeyType(handles.hCryptKey) + ", container=" +
+            getContainerName(handles.hCryptProv) + "]";
     }
 
     // This class is not serializable
diff --git a/jdk/src/windows/classes/sun/security/mscapi/RSAPublicKey.java b/jdk/src/windows/classes/sun/security/mscapi/RSAPublicKey.java
index a62d783..52081ab 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/RSAPublicKey.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/RSAPublicKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,7 +51,15 @@
      */
     RSAPublicKey(long hCryptProv, long hCryptKey, int keyLength)
     {
-        super(hCryptProv, hCryptKey, keyLength);
+        super(new NativeHandles(hCryptProv, hCryptKey), keyLength);
+    }
+
+    /**
+     * Construct an RSAPublicKey object.
+     */
+    RSAPublicKey(NativeHandles handles, int keyLength)
+    {
+        super(handles, keyLength);
     }
 
     /**
@@ -77,8 +85,8 @@
         StringBuffer sb = new StringBuffer();
 
         sb.append("RSAPublicKey [size=").append(keyLength)
-            .append(" bits, type=").append(getKeyType(hCryptKey))
-            .append(", container=").append(getContainerName(hCryptProv))
+            .append(" bits, type=").append(getKeyType(handles.hCryptKey))
+            .append(", container=").append(getContainerName(handles.hCryptProv))
             .append("]\n  modulus: ").append(getModulus())
             .append("\n  public exponent: ").append(getPublicExponent());
 
@@ -93,7 +101,7 @@
         if (exponent == null) {
 
             try {
-                publicKeyBlob = getPublicKeyBlob(hCryptKey);
+                publicKeyBlob = getPublicKeyBlob(handles.hCryptKey);
                 exponent = new BigInteger(1, getExponent(publicKeyBlob));
 
             } catch (KeyException e) {
@@ -112,7 +120,7 @@
         if (modulus == null) {
 
             try {
-                publicKeyBlob = getPublicKeyBlob(hCryptKey);
+                publicKeyBlob = getPublicKeyBlob(handles.hCryptKey);
                 modulus = new BigInteger(1, getModulus(publicKeyBlob));
 
             } catch (KeyException e) {
diff --git a/jdk/src/windows/native/com/sun/security/auth/module/nt.c b/jdk/src/windows/native/com/sun/security/auth/module/nt.c
index 64ef356..038ceb1 100644
--- a/jdk/src/windows/native/com/sun/security/auth/module/nt.c
+++ b/jdk/src/windows/native/com/sun/security/auth/module/nt.c
@@ -43,6 +43,12 @@
 BOOL getTextualSid(PSID pSid, LPTSTR TextualSid, LPDWORD lpdwBufferLen);
 void DisplayErrorText(DWORD dwLastError);
 
+static void throwIllegalArgumentException(JNIEnv *env, const char *msg) {
+    jclass clazz = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+    if (clazz != NULL)
+        (*env)->ThrowNew(env, clazz, msg);
+}
+
 JNIEXPORT jlong JNICALL
 Java_com_sun_security_auth_module_NTSystem_getImpersonationToken0
         (JNIEnv *env, jobject obj) {
@@ -62,7 +68,6 @@
 
     long i, j = 0;
     HANDLE tokenHandle = INVALID_HANDLE_VALUE;
-    BOOL systemError = FALSE;
 
     LPTSTR userName = NULL;             // user name
     LPTSTR userSid = NULL;              // user sid
@@ -116,70 +121,59 @@
 
     fid = (*env)->GetFieldID(env, cls, "userName", "Ljava/lang/String;");
     if (fid == 0) {
-        jclass newExcCls =
-            (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-        if (newExcCls == 0) {
-            // Unable to find exception class
-            systemError = TRUE;
-            goto out;
-        }
-        (*env)->ThrowNew(env, newExcCls, "invalid field: userName");
+        (*env)->ExceptionClear(env);
+        throwIllegalArgumentException(env, "invalid field: userName");
+        goto cleanup;
     }
     jstr = (*env)->NewStringUTF(env, userName);
+    if (jstr == NULL)
+        goto cleanup;
     (*env)->SetObjectField(env, obj, fid, jstr);
 
     fid = (*env)->GetFieldID(env, cls, "userSID", "Ljava/lang/String;");
     if (fid == 0) {
-        jclass newExcCls =
-            (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-        if (newExcCls == 0) {
-            systemError = TRUE;
-            goto out;
-        }
-        (*env)->ThrowNew(env, newExcCls, "invalid field: userSID");
+        (*env)->ExceptionClear(env);
+        throwIllegalArgumentException(env, "invalid field: userSID");
+        goto cleanup;
     }
     jstr = (*env)->NewStringUTF(env, userSid);
+    if (jstr == NULL)
+        goto cleanup;
     (*env)->SetObjectField(env, obj, fid, jstr);
 
     fid = (*env)->GetFieldID(env, cls, "domain", "Ljava/lang/String;");
     if (fid == 0) {
-        jclass newExcCls =
-            (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-        if (newExcCls == 0) {
-            systemError = TRUE;
-            goto out;
-        }
-        (*env)->ThrowNew(env, newExcCls, "invalid field: domain");
+        (*env)->ExceptionClear(env);
+        throwIllegalArgumentException(env, "invalid field: domain");
+        goto cleanup;
     }
     jstr = (*env)->NewStringUTF(env, domainName);
+    if (jstr == NULL)
+        goto cleanup;
     (*env)->SetObjectField(env, obj, fid, jstr);
 
     if (domainSid != NULL) {
         fid = (*env)->GetFieldID(env, cls, "domainSID", "Ljava/lang/String;");
         if (fid == 0) {
-            jclass newExcCls =
-                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-            if (newExcCls == 0) {
-                systemError = TRUE;
-                goto out;
-            }
-            (*env)->ThrowNew(env, newExcCls, "invalid field: domainSID");
+            (*env)->ExceptionClear(env);
+            throwIllegalArgumentException(env, "invalid field: domainSID");
+            goto cleanup;
         }
         jstr = (*env)->NewStringUTF(env, domainSid);
+        if (jstr == NULL)
+            goto cleanup;
         (*env)->SetObjectField(env, obj, fid, jstr);
     }
 
     fid = (*env)->GetFieldID(env, cls, "primaryGroupID", "Ljava/lang/String;");
     if (fid == 0) {
-        jclass newExcCls =
-            (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-        if (newExcCls == 0) {
-            systemError = TRUE;
-            goto out;
-        }
-        (*env)->ThrowNew(env, newExcCls, "invalid field: PrimaryGroupID");
+        (*env)->ExceptionClear(env);
+        throwIllegalArgumentException(env, "invalid field: PrimaryGroupID");
+        goto cleanup;
     }
     jstr = (*env)->NewStringUTF(env, primaryGroup);
+    if (jstr == NULL)
+        goto cleanup;
     (*env)->SetObjectField(env, obj, fid, jstr);
 
     // primary group may or may not be part of supplementary groups
@@ -204,19 +198,14 @@
 
         fid = (*env)->GetFieldID(env, cls, "groupIDs", "[Ljava/lang/String;");
         if (fid == 0) {
-            jclass newExcCls =
-                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-            if (newExcCls == 0) {
-                systemError = TRUE;
-                goto out;
-            }
-            (*env)->ThrowNew(env, newExcCls, "invalid field: groupIDs");
+            (*env)->ExceptionClear(env);
+            throwIllegalArgumentException(env, "groupIDs");
+            goto cleanup;
         }
 
         stringClass = (*env)->FindClass(env, "java/lang/String");
-        if (stringClass == 0) {
-            goto out;
-        }
+        if (stringClass == NULL)
+            goto cleanup;
 
         if (pIndex == -1) {
             // primary group not in groups array
@@ -226,6 +215,8 @@
             // allocate one less array entry and do not add into new array
             jgroups = (*env)->NewObjectArray(env, numGroups-1, stringClass, 0);
         }
+        if (jgroups == NULL)
+            goto cleanup;
 
         for (i = 0, j = 0; i < (long)numGroups; i++) {
             if (pIndex == i) {
@@ -233,12 +224,14 @@
                 continue;
             }
             jstr = (*env)->NewStringUTF(env, groups[i]);
+            if (jstr == NULL)
+                goto cleanup;
             (*env)->SetObjectArrayElement(env, jgroups, j++, jstr);
         }
         (*env)->SetObjectField(env, obj, fid, jgroups);
     }
 
-out:
+cleanup:
     if (userName != NULL) {
         HeapFree(GetProcessHeap(), 0, userName);
     }
@@ -264,11 +257,6 @@
     }
     CloseHandle(tokenHandle);
 
-    if (systemError && debug) {
-        printf("  [getCurrent] System Error: ");
-        printf("unable to find IllegalArgumentException class\n");
-    }
-
     return;
 }
 
@@ -336,7 +324,7 @@
             DisplayErrorText(GetLastError());
         }
         error = TRUE;
-        goto out;
+        goto cleanup;
     }
 
     if (debug) {
@@ -369,7 +357,7 @@
             DisplayErrorText(GetLastError());
         }
         error = TRUE;
-        goto out;
+        goto cleanup;
     }
 
     if (debug) {
@@ -411,7 +399,7 @@
             DisplayErrorText(GetLastError());
         }
         // ok not to have a domain SID (no error)
-        goto out;
+        goto cleanup;
     }
 
     bufSize = 0;
@@ -422,7 +410,7 @@
         printf("  [getUser] domainSid: %s\n", *domainSid);
     }
 
-out:
+cleanup:
     if (tokenUserInfo != NULL) {
         HeapFree(GetProcessHeap(), 0, tokenUserInfo);
     }
@@ -466,7 +454,7 @@
             DisplayErrorText(GetLastError());
         }
         error = TRUE;
-        goto out;
+        goto cleanup;
     }
 
     if (debug) {
@@ -481,7 +469,7 @@
         printf("  [getPrimaryGroup] primaryGroup: %s\n", *primaryGroup);
     }
 
-out:
+cleanup:
     if (tokenGroupInfo != NULL) {
         HeapFree(GetProcessHeap(), 0, tokenGroupInfo);
     }
@@ -519,7 +507,7 @@
             DisplayErrorText(GetLastError());
         }
         error = TRUE;
-        goto out;
+        goto cleanup;
     }
 
     if (debug) {
@@ -528,7 +516,7 @@
 
     if (tokenGroupInfo->GroupCount == 0) {
         // no groups
-        goto out;
+        goto cleanup;
     }
 
     // return group info
@@ -545,7 +533,7 @@
         }
     }
 
-out:
+cleanup:
     if (tokenGroupInfo != NULL) {
         HeapFree(GetProcessHeap(), 0, tokenGroupInfo);
     }
diff --git a/jdk/src/windows/native/java/lang/java_props_md.c b/jdk/src/windows/native/java/lang/java_props_md.c
index e3387b6..224f290 100644
--- a/jdk/src/windows/native/java/lang/java_props_md.c
+++ b/jdk/src/windows/native/java/lang/java_props_md.c
@@ -188,6 +188,7 @@
         free(elems[index]);
     }
     } else {
+        free(ret);
         ret = NULL;
     }
 
diff --git a/jdk/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c b/jdk/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c
index 23d7ce2..67c62a3 100644
--- a/jdk/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c
+++ b/jdk/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c
@@ -41,7 +41,7 @@
     char buf[1];
     fd_set tbl;
     struct timeval t = { 0, 0 };
-    struct sockaddr_in rmtaddr;
+    SOCKETADDRESS rmtaddr;
     int addrlen = sizeof(rmtaddr);
 
     /*
@@ -87,6 +87,8 @@
     IO_fd_fdID = NET_GetFileDescriptorID(env);
     CHECK_NULL(IO_fd_fdID);
     JNU_CHECK_EXCEPTION(env);
+
+    initInetAddressIDs(env);
 }
 
 /*
diff --git a/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c b/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c
index 604ea9f..6d4905d 100644
--- a/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c
+++ b/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c
@@ -47,6 +47,8 @@
     isa_class = (*env)->NewGlobalRef(env, cls);
     isa_ctorID = (*env)->GetMethodID(env, cls, "<init>",
                                      "(Ljava/net/InetAddress;I)V");
+    CHECK_NULL(isa_ctorID);
+    initInetAddressIDs(env);
 
     // implement read timeout with select.
     isRcvTimeoutSupported = 0;
diff --git a/jdk/src/windows/native/java/net/Inet4AddressImpl.c b/jdk/src/windows/native/java/net/Inet4AddressImpl.c
index bfecffc..9e7097e 100644
--- a/jdk/src/windows/native/java/net/Inet4AddressImpl.c
+++ b/jdk/src/windows/native/java/net/Inet4AddressImpl.c
@@ -114,11 +114,6 @@
     return JNU_NewStringPlatform(env, hostname);
 }
 
-static jclass ni_iacls;
-static jclass ni_ia4cls;
-static jmethodID ni_ia4ctrID;
-static int initialized = 0;
-
 /*
  * Find an internet address for a given hostname.  Not this this
  * code only works for addresses of type INET. The translation
@@ -143,19 +138,8 @@
 
     jobjectArray ret = NULL;
 
-    if (!initialized) {
-      ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
-      CHECK_NULL_RETURN(ni_iacls, NULL);
-      ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
-      CHECK_NULL_RETURN(ni_iacls, NULL);
-      ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
-      CHECK_NULL_RETURN(ni_ia4cls, NULL);
-      ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
-      CHECK_NULL_RETURN(ni_ia4cls, NULL);
-      ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
-      CHECK_NULL_RETURN(ni_ia4ctrID, NULL);
-      initialized = 1;
-    }
+    initInetAddressIDs(env);
+    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host argument");
@@ -199,13 +183,13 @@
         address |= (addr[1]<<8) & 0xff00;
         address |= addr[0];
 
-        ret = (*env)->NewObjectArray(env, 1, ni_iacls, NULL);
+        ret = (*env)->NewObjectArray(env, 1, ia_class, NULL);
 
         if (IS_NULL(ret)) {
             goto cleanupAndReturn;
         }
 
-        iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+        iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
         if (IS_NULL(iaObj)) {
           ret = NULL;
           goto cleanupAndReturn;
@@ -229,7 +213,7 @@
             addrp++;
         }
 
-        ret = (*env)->NewObjectArray(env, i, ni_iacls, NULL);
+        ret = (*env)->NewObjectArray(env, i, ia_class, NULL);
 
         if (IS_NULL(ret)) {
             goto cleanupAndReturn;
@@ -238,7 +222,7 @@
         addrp = (struct in_addr **) hp->h_addr_list;
         i = 0;
         while (*addrp != (struct in_addr *) 0) {
-          jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+          jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
           if (IS_NULL(iaObj)) {
             ret = NULL;
             goto cleanupAndReturn;
@@ -538,6 +522,8 @@
             case ERROR_REQUEST_ABORTED:
             case ERROR_INCORRECT_ADDRESS:
             case ERROR_HOST_DOWN:
+            case ERROR_INVALID_COMPUTERNAME:
+            case ERROR_INVALID_NETNAME:
             case WSAEHOSTUNREACH:   /* Host Unreachable */
             case WSAENETUNREACH:    /* Network Unreachable */
             case WSAENETDOWN:       /* Network is down */
diff --git a/jdk/src/windows/native/java/net/Inet6AddressImpl.c b/jdk/src/windows/native/java/net/Inet6AddressImpl.c
index 2ab1ded..0ebd061 100644
--- a/jdk/src/windows/native/java/net/Inet6AddressImpl.c
+++ b/jdk/src/windows/native/java/net/Inet6AddressImpl.c
@@ -74,13 +74,6 @@
     return JNU_NewStringPlatform (env, hostname);
 }
 
-static jclass ni_iacls;
-static jclass ni_ia4cls;
-static jclass ni_ia6cls;
-static jmethodID ni_ia4ctrID;
-static jmethodID ni_ia6ctrID;
-static int initialized = 0;
-
 JNIEXPORT jobjectArray JNICALL
 Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
                                                 jstring host) {
@@ -88,30 +81,13 @@
     jobjectArray ret = 0;
     int retLen = 0;
     jboolean preferIPv6Address;
-    static jfieldID ia_preferIPv6AddressID;
 
     int error=0;
     struct addrinfo hints, *res, *resNew = NULL;
 
-    if (!initialized) {
-      ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
-      CHECK_NULL_RETURN(ni_iacls, NULL);
-      ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
-      CHECK_NULL_RETURN(ni_iacls, NULL);
-      ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
-      CHECK_NULL_RETURN(ni_ia4cls, NULL);
-      ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
-      CHECK_NULL_RETURN(ni_ia4cls, NULL);
-      ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
-      CHECK_NULL_RETURN(ni_ia6cls, NULL);
-      ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
-      CHECK_NULL_RETURN(ni_ia6cls, NULL);
-      ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
-      CHECK_NULL_RETURN(ni_ia4ctrID, NULL);
-      ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
-      CHECK_NULL_RETURN(ni_ia6ctrID, NULL);
-      initialized = 1;
-    }
+    initInetAddressIDs(env);
+    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host is null");
         return 0;
@@ -119,17 +95,6 @@
     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
     CHECK_NULL_RETURN(hostname, NULL);
 
-    if (ia_preferIPv6AddressID == NULL) {
-        jclass c = (*env)->FindClass(env,"java/net/InetAddress");
-        if (c)  {
-            ia_preferIPv6AddressID =
-                (*env)->GetStaticFieldID(env, c, "preferIPv6Address", "Z");
-        }
-        if (ia_preferIPv6AddressID == NULL) {
-            JNU_ReleaseStringPlatformChars(env, host, hostname);
-            return NULL;
-        }
-    }
     /* get the address preference */
     preferIPv6Address
         = (*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID);
@@ -231,7 +196,7 @@
         retLen = i;
         iterator = resNew;
         i = 0;
-        ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
+        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
 
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
@@ -248,7 +213,7 @@
 
         while (iterator != NULL) {
             if (iterator->ai_family == AF_INET) {
-              jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+              jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
               if (IS_NULL(iaObj)) {
                 ret = NULL;
                 goto cleanupAndReturn;
@@ -259,7 +224,7 @@
                 inetIndex ++;
             } else if (iterator->ai_family == AF_INET6) {
               jint scope = 0, ret1;
-              jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
+              jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
               if (IS_NULL(iaObj)) {
                 ret = NULL;
                 goto cleanupAndReturn;
@@ -349,6 +314,7 @@
 
     if (!error) {
         ret = (*env)->NewStringUTF(env, host);
+        CHECK_NULL_RETURN(ret, NULL);
     }
 
     if (ret == NULL) {
diff --git a/jdk/src/windows/native/java/net/NetworkInterface.c b/jdk/src/windows/native/java/net/NetworkInterface.c
index 6483f12..4dc22a0 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface.c
+++ b/jdk/src/windows/native/java/net/NetworkInterface.c
@@ -65,13 +65,6 @@
 jfieldID ni_nameID;         /* NetworkInterface.name */
 jfieldID ni_displayNameID;  /* NetworkInterface.displayName */
 jfieldID ni_childsID;       /* NetworkInterface.childs */
-jclass ni_iacls;            /* InetAddress */
-
-jclass ni_ia4cls;           /* Inet4Address */
-jmethodID ni_ia4Ctor;       /* Inet4Address() */
-
-jclass ni_ia6cls;           /* Inet6Address */
-jmethodID ni_ia6ctrID;      /* Inet6Address() */
 
 jclass ni_ibcls;            /* InterfaceAddress */
 jmethodID ni_ibctrID;       /* InterfaceAddress() */
@@ -515,26 +508,6 @@
     CHECK_NULL(ni_childsID);
     ni_ctor = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
     CHECK_NULL(ni_ctor);
-
-    ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
-    CHECK_NULL(ni_iacls);
-    ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
-    CHECK_NULL(ni_iacls);
-
-    ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
-    CHECK_NULL(ni_ia4cls);
-    ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
-    CHECK_NULL(ni_ia4cls);
-    ni_ia4Ctor = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
-    CHECK_NULL(ni_ia4Ctor);
-
-    ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
-    CHECK_NULL(ni_ia6cls);
-    ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
-    CHECK_NULL(ni_ia6cls);
-    ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
-    CHECK_NULL(ni_ia6ctrID);
-
     ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
     CHECK_NULL(ni_ibcls);
     ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
@@ -546,6 +519,9 @@
     ni_ibbroadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast", "Ljava/net/Inet4Address;");
     CHECK_NULL(ni_ibbroadcastID);
     ni_ibmaskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");
+    CHECK_NULL(ni_ibmaskID);
+
+    initInetAddressIDs(env);
 }
 
 /*
@@ -591,7 +567,7 @@
             return NULL;
         }
     }
-    addrArr = (*env)->NewObjectArray(env, netaddrCount, ni_iacls, NULL);
+    addrArr = (*env)->NewObjectArray(env, netaddrCount, ia_class, NULL);
     if (addrArr == NULL) {
         free_netaddr(netaddrP);
         return NULL;
@@ -609,7 +585,7 @@
         jobject iaObj, ia2Obj;
         jobject ibObj = NULL;
         if (addrs->addr.him.sa_family == AF_INET) {
-            iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
+            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (iaObj == NULL) {
                 free_netaddr(netaddrP);
                 return NULL;
@@ -624,7 +600,7 @@
                 return NULL;
               }
               (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
-              ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
+              ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
               if (ia2Obj == NULL) {
                 free_netaddr(netaddrP);
                 return NULL;
@@ -636,7 +612,7 @@
             }
         } else /* AF_INET6 */ {
             int scope;
-            iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
+            iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
             if (iaObj) {
                 int ret = setInet6Address_ipaddress(env, iaObj,  (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
                 if (ret == JNI_FALSE) {
diff --git a/jdk/src/windows/native/java/net/NetworkInterface.h b/jdk/src/windows/native/java/net/NetworkInterface.h
index fc40906..3bf4ed0 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface.h
+++ b/jdk/src/windows/native/java/net/NetworkInterface.h
@@ -70,16 +70,6 @@
 extern jfieldID ni_displayNameID;   /* NetworkInterface.displayName */
 extern jfieldID ni_childsID;        /* NetworkInterface.childs */
 
-extern jclass ni_iacls;             /* InetAddress */
-
-extern jclass ni_ia4cls;            /* Inet4Address */
-extern jmethodID ni_ia4Ctor;        /* Inet4Address() */
-
-extern jclass ni_ia6cls;            /* Inet6Address */
-extern jmethodID ni_ia6ctrID;       /* Inet6Address() */
-extern jfieldID ni_ia6ipaddressID;
-extern jfieldID ni_ia6ipaddressID;
-
 extern jclass ni_ibcls;             /* InterfaceAddress */
 extern jmethodID ni_ibctrID;        /* InterfaceAddress() */
 extern jfieldID ni_ibaddressID;     /* InterfaceAddress.address */
diff --git a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
index 4042d16..8003abc 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
+++ b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
@@ -489,14 +489,20 @@
      * Create a NetworkInterface object and populate it
      */
     netifObj = (*env)->NewObject(env, ni_class, ni_ctor);
+    if (netifObj == NULL) {
+        return NULL;
+    }
     name = (*env)->NewStringUTF(env, ifs->name);
+    if (name == NULL) {
+        return NULL;
+    }
     if (ifs->dNameIsUnicode) {
         displayName = (*env)->NewString(env, (PWCHAR)ifs->displayName,
                                         (jsize)wcslen ((PWCHAR)ifs->displayName));
     } else {
         displayName = (*env)->NewStringUTF(env, ifs->displayName);
     }
-    if (netifObj == NULL || name == NULL || displayName == NULL) {
+    if (displayName == NULL) {
         return NULL;
     }
     (*env)->SetObjectField(env, netifObj, ni_nameID, name);
@@ -513,7 +519,7 @@
         }
     }
 
-    addrArr = (*env)->NewObjectArray(env, netaddrCount, ni_iacls, NULL);
+    addrArr = (*env)->NewObjectArray(env, netaddrCount, ia_class, NULL);
     if (addrArr == NULL) {
         return NULL;
     }
@@ -531,7 +537,7 @@
         jobject iaObj, ia2Obj;
         jobject ibObj = NULL;
         if (addrs->addr.him.sa_family == AF_INET) {
-            iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
+            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (iaObj == NULL) {
                 return NULL;
             }
@@ -545,7 +551,7 @@
               return NULL;
             }
             (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
-            ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
+            ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (ia2Obj == NULL) {
               free_netaddr(netaddrP);
               return NULL;
@@ -556,26 +562,28 @@
             (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
         } else /* AF_INET6 */ {
             int scope;
-            iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
-            if (iaObj) {
-                int ret = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
-                if (ret == JNI_FALSE) {
-                    return NULL;
-                }
-                scope = addrs->addr.him6.sin6_scope_id;
-                if (scope != 0) { /* zero is default value, no need to set */
-                    setInet6Address_scopeid(env, iaObj, scope);
-                    setInet6Address_scopeifname(env, iaObj, netifObj);
-                }
-                ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
-                if (ibObj == NULL) {
-                  free_netaddr(netaddrP);
-                  return NULL;
-                }
-                (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
-                (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
-                (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
+            int ret;
+            iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
+            if (iaObj == NULL) {
+                return NULL;
             }
+            ret = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
+            if (ret == JNI_FALSE) {
+                return NULL;
+            }
+            scope = addrs->addr.him6.sin6_scope_id;
+            if (scope != 0) { /* zero is default value, no need to set */
+                setInet6Address_scopeid(env, iaObj, scope);
+                setInet6Address_scopeifname(env, iaObj, netifObj);
+            }
+            ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
+            if (ibObj == NULL) {
+              free_netaddr(netaddrP);
+              return NULL;
+            }
+            (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
+            (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
+            (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
         }
         (*env)->SetObjectArrayElement(env, addrArr, addr_index, iaObj);
         addrs = addrs->next;
diff --git a/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c b/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c
index 3b1994d..e7f1f58 100644
--- a/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c
@@ -332,7 +332,7 @@
     char buf[1];
     fd_set tbl;
     struct timeval t = { 0, 0 };
-    struct sockaddr_in rmtaddr;
+    SOCKETADDRESS rmtaddr;
     int addrlen = sizeof(rmtaddr);
 
     memset((char *)&rmtaddr, 0, sizeof(rmtaddr));
@@ -838,6 +838,7 @@
     }
     if (IS_NULL(addressObj)) {
         JNU_ThrowNullPointerException(env, "Null address in peek()");
+        return -1;
     } else {
         address = getInetAddress_addr(env, addressObj);
         /* We only handle IPv4 for now. Will support IPv6 once its in the os */
@@ -1150,11 +1151,23 @@
     }
     if (n == -1) {
         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "socket closed");
+        if (packetBufferLen > MAX_BUFFER_LEN) {
+            free(fullPacket);
+        }
+        return -1;
     } else if (n == -2) {
         JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException",
                         "operation interrupted");
+        if (packetBufferLen > MAX_BUFFER_LEN) {
+            free(fullPacket);
+        }
+        return -1;
     } else if (n < 0) {
         NET_ThrowCurrent(env, "Datagram receive failed");
+        if (packetBufferLen > MAX_BUFFER_LEN) {
+            free(fullPacket);
+        }
+        return -1;
     } else {
         jobject packetAddress;
 
@@ -1914,7 +1927,7 @@
         default :
             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
                 "Socket option not supported by PlainDatagramSocketImp");
-            break;
+            return;
 
     }
 
@@ -2357,6 +2370,7 @@
       if (NET_SetSockOpt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&ittl,
                          sizeof (ittl)) < 0) {
         NET_ThrowCurrent(env, "set IP_MULTICAST_TTL failed");
+        return;
       }
     }
 
@@ -2550,6 +2564,9 @@
         } else {
             ifindex = getIndexFromIf (env, niObj);
             if (ifindex == -1) {
+                if ((*env)->ExceptionOccurred(env)) {
+                    return;
+                }
                 NET_ThrowCurrent(env, "get ifindex failed");
                 return;
             }
diff --git a/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c b/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
index 899d5de..6e7ea71 100644
--- a/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
@@ -109,7 +109,7 @@
     psi_portID = (*env)->GetFieldID(env, cls, "port", "I");
     CHECK_NULL(psi_portID);
     psi_lastfdID = (*env)->GetFieldID(env, cls, "lastfd", "I");
-    CHECK_NULL(psi_portID);
+    CHECK_NULL(psi_lastfdID);
     psi_localportID = (*env)->GetFieldID(env, cls, "localport", "I");
     CHECK_NULL(psi_localportID);
     psi_timeoutID = (*env)->GetFieldID(env, cls, "timeout", "I");
@@ -154,17 +154,17 @@
         fd1Obj = (*env)->GetObjectField(env, this, psi_fd1ID);
 
         if (IS_NULL(fd1Obj)) {
-            JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
-                            "null fd1 object");
             (*env)->SetIntField(env, fdObj, IO_fd_fdID, -1);
             NET_SocketClose(fd);
+            JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
+                            "null fd1 object");
             return;
         }
         fd1 = socket(AF_INET6, (stream ? SOCK_STREAM: SOCK_DGRAM), 0);
         if (fd1 == -1) {
-            NET_ThrowCurrent(env, "create");
             (*env)->SetIntField(env, fdObj, IO_fd_fdID, -1);
             NET_SocketClose(fd);
+            NET_ThrowCurrent(env, "create");
             return;
         } else {
             /* Set socket attribute so it is not passed to any child process */
@@ -911,6 +911,7 @@
                     isRcvTimeoutSupported = JNI_FALSE;
                 } else {
                     NET_ThrowCurrent(env, "setsockopt SO_RCVTIMEO");
+                    return;
                 }
             }
             if (fd1 != -1) {
diff --git a/jdk/src/windows/native/java/nio/MappedByteBuffer.c b/jdk/src/windows/native/java/nio/MappedByteBuffer.c
index 4880123..05f5680 100644
--- a/jdk/src/windows/native/java/nio/MappedByteBuffer.c
+++ b/jdk/src/windows/native/java/nio/MappedByteBuffer.c
@@ -83,9 +83,9 @@
         HANDLE h;
         if (handle_fdID == NULL) {
             jclass clazz = (*env)->FindClass(env, "java/io/FileDescriptor");
-            if (clazz == NULL)
-                return; // exception thrown
+            CHECK_NULL(clazz); //exception thrown
             handle_fdID = (*env)->GetFieldID(env, clazz, "handle", "J");
+            CHECK_NULL(handle_fdID);
         }
         h = jlong_to_ptr((*env)->GetLongField(env, fdo, handle_fdID));
         result = FlushFileBuffers(h);
diff --git a/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp b/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp
index 1b5b71f..3e706c4 100644
--- a/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp
+++ b/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp
@@ -128,7 +128,7 @@
                 return;
             }
             hDC = comp->GetDCFromComponent();
-            if (hDC != NULL) {
+            if (hDC != NULL && wsdo->device != NULL) {
                 ::SelectObject(hDC, nullbrush);
                 ::SelectObject(hDC, nullpen);
                 ::SelectClipRgn(hDC, (HRGN) NULL);
diff --git a/jdk/src/windows/native/sun/nio/ch/IOUtil.c b/jdk/src/windows/native/sun/nio/ch/IOUtil.c
index 370dcf5..49de1eb 100644
--- a/jdk/src/windows/native/sun/nio/ch/IOUtil.c
+++ b/jdk/src/windows/native/sun/nio/ch/IOUtil.c
@@ -33,6 +33,7 @@
 
 #include "nio.h"
 #include "nio_util.h"
+#include "net_util.h"
 #include "sun_nio_ch_IOUtil.h"
 
 /* field id for jlong 'handle' in java.io.FileDescriptor used for file fds */
@@ -55,6 +56,7 @@
     CHECK_NULL(clazz = (*env)->FindClass(env, "java/io/FileDescriptor"));
     CHECK_NULL(fd_fdID = (*env)->GetFieldID(env, clazz, "fd", "I"));
     CHECK_NULL(handle_fdID = (*env)->GetFieldID(env, clazz, "handle", "J"));
+    initInetAddressIDs(env);
 }
 
 /**************************************************************
diff --git a/jdk/src/windows/native/sun/windows/awt_Component.cpp b/jdk/src/windows/native/sun/windows/awt_Component.cpp
index 57f85a5..44df115 100644
--- a/jdk/src/windows/native/sun/windows/awt_Component.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Component.cpp
@@ -260,6 +260,8 @@
         AwtComponent::BuildPrimaryDynamicTable();
         sm_PrimaryDynamicTableBuilt = TRUE;
     }
+
+    deadKeyActive = FALSE;
 }
 
 AwtComponent::~AwtComponent()
@@ -2937,6 +2939,7 @@
     {0x037A, java_awt_event_KeyEvent_VK_DEAD_IOTA},             // ASCII ???
     {0x309B, java_awt_event_KeyEvent_VK_DEAD_VOICED_SOUND},
     {0x309C, java_awt_event_KeyEvent_VK_DEAD_SEMIVOICED_SOUND},
+    {0x0004, java_awt_event_KeyEvent_VK_COMPOSE},
     {0,0}
 };
 
@@ -3429,8 +3432,9 @@
     AwtToolkit::GetKeyboardState(keyboardState);
 
     // apply modifiers to keyboard state if necessary
+    BOOL shiftIsDown = FALSE;
     if (modifiers) {
-        BOOL shiftIsDown = modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK;
+        shiftIsDown = modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK;
         BOOL altIsDown = modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK;
         BOOL ctrlIsDown = modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK;
 
@@ -3502,18 +3506,27 @@
         } // ctrlIsDown
     } // modifiers
 
-    // instead of creating our own conversion tables, I'll let Win32
-    // convert the character for me.
     WORD wChar[2];
-    UINT scancode = ::MapVirtualKey(wkey, 0);
-    int converted = ::ToUnicodeEx(wkey, scancode, keyboardState,
-                                  wChar, 2, 0, GetKeyboardLayout());
+    int converted = 1;
+    UINT ch = ::MapVirtualKeyEx(wkey, 2, GetKeyboardLayout());
+    if (ch & 0x80000000) {
+        // Dead key which is handled as a normal key
+        isDeadKey = deadKeyActive = TRUE;
+    } else if (deadKeyActive) {
+        // We cannot use ::ToUnicodeEx if dead key is active because this will
+        // break dead key function
+        wChar[0] = shiftIsDown ? ch : tolower(ch);
+    } else {
+        UINT scancode = ::MapVirtualKey(wkey, 0);
+        converted = ::ToUnicodeEx(wkey, scancode, keyboardState,
+                                              wChar, 2, 0, GetKeyboardLayout());
+    }
 
     UINT translation;
     BOOL deadKeyFlag = (converted == 2);
 
     // Dead Key
-    if (converted < 0) {
+    if (converted < 0 || isDeadKey) {
         translation = java_awt_event_KeyEvent_CHAR_UNDEFINED;
     } else
     // No translation available -- try known conversions or else punt.
@@ -3667,6 +3680,8 @@
 MsgRouting AwtComponent::WmChar(UINT character, UINT repCnt, UINT flags,
                                 BOOL system)
 {
+    deadKeyActive = FALSE;
+
     // Will only get WmChar messages with DBCS if we create them for
     // an Edit class in the WmForwardChar method. These synthesized
     // DBCS chars are ok to pass on directly to the default window
diff --git a/jdk/src/windows/native/sun/windows/awt_Component.h b/jdk/src/windows/native/sun/windows/awt_Component.h
index a9fd47b..1084699 100644
--- a/jdk/src/windows/native/sun/windows/awt_Component.h
+++ b/jdk/src/windows/native/sun/windows/awt_Component.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -821,6 +821,8 @@
     // 6524352: support finer-resolution
     int m_wheelRotationAmount;
 
+    BOOL deadKeyActive;
+
     /*
      * The association list of children's IDs and corresponding components.
      * Some components like Choice or List are required their sizes while
diff --git a/jdk/src/windows/native/sun/windows/awt_FileDialog.cpp b/jdk/src/windows/native/sun/windows/awt_FileDialog.cpp
index a9573e5..b5d7663 100644
--- a/jdk/src/windows/native/sun/windows/awt_FileDialog.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_FileDialog.cpp
@@ -349,9 +349,9 @@
 
         // show the Win32 file dialog
         if (mode == java_awt_FileDialog_LOAD) {
-            result = AwtFileDialog::GetOpenFileName(&ofn);
+            result = ::GetOpenFileName(&ofn);
         } else {
-            result = AwtFileDialog::GetSaveFileName(&ofn);
+            result = ::GetSaveFileName(&ofn);
         }
         // Fix for 4181310: FileDialog does not show up.
         // If the dialog is not shown because of invalid file name
@@ -361,9 +361,9 @@
             if (dlgerr == FNERR_INVALIDFILENAME) {
                 _tcscpy_s(fileBuffer, bufferLimit, TEXT(""));
                 if (mode == java_awt_FileDialog_LOAD) {
-                    result = AwtFileDialog::GetOpenFileName(&ofn);
+                    result = ::GetOpenFileName(&ofn);
                 } else {
-                    result = AwtFileDialog::GetSaveFileName(&ofn);
+                    result = ::GetSaveFileName(&ofn);
                 }
             }
         }
@@ -422,22 +422,6 @@
         delete[] ofn.lpstrFile;
 }
 
-BOOL
-AwtFileDialog::GetOpenFileName(LPOPENFILENAME data) {
-    return static_cast<BOOL>(reinterpret_cast<INT_PTR>(
-        AwtToolkit::GetInstance().InvokeFunction((void*(*)(void*))
-                     ::GetOpenFileName, data)));
-
-}
-
-BOOL
-AwtFileDialog::GetSaveFileName(LPOPENFILENAME data) {
-    return static_cast<BOOL>(reinterpret_cast<INT_PTR>(
-        AwtToolkit::GetInstance().InvokeFunction((void *(*)(void *))
-                     ::GetSaveFileName, data)));
-
-}
-
 BOOL AwtFileDialog::InheritsNativeMouseWheelBehavior() {return true;}
 
 void AwtFileDialog::_DisposeOrHide(void *param)
@@ -585,9 +569,10 @@
      */
     jobject peerGlobal = env->NewGlobalRef(peer);
 
-    AwtToolkit::GetInstance().InvokeFunction(AwtFileDialog::Show, peerGlobal);
-
-    env->DeleteGlobalRef(peerGlobal);
+    if (!AwtToolkit::GetInstance().PostMessage(WM_AWT_INVOKE_METHOD,
+                             (WPARAM)AwtFileDialog::Show, (LPARAM)peerGlobal)) {
+        env->DeleteGlobalRef(peerGlobal);
+    }
 
     CATCH_BAD_ALLOC;
 }
diff --git a/jdk/src/windows/native/sun/windows/awt_FileDialog.h b/jdk/src/windows/native/sun/windows/awt_FileDialog.h
index a71ba6a..8647e35 100644
--- a/jdk/src/windows/native/sun/windows/awt_FileDialog.h
+++ b/jdk/src/windows/native/sun/windows/awt_FileDialog.h
@@ -60,9 +60,6 @@
     static void Initialize(JNIEnv *env, jstring filterDescription);
     static void Show(void *peer);
 
-    static BOOL GetOpenFileName(LPOPENFILENAME);
-    static BOOL GetSaveFileName(LPOPENFILENAME);
-
     virtual BOOL InheritsNativeMouseWheelBehavior();
 
     // some methods called on Toolkit thread
diff --git a/jdk/src/windows/native/sun/windows/awt_Font.cpp b/jdk/src/windows/native/sun/windows/awt_Font.cpp
index 7c90849..56a0e8c 100644
--- a/jdk/src/windows/native/sun/windows/awt_Font.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Font.cpp
@@ -1662,6 +1662,8 @@
 
 CSegTableManager g_segTableManager;
 
+#define KEYLEN 16
+
 class CCombinedSegTable : public CSegTableComponent
 {
 public:
@@ -1672,7 +1674,7 @@
 private:
     LPSTR GetCodePageSubkey();
     void GetEUDCFileName(LPWSTR lpszFileName, int cchFileName);
-    static char m_szCodePageSubkey[16];
+    static char m_szCodePageSubkey[KEYLEN];
     static WCHAR m_szDefaultEUDCFile[_MAX_PATH];
     static BOOL m_fEUDCSubKeyExist;
     static BOOL m_fTTEUDCFileExist;
@@ -1680,7 +1682,7 @@
     CEUDCSegTable* m_pEUDCSegTable;
 };
 
-char CCombinedSegTable::m_szCodePageSubkey[16] = "";
+char CCombinedSegTable::m_szCodePageSubkey[KEYLEN] = "";
 
 WCHAR CCombinedSegTable::m_szDefaultEUDCFile[_MAX_PATH] = L"";
 
@@ -1712,8 +1714,11 @@
     }
     lpszCP++; // cf lpszCP = "932"
 
-    char szSubKey[80];
+    char szSubKey[KEYLEN];
     strcpy(szSubKey, "EUDC\\");
+    if ((strlen(szSubKey) + strlen(lpszCP)) >= KEYLEN) {
+        return NULL;
+    }
     strcpy(&(szSubKey[strlen(szSubKey)]), lpszCP);
     strcpy(m_szCodePageSubkey, szSubKey);
     return m_szCodePageSubkey;
diff --git a/jdk/src/windows/native/sun/windows/awt_Frame.cpp b/jdk/src/windows/native/sun/windows/awt_Frame.cpp
index 9385cb4..4982f97 100644
--- a/jdk/src/windows/native/sun/windows/awt_Frame.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Frame.cpp
@@ -484,7 +484,10 @@
             if (fgProcessID != ::GetCurrentProcessId()) {
                 AwtWindow* window = (AwtWindow*)GetComponent(GetHWnd());
 
-                if (window != NULL && window->IsFocusableWindow() && window->IsAutoRequestFocus() &&
+                if (window != NULL &&
+                    window->IsFocusableWindow() &&
+                    window->IsAutoRequestFocus() &&
+                    !::IsWindowVisible(GetHWnd()) && // the window is really showing
                     !::IsWindow(GetModalBlocker(GetHWnd())))
                 {
                     // When the Java process is not allowed to set the foreground window
diff --git a/jdk/src/windows/native/sun/windows/awt_PrintControl.cpp b/jdk/src/windows/native/sun/windows/awt_PrintControl.cpp
index d3d8b5d..0b228e8 100644
--- a/jdk/src/windows/native/sun/windows/awt_PrintControl.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_PrintControl.cpp
@@ -54,6 +54,7 @@
 jmethodID AwtPrintControl::setDevmodeID;
 jmethodID AwtPrintControl::getDevnamesID;
 jmethodID AwtPrintControl::setDevnamesID;
+jmethodID AwtPrintControl::getParentWindowID;
 jfieldID  AwtPrintControl::driverDoesMultipleCopiesID;
 jfieldID  AwtPrintControl::driverDoesCollationID;
 jmethodID AwtPrintControl::getWin32MediaID;
@@ -240,6 +241,11 @@
     DASSERT(AwtPrintControl::dialogOwnerPeerID != NULL);
     CHECK_NULL(AwtPrintControl::dialogOwnerPeerID);
 
+    AwtPrintControl::getParentWindowID = env->GetMethodID(cls,
+                                       "getParentWindowID", "()J");
+    DASSERT(AwtPrintControl::getParentWindowID != NULL);
+    CHECK_NULL(AwtPrintControl::getParentWindowID);
+
     AwtPrintControl::getPrintDCID = env->GetMethodID(cls, "getPrintDC", "()J");
     DASSERT(AwtPrintControl::getPrintDCID != NULL);
     CHECK_NULL(AwtPrintControl::getPrintDCID);
diff --git a/jdk/src/windows/native/sun/windows/awt_PrintControl.h b/jdk/src/windows/native/sun/windows/awt_PrintControl.h
index 5f66377..bc782c4 100644
--- a/jdk/src/windows/native/sun/windows/awt_PrintControl.h
+++ b/jdk/src/windows/native/sun/windows/awt_PrintControl.h
@@ -47,6 +47,7 @@
     static jmethodID setDevmodeID;
     static jmethodID getDevnamesID;
     static jmethodID setDevnamesID;
+    static jmethodID getParentWindowID;
     static jmethodID getWin32MediaID;
     static jmethodID setWin32MediaID;
     static jmethodID getWin32MediaTrayID;
@@ -97,6 +98,10 @@
                                  LPTSTR pPrinterName,
                                  LPDEVMODE *pDevMode);
 
+    inline static HWND getParentID(JNIEnv *env, jobject self) {
+      return (HWND)env->CallLongMethod(self, getParentWindowID);
+    }
+
     inline static  HDC getPrintDC(JNIEnv *env, jobject self) {
       return (HDC)env->CallLongMethod(self, getPrintDCID);
     }
diff --git a/jdk/src/windows/native/sun/windows/awt_PrintDialog.cpp b/jdk/src/windows/native/sun/windows/awt_PrintDialog.cpp
index 7a7e7a7..0669aa1 100644
--- a/jdk/src/windows/native/sun/windows/awt_PrintDialog.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_PrintDialog.cpp
@@ -248,6 +248,11 @@
       pd.lpfnPrintHook = (LPPRINTHOOKPROC)PrintDialogHookProc;
       pd.lpfnSetupHook = (LPSETUPHOOKPROC)PrintDialogHookProc;
       pd.Flags |= PD_ENABLESETUPHOOK | PD_ENABLEPRINTHOOK;
+      HWND parent = AwtPrintControl::getParentID(env, control);
+      if (parent != NULL && ::IsWindow(parent)) {
+          // Windows native modality is requested (used by JavaFX).
+          pd.hwndOwner = parent;
+      }
       /*
           Fix for 6488834.
           To disable Win32 native parent modality we have to set
@@ -255,7 +260,7 @@
           parentless dialogs we use NULL to show them in the taskbar,
           and for all other dialogs AwtToolkit's HWND is used.
       */
-      if (awtParent != NULL)
+      else if (awtParent != NULL)
       {
           pd.hwndOwner = AwtToolkit::GetInstance().GetHWnd();
       }
diff --git a/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp b/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp
index 6899b8d..7632f07 100644
--- a/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp
@@ -521,12 +521,18 @@
     AwtComponent *awtParent = (parent != NULL) ? (AwtComponent *)JNI_GET_PDATA(parent) : NULL;
     HWND hwndOwner = awtParent ? awtParent->GetHWnd() : NULL;
 
+
     jboolean doIt = JNI_FALSE; // Assume the user will cancel the dialog.
     PAGESETUPDLG setup;
     memset(&setup, 0, sizeof(setup));
 
     setup.lStructSize = sizeof(setup);
 
+    HWND parentID = AwtPrintControl::getParentID(env, self);
+    if (parentID != NULL && ::IsWindow(parentID)) {
+        // windows native modality is requested (used by JavaFX).
+        setup.hwndOwner = parentID;
+    }
     /*
       Fix for 6488834.
       To disable Win32 native parent modality we have to set
@@ -534,7 +540,7 @@
       parentless dialogs we use NULL to show them in the taskbar,
       and for all other dialogs AwtToolkit's HWND is used.
     */
-    if (awtParent != NULL)
+    else if (awtParent != NULL)
     {
         setup.hwndOwner = AwtToolkit::GetInstance().GetHWnd();
     }
diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt
index 2f9a8ce..b4f6849 100644
--- a/jdk/test/ProblemList.txt
+++ b/jdk/test/ProblemList.txt
@@ -1,6 +1,6 @@
 ###########################################################################
 #
-# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2009, 2017, 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
@@ -150,34 +150,49 @@
 # 7027502
 demo/jvmti/hprof/MonitorTest.java                               generic-all
 
-# 8027973
-javax/xml/jaxp/transform/jdk8004476/XSLTExFuncTest.java		windows-all
-
 ############################################################################
 
 # jdk_net
 
-# Filed 7052625
-com/sun/net/httpserver/bugs/6725892/Test.java                   generic-all
-
-# failing on vista 32/64 on nightly
-# 7102702
-java/net/PortUnreachableException/OneExceptionOnly.java         windows-all
-
-# 7148829
-sun/net/InetAddress/nameservice/simple/CacheTest.java		generic-all
-sun/net/InetAddress/nameservice/simple/DefaultCaching.java	generic-all
-
 # 7122846
 java/net/MulticastSocket/NoLoopbackPackets.java                  macosx-all
-java/net/MulticastSocket/SetLoopbackMode.java                    macosx-all
 
-# 7145658
-java/net/MulticastSocket/Test.java                               macosx-all
+# 7122846, 8098566
+java/net/MulticastSocket/SetLoopbackMode.java                    macosx-all,solaris-all
+
+# 8171217, 7145658
+java/net/MulticastSocket/Test.java                               macosx-all,solaris-all
 
 # 7143960
 java/net/DatagramSocket/SendDatagramToBadAddress.java            macosx-all
 
+# 8172046
+java/net/MulticastSocket/TestInterfaces.java                     windows-x64,solaris-x64
+
+# 8160738
+sun/net/www/protocol/https/HttpsURLConnection/ImpactOnSNI.java   macosx-x64
+
+# 8010379
+sun/net/www/http/KeepAliveCache/B5045306.java                    macosx-x64
+
+# 8158598
+sun/net/www/protocol/http/B6296310.java                          macosx-x64
+
+# 8171208
+java/net/CookieHandler/CookieManagerTest.java                    macosx-x64
+java/net/HttpURLConnection/UnmodifiableMaps.java                 macosx-x64
+sun/net/www/protocol/http/B6299712.java                          macosx-x64
+
+# 8166362
+sun/net/www/http/HttpClient/B8025710.java			generic-all
+
+############################################################################
+
+# jdk_io
+
+# 8169774
+java/io/File/WinSpecialFiles.java                               windows-all
+
 ############################################################################
 
 # jdk_nio
@@ -191,10 +206,30 @@
 # 7132677
 java/nio/channels/Selector/OutOfBand.java                       macosx-all
 
-# 7158947, Solaris 11
+# 7158947
 java/nio/file/WatchService/Basic.java				solaris-all
 java/nio/file/WatchService/LotsOfEvents.java			solaris-all
 
+# 8030179
+java/nio/Buffer/Chars.java                      windows-x64
+
+# 8172045
+java/nio/channels/AsyncCloseAndInterrupt.java           linux-all
+
+# 8076056
+java/nio/channels/DatagramChannel/BasicMulticastTests.java      linux-i586
+java/nio/channels/DatagramChannel/MulticastSendReceiveTests.java    linux-i586
+
+# 8148996
+java/nio/file/WatchService/WithSecurityManager.java     linux-i586
+
+# 8173179
+java/nio/file/Files/probeContentType/Basic.java                  solaris-x64
+
+# 8171218
+java/nio/file/FileStore/Basic.java              linux-i586
+java/nio/file/FileSystem/Basic.java                 linux-i586
+
 ############################################################################
 
 # jdk_rmi
@@ -211,28 +246,33 @@
 # 7195095
 sun/rmi/transport/proxy/EagerHttpFallback.java                  generic-all
 
+# 8049531
+java/rmi/reliability/benchmark/bench/serial/Main.java           linux-i586
+
+# 8162906
+javax/rmi/ssl/SSLSocketParametersTest.sh                    linux-all
+
+# 8137232
+javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java       linux-all
+
+# 8170248
+javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java  linux-all
+
 ############################################################################
 
 # jdk_security
 
-# 7157786
+# 8026976
 sun/security/pkcs11/ec/TestKeyFactory.java                      generic-all
 
-# 7164518: no PortUnreachableException on Mac
+# 7164518
 sun/security/krb5/auto/Unreachable.java                         macosx-all
 
 # 7147060
 com/sun/org/apache/xml/internal/security/transforms/ClassLoaderTest.java	generic-all
 
-# 6988842: 4 tests failing on Solaris 5.10
-sun/security/pkcs11/Secmod/AddPrivateKey.java                   solaris-all
-sun/security/pkcs11/ec/ReadCertificates.java                    solaris-all
-sun/security/pkcs11/ec/ReadPKCS12.java                          solaris-all
-sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java            solaris-all
-
-# 7041639, Solaris DSA keypair generation bug
-java/security/KeyPairGenerator/SolarisShortDSA.java             solaris-all
-sun/security/tools/keytool/standard.sh                          solaris-all
+# 8160071
+sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java            linux-all
 
 # 8026393
 sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java      generic-all
@@ -240,9 +280,26 @@
 # 8158827
 sun/security/krb5/auto/tools/KinitConfPlusProps.java                       windows-all
 
-# 8160071 ClientJSSEServerJSSE.java test failure
-sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java		linux-all
+# 8151225
+sun/security/rsa/SpecTest.java                                  linux-i586
 
+# 8173182
+sun/security/pkcs11/MessageDigest/TestCloning.java              solaris-x64
+
+# 8156709
+sun/security/provider/SecureRandom/StrongSecureRandom.java      macosx-x64
+
+# 8163498
+sun/security/provider/NSASuiteB/TestDSAGenParameterSpec.java    linux-i586
+
+# 8129560
+sun/security/pkcs11/rsa/TestKeyPairGenerator.java               solaris-all
+
+# 8151834
+sun/security/mscapi/SmallPrimeExponentP.java                    windows-i586
+
+#8176354 
+sun/security/ssl/com/sun/net/ssl/internal/ssl/X509KeyManager/PreferredKey.java     generic-all
 ############################################################################
 
 # jdk_sound
@@ -263,12 +320,8 @@
 
 # jdk_tools
 
-# Tests take too long, on sparcs see 7143279
-tools/pack200/CommandLineTests.java                             solaris-all, macosx-all
-tools/pack200/Pack200Test.java                                  solaris-all, macosx-all
-
-# 8007410
-tools/launcher/FXLauncherTest.java                              linux-all
+# 8172782, 8007410
+tools/launcher/FXLauncherTest.java                     windows-all,linux-all
 
 ############################################################################
 
@@ -278,8 +331,8 @@
 
 # jdk_util
 
-# Filed 6772009
-java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java generic-all
+# 8004807
+java/util/Timer/Args.java                                        generic-all
 
 ############################################################################
 
@@ -292,3 +345,10 @@
 sun/tools/jps/TestJpsJarRelative.java				generic-all
 
 ############################################################################
+
+# jdk_other
+
+############################################################################
+
+# 8141370
+com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java			linux-i586,macosx-all
diff --git a/jdk/test/com/apple/laf/ScreenMenu/ScreenMenuMemoryLeakTest.java b/jdk/test/com/apple/laf/ScreenMenu/ScreenMenuMemoryLeakTest.java
new file mode 100644
index 0000000..8aabcae
--- /dev/null
+++ b/jdk/test/com/apple/laf/ScreenMenu/ScreenMenuMemoryLeakTest.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8158325
+ * @summary Memory leak in com.apple.laf.ScreenMenu: removed JMenuItems are still referenced
+ * @requires (os.family == "mac")
+ * @run main/timeout=300/othervm -Xmx16m ScreenMenuMemoryLeakTest
+ */
+import java.awt.EventQueue;
+import java.lang.ref.WeakReference;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Objects;
+
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+import javax.swing.JMenuItem;
+import javax.swing.WindowConstants;
+
+public class ScreenMenuMemoryLeakTest {
+
+    private static byte[] sBytes;
+
+    private static WeakReference<JMenuItem> sMenuItem;
+    private static JFrame sFrame;
+    private static JMenu sMenu;
+
+    public static void main(String[] args) throws InvocationTargetException, InterruptedException {
+        EventQueue.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                System.setProperty("apple.laf.useScreenMenuBar", "true");
+                showUI();
+            }
+        });
+
+        EventQueue.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                removeMenuItemFromMenu();
+            }
+        });
+        System.gc();
+        System.runFinalization();
+        JMenuItem menuItem = sMenuItem.get();
+        EventQueue.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                sFrame.dispose();
+            }
+        });
+        if (menuItem != null) {
+            throw new RuntimeException("The menu item should have been GC-ed");
+        }
+    }
+
+    private static void showUI() {
+        sFrame = new JFrame();
+        sFrame.add(new JLabel("Some dummy content"));
+
+        JMenuBar menuBar = new JMenuBar();
+
+        sMenu = new JMenu("Menu");
+        JMenuItem item = new JMenuItem("Item");
+        sMenu.add(item);
+
+        sMenuItem = new WeakReference<>(item);
+
+        menuBar.add(sMenu);
+
+        sFrame.setJMenuBar(menuBar);
+
+        sFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
+        sFrame.pack();
+        sFrame.setVisible(true);
+    }
+
+    private static void removeMenuItemFromMenu() {
+        JMenuItem menuItem = sMenuItem.get();
+        Objects.requireNonNull(menuItem, "The menu item should still be available at this point");
+        sMenu.remove(menuItem);
+    }
+}
\ No newline at end of file
diff --git a/jdk/test/com/sun/jdi/EvalArraysAsList.sh b/jdk/test/com/sun/jdi/EvalArraysAsList.sh
new file mode 100644
index 0000000..fa5cd93
--- /dev/null
+++ b/jdk/test/com/sun/jdi/EvalArraysAsList.sh
@@ -0,0 +1,85 @@
+#!/bin/sh
+#
+# Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+#  @test
+#  @bug 8160024
+#  @summary jdb returns invalid argument count if first parameter to Arrays.asList is null
+#
+#  @run shell/timeout=300 EvalArraysAsList.sh
+#
+#  The test checks if evaluation of the expression java.util.Arrays.asList(null, "a")
+#  works normally and does not throw an IllegalArgumentException.
+
+classname=EvalArraysAsList
+
+createJavaFile()
+{
+    cat <<EOF > $classname.java.1
+public class $classname {
+    public static void main(String[] args) {
+        java.util.List<Object> l = java.util.Arrays.asList(null, "a");
+        System.out.println("java.util.Arrays.asList(null, \"a\") returns: " + l);
+        return;    // @1 breakpoint
+    }
+}
+EOF
+}
+
+# drive jdb by sending cmds to it and examining its output
+dojdbCmds()
+{
+    setBkpts @1
+    runToBkpt @1
+
+    cmd eval "java.util.Arrays.asList(null, null)"
+    jdbFailIfPresent "IllegalArgumentException" 3
+
+    cmd eval "java.util.Arrays.asList(null, \"a\")"
+    jdbFailIfPresent "IllegalArgumentException" 3
+
+    cmd eval "java.util.Arrays.asList(\"a\", null)"
+    jdbFailIfPresent "IllegalArgumentException" 3
+}
+
+
+mysetup()
+{
+    if [ -z "$TESTSRC" ] ; then
+        TESTSRC=.
+    fi
+
+    for ii in . $TESTSRC $TESTSRC/.. ; do
+        if [ -r "$ii/ShellScaffold.sh" ] ; then
+            . $ii/ShellScaffold.sh
+            break
+        fi
+    done
+}
+
+# You could replace this next line with the contents
+# of ShellScaffold.sh and this script will run just the same.
+mysetup
+
+runit
+pass
diff --git a/jdk/test/com/sun/jdi/oom/@debuggeeVMOptions b/jdk/test/com/sun/jdi/oom/@debuggeeVMOptions
new file mode 100644
index 0000000..6f219bc
--- /dev/null
+++ b/jdk/test/com/sun/jdi/oom/@debuggeeVMOptions
@@ -0,0 +1 @@
+-Xmx40m
\ No newline at end of file
diff --git a/jdk/test/com/sun/jdi/oom/OomDebugTest.java b/jdk/test/com/sun/jdi/oom/OomDebugTest.java
new file mode 100644
index 0000000..6bd546b
--- /dev/null
+++ b/jdk/test/com/sun/jdi/oom/OomDebugTest.java
@@ -0,0 +1,417 @@
+/*
+ * Copyright (c) 2016 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.
+ */
+
+/**
+ *  @test
+ *  @bug 8153711
+ *  @summary JDWP: Memory Leak (global references not deleted after invokeMethod).
+ *
+ *  @author Severin Gehwolf <sgehwolf@redhat.com>
+ *
+ *  @library ..
+ *  @run build TestScaffold VMConnection TargetListener TargetAdapter
+ *  @run compile -g OomDebugTest.java
+ *  @run shell OomDebugTestSetup.sh
+ *  @run main OomDebugTest OomDebugTestTarget test1
+ *  @run main OomDebugTest OomDebugTestTarget test2
+ *  @run main OomDebugTest OomDebugTestTarget test3
+ *  @run main OomDebugTest OomDebugTestTarget test4
+ *  @run main OomDebugTest OomDebugTestTarget test5
+ */
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import com.sun.jdi.ArrayReference;
+import com.sun.jdi.ArrayType;
+import com.sun.jdi.ClassType;
+import com.sun.jdi.Field;
+import com.sun.jdi.InvocationException;
+import com.sun.jdi.Method;
+import com.sun.jdi.ObjectReference;
+import com.sun.jdi.ReferenceType;
+import com.sun.jdi.StackFrame;
+import com.sun.jdi.VMOutOfMemoryException;
+import com.sun.jdi.Value;
+import com.sun.jdi.event.BreakpointEvent;
+import com.sun.jdi.event.ExceptionEvent;
+
+/***************** Target program **********************/
+
+class OomDebugTestTarget {
+
+    OomDebugTestTarget() {
+        System.out.println("DEBUG: invoked constructor");
+    }
+    static class FooCls {
+        @SuppressWarnings("unused")
+        private byte[] bytes = new byte[3000000];
+    };
+
+    FooCls fooCls = new FooCls();
+    byte[] byteArray = new byte[0];
+
+    void testMethod(FooCls foo) {
+        System.out.println("DEBUG: invoked 'void testMethod(FooCls)', foo == " + foo);
+    }
+
+    void testPrimitive(byte[] foo) {
+        System.out.println("DEBUG: invoked 'void testPrimitive(byte[])', foo == " + foo);
+    }
+
+    byte[] testPrimitiveArrRetval() {
+        System.out.println("DEBUG: invoked 'byte[] testPrimitiveArrRetval()'");
+        return new byte[3000000];
+    }
+
+    FooCls testFooClsRetval() {
+        System.out.println("DEBUG: invoked 'FooCls testFooClsRetval()'");
+        return new FooCls();
+    }
+
+    public void entry() {}
+
+    public static void main(String[] args){
+        System.out.println("DEBUG: OomDebugTestTarget.main");
+        new OomDebugTestTarget().entry();
+    }
+}
+
+/***************** Test program ************************/
+
+public class OomDebugTest extends TestScaffold {
+
+    private static final String[] ALL_TESTS = new String[] {
+            "test1", "test2", "test3", "test4", "test5"
+    };
+    private static final Set<String> ALL_TESTS_SET = new HashSet<String>();
+    static {
+        ALL_TESTS_SET.addAll(Arrays.asList(ALL_TESTS));
+    }
+    private static final String TEST_CLASSES = System.getProperty("test.classes", ".");
+    private static final File RESULT_FILE = new File(TEST_CLASSES, "results.properties");
+    private static final String LAST_TEST = ALL_TESTS[ALL_TESTS.length - 1];
+    private ReferenceType targetClass;
+    private ObjectReference thisObject;
+    private int failedTests;
+    private final String testMethod;
+
+    public OomDebugTest(String[] args) {
+        super(args);
+        if (args.length != 2) {
+            throw new RuntimeException("Test failed unexpectedly.");
+        }
+        this.testMethod = args[1];
+    }
+
+    @Override
+    protected void runTests() throws Exception {
+        try {
+            addListener(new TargetAdapter() {
+
+                @Override
+                public void exceptionThrown(ExceptionEvent event) {
+                    String name = event.exception().referenceType().name();
+                    System.err.println("DEBUG: Exception thrown in debuggee was: " + name);
+                }
+            });
+            /*
+             * Get to the top of entry()
+             * to determine targetClass and mainThread
+             */
+            BreakpointEvent bpe = startTo("OomDebugTestTarget", "entry", "()V");
+            targetClass = bpe.location().declaringType();
+
+            mainThread = bpe.thread();
+
+            StackFrame frame = mainThread.frame(0);
+            thisObject = frame.thisObject();
+            java.lang.reflect.Method m = findTestMethod();
+            m.invoke(this);
+        } catch (NoSuchMethodException e) {
+            e.printStackTrace();
+            failure();
+        } catch (SecurityException e) {
+            e.printStackTrace();
+            failure();
+        }
+        /*
+         * resume the target, listening for events
+         */
+        listenUntilVMDisconnect();
+    }
+
+    private java.lang.reflect.Method findTestMethod()
+            throws NoSuchMethodException, SecurityException {
+        return OomDebugTest.class.getDeclaredMethod(testMethod);
+    }
+
+    private void failure() {
+        failedTests++;
+    }
+
+    /*
+     * Test case: Object reference as method parameter.
+     */
+    @SuppressWarnings("unused") // called via reflection
+    private void test1() throws Exception {
+        System.out.println("DEBUG: ------------> Running test1");
+        try {
+            Field field = targetClass.fieldByName("fooCls");
+            ClassType clsType = (ClassType)field.type();
+            Method constructor = getConstructorForClass(clsType);
+            for (int i = 0; i < 15; i++) {
+                @SuppressWarnings({ "rawtypes", "unchecked" })
+                ObjectReference objRef = clsType.newInstance(mainThread,
+                                                             constructor,
+                                                             new ArrayList(0),
+                                                             ObjectReference.INVOKE_NONVIRTUAL);
+                if (objRef.isCollected()) {
+                    System.out.println("DEBUG: Object got GC'ed before we can use it. NO-OP.");
+                    continue;
+                }
+                invoke("testMethod", "(LOomDebugTestTarget$FooCls;)V", objRef);
+            }
+        } catch (InvocationException e) {
+            handleFailure(e);
+        }
+    }
+
+    /*
+     * Test case: Array reference as method parameter.
+     */
+    @SuppressWarnings("unused") // called via reflection
+    private void test2() throws Exception {
+        System.out.println("DEBUG: ------------> Running test2");
+        try {
+            Field field = targetClass.fieldByName("byteArray");
+            ArrayType arrType = (ArrayType)field.type();
+
+            for (int i = 0; i < 15; i++) {
+                ArrayReference byteArrayVal = arrType.newInstance(3000000);
+                if (byteArrayVal.isCollected()) {
+                    System.out.println("DEBUG: Object got GC'ed before we can use it. NO-OP.");
+                    continue;
+                }
+                invoke("testPrimitive", "([B)V", byteArrayVal);
+            }
+        } catch (VMOutOfMemoryException e) {
+            defaultHandleOOMFailure(e);
+        }
+    }
+
+    /*
+     * Test case: Array reference as return value.
+     */
+    @SuppressWarnings("unused") // called via reflection
+    private void test3() throws Exception {
+        System.out.println("DEBUG: ------------> Running test3");
+        try {
+            for (int i = 0; i < 15; i++) {
+                invoke("testPrimitiveArrRetval",
+                       "()[B",
+                       Collections.EMPTY_LIST,
+                       vm().mirrorOfVoid());
+            }
+        } catch (InvocationException e) {
+            handleFailure(e);
+        }
+    }
+
+    /*
+     * Test case: Object reference as return value.
+     */
+    @SuppressWarnings("unused") // called via reflection
+    private void test4() throws Exception {
+        System.out.println("DEBUG: ------------> Running test4");
+        try {
+            for (int i = 0; i < 15; i++) {
+                invoke("testFooClsRetval",
+                       "()LOomDebugTestTarget$FooCls;",
+                       Collections.EMPTY_LIST,
+                       vm().mirrorOfVoid());
+            }
+        } catch (InvocationException e) {
+            handleFailure(e);
+        }
+    }
+
+    /*
+     * Test case: Constructor
+     */
+    @SuppressWarnings({ "unused", "unchecked", "rawtypes" }) // called via reflection
+    private void test5() throws Exception {
+        System.out.println("DEBUG: ------------> Running test5");
+        try {
+            ClassType type = (ClassType)thisObject.type();
+            for (int i = 0; i < 15; i++) {
+                type.newInstance(mainThread,
+                                 findMethod(targetClass, "<init>", "()V"),
+                                 new ArrayList(0),
+                                 ObjectReference.INVOKE_NONVIRTUAL);
+            }
+        } catch (InvocationException e) {
+            handleFailure(e);
+        }
+    }
+
+    private Method getConstructorForClass(ClassType clsType) {
+        List<Method> methods = clsType.methodsByName("<init>");
+        if (methods.size() != 1) {
+            throw new RuntimeException("FAIL. Expected only one, the default, constructor");
+        }
+        return methods.get(0);
+    }
+
+    private void handleFailure(InvocationException e) {
+        // There is no good way to see the OOME diagnostic message in the target since the
+        // TestScaffold might throw an exception while trying to print the stack trace. I.e
+        // it might get a a VMDisconnectedException before the stack trace printing finishes.
+        System.err.println("FAILURE: InvocationException thrown. Trying to determine cause...");
+        defaultHandleOOMFailure(e);
+    }
+
+    private void defaultHandleOOMFailure(Exception e) {
+        e.printStackTrace();
+        failure();
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    void invoke(String methodName, String methodSig, Value value)
+            throws Exception {
+        List args = new ArrayList(1);
+        args.add(value);
+        invoke(methodName, methodSig, args, value);
+    }
+
+    void invoke(String methodName,
+                String methodSig,
+                @SuppressWarnings("rawtypes") List args,
+                Value value) throws Exception {
+        Method method = findMethod(targetClass, methodName, methodSig);
+        if ( method == null) {
+            failure("FAILED: Can't find method: "
+                    + methodName  + " for class = " + targetClass);
+            return;
+        }
+        invoke(method, args, value);
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    void invoke(Method method, List args, Value value) throws Exception {
+        thisObject.invokeMethod(mainThread, method, args, 0);
+        System.out.println("DEBUG: Done invoking method via debugger.");
+    }
+
+    Value fieldValue(String fieldName) {
+        Field field = targetClass.fieldByName(fieldName);
+        return thisObject.getValue(field);
+    }
+
+    // Determine the pass/fail status on some heuristic and don't fail the
+    // test if < 3 of the total number of tests (currently 5) fail. This also
+    // has the nice side effect that all tests are first attempted and only
+    // all tests ran an overall pass/fail status is determined.
+    private static void determineOverallTestStatus(OomDebugTest oomTest)
+                                   throws IOException, FileNotFoundException {
+        Properties resultProps = new Properties();
+        if (!RESULT_FILE.exists()) {
+            RESULT_FILE.createNewFile();
+        }
+        FileInputStream fin = null;
+        try {
+            fin = new FileInputStream(RESULT_FILE);
+            resultProps.load(fin);
+            resultProps.put(oomTest.testMethod,
+                            Integer.toString(oomTest.failedTests));
+        } finally {
+            if (fin != null) {
+                fin.close();
+            }
+        }
+        System.out.println("DEBUG: Finished running test '"
+                           + oomTest.testMethod + "'.");
+        if (LAST_TEST.equals(oomTest.testMethod)) {
+            System.out.println("DEBUG: Determining overall test status.");
+            Set<String> actualTestsRun = new HashSet<String>();
+            int totalTests = ALL_TESTS.length;
+            int failedTests = 0;
+            for (Object key: resultProps.keySet()) {
+                actualTestsRun.add((String)key);
+                Object propVal = resultProps.get(key);
+                int value = Integer.parseInt((String)propVal);
+                failedTests += value;
+            }
+            if (!ALL_TESTS_SET.equals(actualTestsRun)) {
+                String errorMsg = "Test failed! Expected to run tests '"
+                        + ALL_TESTS_SET + "', but only these were run '"
+                        + actualTestsRun + "'";
+                throw new RuntimeException(errorMsg);
+            }
+            if (failedTests >= 3) {
+                String errorMsg = "Test failed. Expected < 3 sub-tests to fail "
+                                  + "for a pass. Got " + failedTests
+                                  + " failed tests out of " + totalTests + ".";
+                throw new RuntimeException(errorMsg);
+            }
+            RESULT_FILE.delete();
+            System.out.println("All " + totalTests + " tests passed.");
+        } else {
+            System.out.println("DEBUG: More tests to run. Coninuing.");
+            FileOutputStream fout = null;
+            try {
+                fout = new FileOutputStream(RESULT_FILE);
+                resultProps.store(fout, "Storing results after test "
+                                         + oomTest.testMethod);
+            } finally {
+                if (fout != null) {
+                    fout.close();
+                }
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        System.setProperty("test.vm.opts", "-Xmx40m"); // Set debuggee VM option
+        OomDebugTest oomTest = new OomDebugTest(args);
+        try {
+            oomTest.startTests();
+        } catch (Throwable e) {
+            System.out.println("DEBUG: Got exception for test run. " + e);
+            e.printStackTrace();
+            oomTest.failure();
+        }
+        determineOverallTestStatus(oomTest);
+    }
+
+}
diff --git a/jdk/test/com/sun/jdi/oom/OomDebugTestSetup.sh b/jdk/test/com/sun/jdi/oom/OomDebugTestSetup.sh
new file mode 100644
index 0000000..5fbb32e
--- /dev/null
+++ b/jdk/test/com/sun/jdi/oom/OomDebugTestSetup.sh
@@ -0,0 +1,46 @@
+#!/bin/sh
+#
+# Copyright (c) 2016 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.
+#
+
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+cp ${TESTSRC}/@debuggeeVMOptions ${TESTCLASSES}/
diff --git a/jdk/test/com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java b/jdk/test/com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java
new file mode 100644
index 0000000..1301c4c
--- /dev/null
+++ b/jdk/test/com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java
@@ -0,0 +1,210 @@
+/*
+ * 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
+ * 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
+ * @run main/othervm DeadSSLLdapTimeoutTest
+ * @bug 8141370
+ * @key intermittent
+ */
+
+import java.net.Socket;
+import java.net.ServerSocket;
+import java.net.SocketTimeoutException;
+import java.io.*;
+import javax.naming.*;
+import javax.naming.directory.*;
+import java.util.List;
+import java.util.Hashtable;
+import java.util.ArrayList;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLHandshakeException;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+
+
+class DeadServerTimeoutSSLTest implements Callable {
+
+    Hashtable env;
+    DeadSSLServer server;
+    boolean passed = false;
+    private int HANGING_TEST_TIMEOUT = 20_000;
+
+    public DeadServerTimeoutSSLTest(Hashtable env) throws IOException {
+        this.server = new DeadSSLServer();
+        this.env = env;
+    }
+
+    public void performOp(InitialContext ctx) throws NamingException {}
+
+    public void handleNamingException(NamingException e, long start, long end) {
+        if (e.getCause() instanceof SocketTimeoutException) {
+            // SSL connect will timeout via readReply using
+            // SocketTimeoutException
+            e.printStackTrace();
+            pass();
+        } else if (e.getCause() instanceof SSLHandshakeException
+                && e.getCause().getCause() instanceof EOFException) {
+            // test seems to be failing intermittently on some
+            // platforms.
+            pass();
+        } else {
+            fail(e);
+        }
+    }
+
+    public void pass() {
+        this.passed = true;
+    }
+
+    public void fail() {
+        throw new RuntimeException("Test failed");
+    }
+
+    public void fail(Exception e) {
+        throw new RuntimeException("Test failed", e);
+    }
+
+    boolean shutItDown(InitialContext ctx) {
+        try {
+            if (ctx != null) ctx.close();
+            return true;
+        } catch (NamingException ex) {
+            return false;
+        }
+    }
+
+    public Boolean call() {
+        InitialContext ctx = null;
+        ScheduledFuture killer = null;
+        long start = System.nanoTime();
+
+        try {
+            while(!server.accepting())
+                Thread.sleep(200); // allow the server to start up
+            Thread.sleep(200); // to be sure
+
+            env.put(Context.PROVIDER_URL, "ldap://localhost:" +
+                    server.getLocalPort());
+
+            try {
+                ctx = new InitialDirContext(env);
+                performOp(ctx);
+                fail();
+            } catch (NamingException e) {
+                long end = System.nanoTime();
+                System.out.println(this.getClass().toString() + " - elapsed: "
+                        + NANOSECONDS.toMillis(end - start));
+                handleNamingException(e, start, end);
+            } finally {
+                if (killer != null && !killer.isDone())
+                    killer.cancel(true);
+                shutItDown(ctx);
+                server.close();
+            }
+            return passed;
+        } catch (IOException|InterruptedException e) {
+            throw new RuntimeException(e);
+        }
+    }
+}
+
+class DeadSSLServer extends Thread {
+    ServerSocket serverSock;
+    boolean accepting = false;
+
+    public DeadSSLServer() throws IOException {
+        this.serverSock = new ServerSocket(0);
+        start();
+    }
+
+    public void run() {
+        while(true) {
+            try {
+                accepting = true;
+                Socket socket = serverSock.accept();
+            } catch (Exception e) {
+                break;
+            }
+        }
+    }
+
+    public int getLocalPort() {
+        return serverSock.getLocalPort();
+    }
+
+    public boolean accepting() {
+        return accepting;
+    }
+
+    public void close() throws IOException {
+        serverSock.close();
+    }
+}
+
+public class DeadSSLLdapTimeoutTest {
+
+    static Hashtable createEnv() {
+        Hashtable env = new Hashtable(11);
+        env.put(Context.INITIAL_CONTEXT_FACTORY,
+            "com.sun.jndi.ldap.LdapCtxFactory");
+        return env;
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        InitialContext ctx = null;
+
+        //
+        // Running this test serially as it seems to tickle a problem
+        // on older kernels
+        //
+        // run the DeadServerTest with connect / read timeouts set
+        // and ssl enabled
+        // this should exit with a SocketTimeoutException as the root cause
+        // it should also use the connect timeout instead of the read timeout
+        System.out.println("Running connect timeout test with 10ms connect timeout, 3000ms read timeout & SSL");
+        Hashtable sslenv = createEnv();
+        sslenv.put("com.sun.jndi.ldap.connect.timeout", "10");
+        sslenv.put("com.sun.jndi.ldap.read.timeout", "3000");
+        sslenv.put(Context.SECURITY_PROTOCOL, "ssl");
+        boolean testFailed =
+            (new DeadServerTimeoutSSLTest(sslenv).call()) ? false : true;
+
+        if (testFailed) {
+            throw new AssertionError("some tests failed");
+        }
+
+    }
+
+}
+
diff --git a/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java b/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
index 9a55800..aa071ef 100644
--- a/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
+++ b/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
@@ -46,6 +46,7 @@
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLHandshakeException;
 
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 import static java.util.concurrent.TimeUnit.NANOSECONDS;
@@ -83,6 +84,10 @@
         throw new RuntimeException("Test failed");
     }
 
+    public void fail(Exception e) {
+        throw new RuntimeException("Test failed", e);
+    }
+
     boolean shutItDown(InitialContext ctx) {
         try {
             if (ctx != null) ctx.close();
@@ -219,23 +224,6 @@
     }
 }
 
-class DeadServerTimeoutSSLTest extends DeadServerTest {
-
-    public DeadServerTimeoutSSLTest(Hashtable env) throws IOException {
-        super(env);
-    }
-
-    public void handleNamingException(NamingException e, long start, long end) {
-        if (e.getCause() instanceof SocketTimeoutException) {
-            // SSL connect will timeout via readReply using
-            // SocketTimeoutException
-            pass();
-        } else {
-            fail();
-        }
-    }
-}
-
 
 class ReadServerNoTimeoutTest extends ReadServerTest {
 
@@ -268,7 +256,8 @@
     }
 
     public void handleNamingException(NamingException e, long start, long end) {
-        if (NANOSECONDS.toMillis(end - start) < 2_900) {
+        System.out.println("ReadServerTimeoutTest: end-start=" + NANOSECONDS.toMillis(end - start));
+        if (NANOSECONDS.toMillis(end - start) < 2_500) {
             fail();
         } else {
             pass();
@@ -406,11 +395,14 @@
 
             // run the ReadServerTest with connect / read timeouts set
             // this should exit after the connect timeout expires
-            System.out.println("Running read timeout test with 10ms connect timeout, 3000ms read timeout");
-            Hashtable env4 = createEnv();
-            env4.put("com.sun.jndi.ldap.connect.timeout", "10");
-            env4.put("com.sun.jndi.ldap.read.timeout", "3000");
-            results.add(testPool.submit(new ReadServerTimeoutTest(env4)));
+            //
+            // NOTE: commenting this test out as it is failing intermittently.
+            //
+            // System.out.println("Running read timeout test with 10ms connect timeout, 3000ms read timeout");
+            // Hashtable env4 = createEnv();
+            // env4.put("com.sun.jndi.ldap.connect.timeout", "10");
+            // env4.put("com.sun.jndi.ldap.read.timeout", "3000");
+            // results.add(testPool.submit(new ReadServerTimeoutTest(env4)));
 
             // run the DeadServerTest with connect timeout set
             // this should exit after the connect timeout expires
@@ -438,21 +430,6 @@
                 }
             }
 
-            //
-            // Running this test serially as it seems to tickle a problem
-            // on older kernels
-            //
-            // run the DeadServerTest with connect / read timeouts set
-            // and ssl enabled
-            // this should exit with a SocketTimeoutException as the root cause
-            // it should also use the connect timeout instead of the read timeout
-            System.out.println("Running connect timeout test with 10ms connect timeout, 3000ms read timeout & SSL");
-            Hashtable sslenv = createEnv();
-            sslenv.put("com.sun.jndi.ldap.connect.timeout", "10");
-            sslenv.put("com.sun.jndi.ldap.read.timeout", "3000");
-            sslenv.put(Context.SECURITY_PROTOCOL, "ssl");
-            testFailed = (new DeadServerTimeoutSSLTest(sslenv).call()) ? false : true;
-
             if (testFailed) {
                 throw new AssertionError("some tests failed");
             }
diff --git a/jdk/test/com/sun/net/httpserver/bugs/6725892/Test.java b/jdk/test/com/sun/net/httpserver/bugs/6725892/Test.java
index 622f1b1..e09a33f 100644
--- a/jdk/test/com/sun/net/httpserver/bugs/6725892/Test.java
+++ b/jdk/test/com/sun/net/httpserver/bugs/6725892/Test.java
@@ -68,7 +68,7 @@
 
         try {
             InetSocketAddress addr = new InetSocketAddress (0);
-            s1 = HttpServer.create (addr, 0);
+            s1 = HttpServer.create (addr, 100);
             HttpHandler h = new Handler ();
             HttpContext c1 = s1.createContext ("/", h);
             s1.setExecutor(exec);
diff --git a/jdk/test/java/awt/Container/MoveToOtherScreenTest/MoveToOtherScreenTest.java b/jdk/test/java/awt/Container/MoveToOtherScreenTest/MoveToOtherScreenTest.java
new file mode 100644
index 0000000..d5cfa4a
--- /dev/null
+++ b/jdk/test/java/awt/Container/MoveToOtherScreenTest/MoveToOtherScreenTest.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+import java.awt.Canvas;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Frame;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.lang.reflect.InvocationTargetException;
+
+
+
+/* @test
+   @bug 8160696
+   @summary IllegalArgumentException: adding a component to a container on a different GraphicsDevice
+   @author Mikhail Cherkasov
+   @run main MoveToOtherScreenTest
+*/
+public class MoveToOtherScreenTest {
+
+    private static volatile boolean twoDisplays = true;
+    private static final Canvas canvas = new Canvas();
+    private static final Frame[] frms = new JFrame[2];
+
+    public static void main(String[] args) throws InterruptedException, InvocationTargetException {
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                GraphicsEnvironment ge = GraphicsEnvironment.
+                        getLocalGraphicsEnvironment();
+                GraphicsDevice[] gds = ge.getScreenDevices();
+                if (gds.length < 2) {
+                    System.out.println("Test requires at least 2 displays");
+                    twoDisplays = false;
+                    return;
+                }
+                for (int i = 0; i < 2; i++) {
+                    GraphicsConfiguration conf = gds[i].getConfigurations()[0];
+                    JFrame frm = new JFrame("Frame " + i);
+                    frm.setLocation(conf.getBounds().x, 0); // On first screen
+                    frm.setSize(new Dimension(400, 400));
+                    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+                    frm.setVisible(true);
+                    frms[i] = frm;
+                }
+                canvas.setBackground(Color.red);
+                frms[0].add(canvas);
+            }
+        });
+        if(!twoDisplays){
+           return;
+        }
+        Thread.sleep(200);
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                frms[1].add(canvas);
+            }
+        });
+        for (Frame frm : frms) {
+            frm.dispose();
+        }
+    }
+}
diff --git a/jdk/test/java/awt/Dialog/DialogAboveFrame/DialogAboveFrameTest.java b/jdk/test/java/awt/Dialog/DialogAboveFrame/DialogAboveFrameTest.java
new file mode 100644
index 0000000..6f0a631
--- /dev/null
+++ b/jdk/test/java/awt/Dialog/DialogAboveFrame/DialogAboveFrameTest.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2016, 2017, 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 8169589 8171909
+ * @summary Activating a dialog puts to back another dialog owned by the same frame
+ * @author Dmitry Markov
+ * @library ../../regtesthelpers
+ * @build Util
+ * @run main DialogAboveFrameTest
+ */
+
+import java.awt.Color;
+import java.awt.Dialog;
+import java.awt.Frame;
+import java.awt.Point;
+import java.awt.Robot;
+
+import test.java.awt.regtesthelpers.Util;
+
+public class DialogAboveFrameTest {
+    public static void main(String[] args) {
+        Robot robot = Util.createRobot();
+
+        Frame frame = new Frame("Frame");
+        frame.setBackground(Color.BLUE);
+        frame.setBounds(200, 50, 300, 300);
+        frame.setVisible(true);
+
+        Dialog dialog1 = new Dialog(frame, "Dialog 1", false);
+        dialog1.setBackground(Color.RED);
+        dialog1.setBounds(100, 100, 200, 200);
+        dialog1.setVisible(true);
+
+        Dialog dialog2 = new Dialog(frame, "Dialog 2", false);
+        dialog2.setBackground(Color.GREEN);
+        dialog2.setBounds(400, 100, 200, 200);
+        dialog2.setVisible(true);
+
+        Util.waitForIdle(robot);
+
+        Util.clickOnComp(dialog2, robot);
+        Util.waitForIdle(robot);
+
+        Point point = dialog1.getLocationOnScreen();
+        int x = point.x + (int)(dialog1.getWidth() * 0.9);
+        int y = point.y + (int)(dialog1.getHeight() * 0.9);
+
+        try {
+            if (!Util.testPixelColor(x, y, dialog1.getBackground(), 10, 100, robot)) {
+                throw new RuntimeException("Test FAILED: Dialog is behind the frame");
+            }
+        } finally {
+            frame.dispose();
+            dialog1.dispose();
+            dialog2.dispose();
+        }
+    }
+}
+
diff --git a/jdk/test/java/awt/EventQueue/6980209/bug6980209.java b/jdk/test/java/awt/EventQueue/6980209/bug6980209.java
new file mode 100644
index 0000000..f01385f
--- /dev/null
+++ b/jdk/test/java/awt/EventQueue/6980209/bug6980209.java
@@ -0,0 +1,241 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+   @bug 6980209
+   @summary Make tracking SecondaryLoop.enter/exit methods easier
+   @author Semyon Sadetsky
+  */
+
+import sun.util.logging.PlatformLogger;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+
+public class bug6980209 implements ActionListener {
+    private final static PlatformLogger log =
+            PlatformLogger.getLogger("java.awt.event.WaitDispatchSupport");
+    public static final int ATTEMPTS = 100;
+    public static final int EVENTS = 5;
+
+    private static boolean runInEDT;
+    private static JFrame frame;
+    private static int disorderCounter = 0;
+    private static Boolean enterReturn;
+    private static Boolean exitReturn;
+    private static int dispatchedEvents;
+
+    public static void main(String[] args) throws Exception {
+        System.out.println(
+                "PLEASE DO NOT TOUCH KEYBOARD AND MOUSE DURING THE TEST RUN!");
+        // log.setLevel(PlatformLogger.Level.FINE);
+        // log.setLevel(PlatformLogger.Level.FINEST);
+        try {
+            SwingUtilities.invokeAndWait(new Runnable() {
+                public void run() {
+                    frame = new JFrame();
+                    frame.setUndecorated(true);
+                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+                    setup(frame);
+                }
+            });
+            testExitBeforeEnter();
+            System.out.println("Run random test in EDT");
+            runInEDT = true;
+            testRandomly();
+            System.out.println("Run random test in another thread");
+            runInEDT = false;
+            testRandomly();
+            System.out.println("ok");
+
+        } finally {
+            SwingUtilities.invokeAndWait(new Runnable() {
+                @Override
+                public void run() {
+                    frame.dispose();
+                }
+            });
+        }
+    }
+
+    private static void testExitBeforeEnter() throws Exception {
+        final SecondaryLoop loop =
+                Toolkit.getDefaultToolkit().getSystemEventQueue()
+                        .createSecondaryLoop();
+        loop.exit();
+        Robot robot = new Robot();
+        robot.mouseWheel(1);
+        robot.waitForIdle();
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                if(loop.enter()) {
+                    throw new RuntimeException("Wrong enter() return value");
+                }
+            }
+        });
+    }
+
+    private static void testRandomly() throws AWTException {
+        disorderCounter = 0;
+        final Robot robot = new Robot();
+        for (int i = 0; i < ATTEMPTS; i++) {
+            enterReturn = null;
+            exitReturn = null;
+            dispatchedEvents = 0;
+            synchronized (bug6980209.class) {
+                try {
+                    for (int j = 0; j < EVENTS; j++) {
+                        robot.keyPress(KeyEvent.VK_1);
+                        robot.keyRelease(KeyEvent.VK_1);
+                    }
+
+                    // trigger the button action that starts secondary loop
+                    robot.keyPress(KeyEvent.VK_SPACE);
+                    robot.keyRelease(KeyEvent.VK_SPACE);
+
+                    for (int j = 0; j < EVENTS; j++) {
+                        robot.keyPress(KeyEvent.VK_1);
+                        robot.keyRelease(KeyEvent.VK_1);
+                    }
+                    long time = System.nanoTime();
+                    // wait for enter() returns
+                    bug6980209.class.wait(1000);
+                    if (enterReturn == null) {
+                        System.out.println("wait time=" +
+                                ((System.nanoTime() - time) / 1E9) +
+                                " seconds");
+                        throw new RuntimeException(
+                                "It seems the secondary loop will never end");
+                    }
+                    if (!enterReturn) disorderCounter++;
+
+                    robot.waitForIdle();
+                    if (dispatchedEvents <
+                            2 * EVENTS) { //check that all events are dispatched
+                        throw new RuntimeException(
+                                "KeyEvent.VK_1 has been lost!");
+                    }
+
+                } catch (InterruptedException e) {
+                    throw new RuntimeException("Interrupted!");
+                }
+            }
+        }
+        if (disorderCounter == 0) {
+            System.out.println(
+                    "Zero disordered enter/exit caught. It is recommended to run scenario again");
+        } else {
+            System.out.println(
+                    "Disordered calls is " + disorderCounter + " from " +
+                            ATTEMPTS);
+        }
+    }
+
+    private static void setup(final JFrame frame) {
+        JButton jButton = new JButton("Button");
+        frame.getContentPane().add(jButton);
+        jButton.addActionListener(new bug6980209());
+        frame.pack();
+        frame.setVisible(true);
+        jButton.setFocusable(true);
+        jButton.requestFocus();
+        jButton.addKeyListener(new KeyListener() {
+            @Override
+            public void keyTyped(KeyEvent e) {
+            }
+
+            @Override
+            public void keyPressed(KeyEvent e) {
+                if (e.getKeyChar() == '1') dispatchedEvents++;
+            }
+
+            @Override
+            public void keyReleased(KeyEvent e) {
+                if (e.getKeyChar() == '1') dispatchedEvents++;
+            }
+        });
+    }
+
+
+    @Override
+    public void actionPerformed(ActionEvent e) {
+        if (runInEDT) {
+            runSecondaryLoop();
+            return;
+        }
+        new Thread("Secondary loop run thread") {
+            @Override
+            public void run() {
+                runSecondaryLoop();
+            }
+        }.start();
+    }
+
+    private static void runSecondaryLoop() {
+        log.fine("\n---TEST START---");
+
+        final SecondaryLoop loop =
+                Toolkit.getDefaultToolkit().getSystemEventQueue()
+                        .createSecondaryLoop();
+
+        final Object LOCK = new Object(); //lock to start simultaneously
+        Thread exitThread = new Thread("Exit thread") {
+            @Override
+            public void run() {
+                synchronized (LOCK) {
+                    LOCK.notify();
+                }
+                Thread.yield();
+                exitReturn = loop.exit();
+                log.fine("exit() returns " + exitReturn);
+            }
+        };
+
+        synchronized (LOCK) {
+            try {
+                exitThread.start();
+                LOCK.wait();
+            } catch (InterruptedException e1) {
+                throw new RuntimeException("What?");
+            }
+        }
+
+        enterReturn = loop.enter();
+        log.fine("enter() returns " + enterReturn);
+
+        try {
+            exitThread.join();
+        } catch (InterruptedException e) {
+            throw new RuntimeException("What?");
+        }
+        synchronized (bug6980209.class) {
+            bug6980209.class.notifyAll();
+        }
+        log.fine("\n---TEST END---");
+    }
+}
\ No newline at end of file
diff --git a/jdk/test/java/awt/FileDialog/DeleteInsideFileDialog/DeleteInsideFileDialogTest.java b/jdk/test/java/awt/FileDialog/DeleteInsideFileDialog/DeleteInsideFileDialogTest.java
new file mode 100644
index 0000000..091733a
--- /dev/null
+++ b/jdk/test/java/awt/FileDialog/DeleteInsideFileDialog/DeleteInsideFileDialogTest.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+  @test
+  @bug 8075516
+  @requires os.family=="windows"
+  @summary Deleting a file from either the open or save java.awt.FileDialog
+           hangs.
+  @run main/manual DeleteInsideFileDialogTest
+*/
+
+import java.awt.*;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+public class DeleteInsideFileDialogTest {
+
+    private static Path dir;
+    private static Path file1;
+    private static Path file2;
+    private static Frame f;
+    private static FileDialog fd;
+
+    public static void main(String[] args) throws Exception {
+
+        String instructions =
+                "1) Delete file deleteMe.tst in the opened File Dialog window" +
+                   " using the right click popup menu\n" +
+                "2) Select thenSelectMe.tst file in the File Dialog and press" +
+                   " Open (if this is not possible the test fails)\n";
+        dir = Files.createTempDirectory("Test");
+        file1 = Files.createFile(Paths.get(dir.toString(), "deleteMe.tst"));
+        file2 = Files.createFile(Paths.get(dir.toString(), "thenSelectMe.tst"));
+        try {
+            f = new Frame("Instructions");
+            f.add(new TextArea(instructions, 6, 60, TextArea.SCROLLBARS_NONE));
+            f.pack();
+            f.setLocation(100, 500);
+            f.setVisible(true);
+
+            fd = new FileDialog((Frame)null);
+            fd.setDirectory(dir.toString());
+            fd.setVisible(true);
+            if (fd.getFile() == null) {
+                throw new RuntimeException("Failed");
+            }
+        } finally {
+            if (fd != null) {
+                fd.dispose();
+            }
+            if (f != null) {
+                f.dispose();
+            }
+            Files.deleteIfExists(file1);
+            Files.deleteIfExists(file2);
+            Files.deleteIfExists(dir);
+        }
+    }
+}
diff --git a/jdk/test/java/awt/Focus/ModalDialogActivationTest/ModalDialogActivationTest.java b/jdk/test/java/awt/Focus/ModalDialogActivationTest/ModalDialogActivationTest.java
new file mode 100644
index 0000000..deff8ee
--- /dev/null
+++ b/jdk/test/java/awt/Focus/ModalDialogActivationTest/ModalDialogActivationTest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  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.
+ */
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+
+/*
+  @test
+  @bug       8160570
+  @summary   Tests that a modal dialog receives WINDOW_ACTIVATED & WINDOW_GAINED_FOCUS on first show.
+*/
+public class ModalDialogActivationTest {
+    static final Object lock = new Object();
+    static volatile boolean activated;
+    static volatile boolean focused;
+
+    public static void main(String[] args) throws InterruptedException {
+        EventQueue.invokeLater(() -> runGUI());
+
+        long time = System.currentTimeMillis();
+        synchronized (lock) {
+            while (!activated || !focused) {
+                lock.wait(5000);
+                if (System.currentTimeMillis() - time >= 5000) break;
+            }
+        }
+        if (!activated || !focused) {
+            throw new RuntimeException("Test FAILED: activated: " + activated + ", focused: " + focused);
+        }
+        System.out.println("Test PASSED");
+    }
+
+    static void runGUI() {
+        JFrame f = new JFrame("frame");
+        final JDialog d = new MyModalDialog(f, "dialog");
+        d.addWindowListener(new WindowAdapter() {
+            @Override
+            public void windowActivated(WindowEvent e) {
+                synchronized (lock) {
+                    activated = true;
+                    lock.notifyAll();
+                }
+            }
+        });
+        d.addWindowFocusListener(new WindowAdapter() {
+            @Override
+            public void windowGainedFocus(WindowEvent e) {
+                synchronized (lock) {
+                    focused = true;
+                    lock.notifyAll();
+                }
+            }
+        });
+        f.setVisible(true);
+        d.setVisible(true);
+    }
+
+    static class MyModalDialog extends JDialog {
+        public MyModalDialog(Frame owner, String title)ª {
+            super(owner, title, true);
+        }
+
+        @Override
+        public boolean getFocusableWindowState() {
+            try {
+                // let Toolkit thread go ahead
+                Thread.sleep(100);
+            } catch (InterruptedException ignore) {
+            }
+            return super.getFocusableWindowState();
+        }
+    }
+}
diff --git a/jdk/test/java/awt/Frame/NormalToIconified/NormalToIconifiedTest.java b/jdk/test/java/awt/Frame/NormalToIconified/NormalToIconifiedTest.java
new file mode 100644
index 0000000..ca4c592
--- /dev/null
+++ b/jdk/test/java/awt/Frame/NormalToIconified/NormalToIconifiedTest.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8171949
+ * @summary Tests that bitwise mask is set and state listener is notified during state transition.
+ * @author Dmitry Markov
+ * @library ../../regtesthelpers
+ * @build Util
+ * @run main NormalToIconifiedTest
+ */
+
+import java.awt.Frame;
+import java.awt.Robot;
+import java.awt.event.WindowEvent;
+import java.awt.event.WindowStateListener;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import test.java.awt.regtesthelpers.Util;
+
+public class NormalToIconifiedTest {
+    private static final AtomicBoolean listenerNotified = new AtomicBoolean(false);
+
+    public static void main(String[] args) {
+        Robot robot = Util.createRobot();
+
+        Frame testFrame = new Frame("Test Frame");
+        testFrame.setSize(200, 200);
+        testFrame.addWindowStateListener(new WindowStateListener() {
+            @Override
+            public void windowStateChanged(WindowEvent e) {
+                listenerNotified.set(true);
+                synchronized (listenerNotified) {
+                    listenerNotified.notifyAll();
+                }
+            }
+        });
+        testFrame.setVisible(true);
+
+        Frame mainFrame = new Frame("Main Frame");
+        mainFrame.setSize(200, 200);
+        mainFrame.setLocationRelativeTo(null);
+        mainFrame.setVisible(true);
+
+        Util.waitForIdle(robot);
+
+        try {
+            Util.clickOnComp(mainFrame, robot);
+            Util.waitForIdle(robot);
+
+            // NORMAL -> ICONIFIED
+            listenerNotified.set(false);
+            testFrame.setExtendedState(Frame.ICONIFIED);
+            Util.waitForIdle(robot);
+
+            Util.waitForCondition(listenerNotified, 2000);
+            if (!listenerNotified.get()) {
+                throw new RuntimeException("Test FAILED! Window state listener was not notified during NORMAL to" +
+                        "ICONIFIED transition");
+            }
+            if (testFrame.getExtendedState() != Frame.ICONIFIED) {
+                throw new RuntimeException("Test FAILED! Frame is not in ICONIFIED state");
+            }
+
+            // ICONIFIED -> NORMAL
+            listenerNotified.set(false);
+            testFrame.setExtendedState(Frame.NORMAL);
+            Util.waitForIdle(robot);
+
+            Util.waitForCondition(listenerNotified, 2000);
+            if (!listenerNotified.get()) {
+                throw new RuntimeException("Test FAILED! Window state listener was not notified during ICONIFIED to" +
+                        "NORMAL transition");
+            }
+            if (testFrame.getExtendedState() != Frame.NORMAL) {
+                throw new RuntimeException("Test FAILED! Frame is not in NORMAL state");
+            }
+        } finally {
+            testFrame.dispose();
+            mainFrame.dispose();
+        }
+    }
+}
+
diff --git a/jdk/test/java/awt/Frame/ObscuredFrame/ObscuredFrameTest.java b/jdk/test/java/awt/Frame/ObscuredFrame/ObscuredFrameTest.java
new file mode 100644
index 0000000..762d672
--- /dev/null
+++ b/jdk/test/java/awt/Frame/ObscuredFrame/ObscuredFrameTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8171952
+ * @summary Tests that getMousePosition() returns null for obscured component.
+ * @author Dmitry Markov
+ * @library ../../regtesthelpers
+ * @build Util
+ * @run main ObscuredFrameTest
+ */
+
+import java.awt.*;
+
+import test.java.awt.regtesthelpers.Util;
+
+public class ObscuredFrameTest {
+    public static void main(String[] args) {
+        Robot robot = Util.createRobot();
+
+        Frame frame = new Frame("Obscured Frame");
+        frame.setSize(200, 200);
+        frame.setLocationRelativeTo(null);
+        Button button = new Button("Button");
+        frame.add(button);
+
+        Dialog dialog = new Dialog(frame, "Visible Dialog", false);
+        dialog.setSize(200, 200);
+        dialog.setLocationRelativeTo(null);
+        dialog.setVisible(true);
+
+        frame.setVisible(true);
+
+        Util.waitForIdle(robot);
+
+        Util.pointOnComp(button, robot);
+        Util.waitForIdle(robot);
+        robot.delay(2000);
+
+        try {
+            if (button.getMousePosition() != null) {
+                throw new RuntimeException("Test Failed! Mouse position is not null for obscured component.");
+            }
+        } finally {
+            frame.dispose();
+            dialog.dispose();
+        }
+    }
+}
+
diff --git a/jdk/test/java/awt/InputMethods/DiacriticsTest/DiacriticsTest.html b/jdk/test/java/awt/InputMethods/DiacriticsTest/DiacriticsTest.html
index 89dab3d..5cf5c91 100644
--- a/jdk/test/java/awt/InputMethods/DiacriticsTest/DiacriticsTest.html
+++ b/jdk/test/java/awt/InputMethods/DiacriticsTest/DiacriticsTest.html
@@ -1,5 +1,5 @@
 <!--
-Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 
 This code is free software; you can redistribute it and/or modify it
@@ -31,6 +31,8 @@
 Test run requires the following keyboard layouts to be installed:
 Linux OS: English (US, alternative international)
 Windows OS: Hungarian
+A keyboard layout having compose function or compose-like key. Programmer
+Dvorak (http://www.kaufmann.no/roland/dvorak/) is suggested to use.
 
 To test JDK-8000423 fix (Linux only!):
 please switch to US alternative international layout and try to type diacritics
@@ -40,6 +42,12 @@
 please switch to Hungarian keyboard layout and try to type diacritics 
 (Ctrl+Alt+2 e; Ctrl+Alt+2 E)
 
+To test JDK-8139189 fix:
+please switch to Programmer Dvorak keyboard layout try to type diacritics
+using compose combinations (Compose+z+d, Compose+z+Shift+d). The Compose key
+in Programmer Dvorak layout is OEM102 the key which is located between
+Left Shift and Z keys on the standard 102-key keyboard.
+
 If you can do that then the test is passed; otherwise failed.
 </body>
 </html>
diff --git a/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html
new file mode 100644
index 0000000..af6cd0c
--- /dev/null
+++ b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html
@@ -0,0 +1,40 @@
+<!--
+Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+
+This code is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License version 2 only, as
+published by the Free Software Foundation.
+
+This code is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+version 2 for more details (a copy is included in the LICENSE file that
+accompanied this code).
+
+You should have received a copy of the GNU General Public License version
+2 along with this work; if not, write to the Free Software Foundation,
+Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+or visit www.oracle.com if you need additional information or have any
+questions.
+-->
+
+<html>
+<head>
+<title> SpanishDiacriticsTest </title>
+</head>
+<body>
+<applet code="SpanishDiacriticsTest.class" width=350 height=200></applet>
+
+Test run requires the following keyboard layout to be installed:
+Windows OS: Spanish (United States) with 'Latin American' keyboard layout
+
+1. A frame with a text field should be displayed at upper left corner
+2. Set focus to the text field and switch to Spanish with 'Latin American' keyboard layout
+3. Type the following: ' ' o - i.e. single quote two times (using [ key on US keyboard) then o character.
+
+If you the text field displays ''o, (i.e. o should be without acute) then the test is passed; otherwise failed.
+</body>
+</html>
diff --git a/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java
new file mode 100644
index 0000000..7887706
--- /dev/null
+++ b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8169355
+ * @summary Check if Spanish diacritical signs could be typed for TextField
+ * @author Dmitry Markov
+ * @run applet/manual=yesno SpanishDiacriticsTest.html
+*/
+
+import javax.swing.*;
+import java.applet.Applet;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.util.concurrent.locks.LockSupport;
+
+public class SpanishDiacriticsTest extends Applet {
+    @Override
+    public void init() {
+        SwingUtilities.invokeLater(() -> {
+            JFrame frame = new JFrame();
+            JTextField textField = new JTextField(20);
+            textField.addKeyListener(new KeyAdapter() {
+                @Override
+                public void keyTyped(KeyEvent e) {
+                    LockSupport.parkNanos(1_000_000_000L);
+                }
+            });
+            frame.add(textField);
+            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+            frame.pack();
+            frame.setVisible(true);
+        });
+    }
+}
+
diff --git a/jdk/test/java/awt/Mouse/EnterExitEvents/ModalDialogEnterExitEventsTest.java b/jdk/test/java/awt/Mouse/EnterExitEvents/ModalDialogEnterExitEventsTest.java
new file mode 100644
index 0000000..1ec2d2f
--- /dev/null
+++ b/jdk/test/java/awt/Mouse/EnterExitEvents/ModalDialogEnterExitEventsTest.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8050478
+ * @summary Cursor not updating correctly after closing a modal dialog.
+ *    The root cause of the issue was the lack of a mouse exit event
+ *    during displaying of a modal dialog.
+ * @author Dmitry Markov
+ * @library ../../regtesthelpers
+ * @build Util
+ * @run main ModalDialogEnterExitEventsTest
+ */
+
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+import java.awt.FlowLayout;
+import java.awt.Frame;
+import java.awt.Robot;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import test.java.awt.regtesthelpers.Util;
+
+public class ModalDialogEnterExitEventsTest {
+    private static volatile AtomicInteger mouseEnterCount = new AtomicInteger();
+    private static volatile AtomicInteger mouseExitCount = new AtomicInteger();
+
+    private static JFrame frame;
+    private static JButton openButton;
+    private static JButton closeButton;
+
+    public static void main(String[] args) {
+        Robot robot = Util.createRobot();
+
+        SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+                createAndShowGUI();
+            }
+        });
+        Util.waitForIdle(robot);
+
+        Util.clickOnComp(frame, robot, 500);
+        Util.waitForIdle(robot);
+
+        mouseEnterCount.set(0);
+        mouseExitCount.set(0);
+
+        Util.clickOnComp(openButton, robot, 500);
+        Util.waitForIdle(robot);
+        if (mouseExitCount.get() != 1) {
+            throw new RuntimeException("Test FAILED. Wrong number of MouseExited events = " + mouseExitCount.get());
+        }
+
+        Util.clickOnComp(closeButton, robot, 500);
+        Util.waitForIdle(robot);
+        if (mouseEnterCount.get() != 1) {
+            throw new RuntimeException("Test FAILED. Wrong number of MouseEntered events = "+ mouseEnterCount.get());
+        }
+    }
+
+    private static void createAndShowGUI() {
+        frame = new JFrame("ModalDialogEnterExitEventsTest");
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+        frame.setLayout(new FlowLayout());
+        frame.addMouseListener(new MouseAdapter() {
+            @Override
+            public void mouseExited(MouseEvent e) {
+                mouseExitCount.getAndIncrement();
+            }
+
+            @Override
+            public void mouseEntered(MouseEvent e) {
+                mouseEnterCount.getAndIncrement();
+            }
+        });
+        openButton = new JButton("Open Dialog");
+        openButton.addActionListener(new ActionListener() {
+            @Override
+            public void actionPerformed(ActionEvent e) {
+                JDialog dialog = new JDialog(frame, "Modal Dialog", true);
+                dialog.setLayout(new FlowLayout());
+                closeButton = new JButton("Close");
+                closeButton.addActionListener(new ActionListener() {
+                    @Override
+                    public void actionPerformed(ActionEvent e) {
+                        dialog.dispose();
+                    }
+                });
+                dialog.add(closeButton);
+                dialog.setSize(200, 200);
+                dialog.setLocationRelativeTo(null);
+                dialog.setVisible(true);
+            }
+        });
+        frame.add(openButton);
+        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
+        frame.setVisible(true);
+    }
+}
+
diff --git a/jdk/test/java/awt/MouseInfo/GetPointerInfoTest.java b/jdk/test/java/awt/MouseInfo/GetPointerInfoTest.java
new file mode 100644
index 0000000..c812cce
--- /dev/null
+++ b/jdk/test/java/awt/MouseInfo/GetPointerInfoTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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
+  @summary unit test for getPointerInfo() from MouseInfo class
+  @author dav@sparc.spb.su: area=
+  @bug 4009555
+  @run main GetPointerInfoTest
+*/
+
+import java.awt.*;
+
+/**
+ * Simply check the result on non-null and results are correct.
+ */
+public class GetPointerInfoTest {
+    private static final String successStage = "Test stage completed.Passed.";
+
+    public static void main(String[] args) throws Exception {
+        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+        GraphicsDevice[] gds = ge.getScreenDevices();
+        int gdslen = gds.length;
+        System.out.println("There are " + gdslen + " Graphics Devices");
+        if (gdslen == 0) {
+            System.out.println("Nothing to be done.");
+            return;
+        }
+        Robot robot = new Robot(gds[0]);
+        robot.setAutoDelay(0);
+        robot.setAutoWaitForIdle(true);
+        robot.delay(10);
+        robot.waitForIdle();
+        Point p = new Point(101, 99);
+        robot.mouseMove(p.x, p.y);
+
+        PointerInfo pi = MouseInfo.getPointerInfo();
+        if (pi == null) {
+            throw new RuntimeException("Test failed. getPointerInfo() returned null value.");
+        } else {
+            System.out.println(successStage);
+        }
+        Point piLocation = pi.getLocation();
+
+        if (piLocation.x != p.x || piLocation.y != p.y) {
+            throw new RuntimeException("Test failed.getPointerInfo() returned incorrect result.");
+        } else {
+            System.out.println(successStage);
+        }
+
+        System.out.println("Test PASSED.");
+    }
+}
diff --git a/jdk/test/java/awt/MouseInfo/MultiscreenPointerInfo.java b/jdk/test/java/awt/MouseInfo/MultiscreenPointerInfo.java
new file mode 100644
index 0000000..288ab4b
--- /dev/null
+++ b/jdk/test/java/awt/MouseInfo/MultiscreenPointerInfo.java
@@ -0,0 +1,90 @@
+/*
+ * 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
+  @summary unit test for getPointerInfo() from MouseInfo class
+  @author prs@sparc.spb.su: area=
+  @bug 4009555
+  @run main MultiscreenPointerInfo
+*/
+
+import java.awt.*;
+
+/**
+ * Simply check the result on non-null and results are correct.
+ */
+public class MultiscreenPointerInfo
+{
+    private static final String successStage = "Test stage completed.Passed.";
+
+    public static void main(String[] args) throws Exception {
+        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+        GraphicsDevice[] gds = ge.getScreenDevices();
+        int gdslen = gds.length;
+        System.out.println("There are " + gdslen + " Graphics Devices");
+        if (gdslen < 2) {
+            System.out.println("Nothing to be done. PASSED automatically.");
+            return;
+        }
+        Rectangle rx = gds[1].getDefaultConfiguration().getBounds();
+        Robot robot;
+
+        if (rx.x == 0 && rx.y == 0) {
+            // Assuming independent graphics devices
+            robot = new Robot(gds[1]);
+        } else {
+            // Means we have a virtual device
+            robot = new Robot(gds[0]);
+        }
+        robot.setAutoDelay(0);
+        robot.setAutoWaitForIdle(true);
+        robot.delay(10);
+        robot.waitForIdle();
+        Point p = new Point(rx.x + 101, rx.y + 99);
+        robot.mouseMove(p.x, p.y);
+        PointerInfo pi = MouseInfo.getPointerInfo();
+        if (pi == null) {
+            throw new RuntimeException("Test failed. getPointerInfo() returned null value.");
+        } else {
+            System.out.println(successStage);
+        }
+
+        Point piLocation = pi.getLocation();
+
+        if (piLocation.x != p.x || piLocation.y != p.y) {
+            throw new RuntimeException("Test failed.getPointerInfo() returned incorrect location.");
+        } else {
+            System.out.println(successStage);
+        }
+
+        GraphicsDevice dev = pi.getDevice();
+
+        if (dev != gds[1]) {
+            throw new RuntimeException("Test failed.getPointerInfo() returned incorrect device.");
+        } else {
+            System.out.println(successStage);
+        }
+        System.out.println("Test PASSED.");
+    }
+}
diff --git a/jdk/test/java/awt/TextArea/TextAreaEditing/TextAreaEditing.java b/jdk/test/java/awt/TextArea/TextAreaEditing/TextAreaEditing.java
new file mode 100644
index 0000000..f330678
--- /dev/null
+++ b/jdk/test/java/awt/TextArea/TextAreaEditing/TextAreaEditing.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ @test
+ @bug 8040322
+ @summary Test TextArea APIs replaceRange, insert, append & setText
+ @run main TextAreaEditing
+ */
+
+import java.awt.Frame;
+import java.awt.TextArea;
+
+public class TextAreaEditing {
+
+    private int testFailCount;
+    private boolean isTestFail;
+    private StringBuilder testFailMessage;
+
+    private Frame mainFrame;
+    private TextArea textArea;
+
+    private TextAreaEditing() {
+        testFailMessage = new StringBuilder();
+        mainFrame = new Frame();
+        mainFrame.setSize(200, 200);
+
+        textArea = new TextArea();
+        mainFrame.add(textArea);
+        mainFrame.setVisible(true);
+    }
+
+    private void dispose() {
+        if (mainFrame != null) {
+            mainFrame.dispose();
+        }
+    }
+
+    public static void main(String[] s) {
+        TextAreaEditing textArea = new TextAreaEditing();
+        textArea.testReplaceRange();
+        textArea.testInsert();
+        textArea.testAppend();
+        textArea.checkFailures();
+        textArea.dispose();
+    }
+
+    private void testReplaceRange() {
+        textArea.setText(null);
+        textArea.replaceRange("Replace", 0, 0);
+        textArea.setText(null);
+        checkTest("");
+
+        textArea.setText("SetText");
+        textArea.replaceRange("Replace", 0, 3);
+        checkTest("ReplaceText");
+
+        textArea.replaceRange("String", textArea.getText().length(),
+                textArea.getText().length());
+        checkTest("ReplaceTextString");
+
+        textArea.replaceRange("String", 0, 0);
+        checkTest("StringReplaceTextString");
+
+        textArea.replaceRange("replaceRange", 0, textArea.getText().length());
+        checkTest("replaceRange");
+    }
+
+    private void testInsert() {
+        textArea.setText(null);
+        textArea.insert("Insert", 0);
+        textArea.setText("");
+        checkTest("");
+
+        textArea.setText("SetText");
+        textArea.insert("Insert", 3);
+        checkTest("SetInsertText");
+
+        textArea.insert("Insert", 0);
+        checkTest("InsertSetInsertText");
+
+        textArea.insert("Insert", textArea.getText().length());
+        checkTest("InsertSetInsertTextInsert");
+    }
+
+    private void testAppend() {
+        textArea.setText(null);
+        textArea.append("Append");
+        textArea.setText(null);
+        checkTest("");
+
+        textArea.setText("SetText");
+        textArea.append("Append");
+        checkTest("SetTextAppend");
+
+        textArea.append("");
+        checkTest("SetTextAppend");
+        textArea.setText("");
+        checkTest("");
+    }
+
+    private void checkTest(String str) {
+        if (str != null && !str.equals(textArea.getText())) {
+            testFailMessage.append("TestFail line : ");
+            testFailMessage.append(Thread.currentThread().getStackTrace()[2].
+                    getLineNumber());
+            testFailMessage.append(" TextArea string : \"");
+            testFailMessage.append(textArea.getText());
+            testFailMessage.append("\" does not match expected string : \"");
+            testFailMessage.append(str).append("\"");
+            testFailMessage.append(System.getProperty("line.separator"));
+            testFailCount++;
+            isTestFail = true;
+        }
+    }
+
+    private void checkFailures() {
+        if (isTestFail) {
+            testFailMessage.insert(0, "Test Fail count : " + testFailCount
+                    + System.getProperty("line.separator"));
+            dispose();
+            throw new RuntimeException(testFailMessage.toString());
+        }
+    }
+}
diff --git a/jdk/test/java/awt/Window/WindowDeadlockTest/WindowDeadlockTest.java b/jdk/test/java/awt/Window/WindowDeadlockTest/WindowDeadlockTest.java
new file mode 100644
index 0000000..01e4783
--- /dev/null
+++ b/jdk/test/java/awt/Window/WindowDeadlockTest/WindowDeadlockTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2017, 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 8176490
+ * @summary Tests that there is no hang or deadlock when the visibility
+ *      of parent and child windows is changed.
+ * @library ../../regtesthelpers
+ * @build Util
+ * @run main/timeout=20 WindowDeadlockTest
+ */
+
+import java.awt.Dialog;
+import java.awt.Frame;
+import java.awt.Robot;
+
+import test.java.awt.regtesthelpers.Util;
+
+public class WindowDeadlockTest {
+    public static void main(String[] args) throws Exception {
+        Robot robot = Util.createRobot();
+
+        Frame main = new Frame("Main");
+        main.setBounds(0, 0, 200, 100);
+        main.setVisible(true);
+
+        Dialog first = new Dialog(main, "First");
+        first.setBounds(250, 0, 200, 100);
+        first.setVisible(true);
+
+        Dialog second = new Dialog(first, "Second");
+        second.setBounds(0, 150, 200, 100);
+        second.setVisible(true);
+
+        Util.waitForIdle(robot);
+        robot.delay(2000);
+
+        Dialog third = new Dialog(first, "Third", false);
+        third.setBounds(250, 150, 200, 100);
+        third.setVisible(true);
+        first.setVisible(false); // the hang takes place here
+
+        Util.waitForIdle(robot);
+        robot.delay(2000);
+
+        third.dispose();
+        second.dispose();
+        first.dispose();
+        main.dispose();
+    }
+}
diff --git a/jdk/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java b/jdk/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java
index 18b7012..eaa1364 100644
--- a/jdk/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java
+++ b/jdk/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java
@@ -23,7 +23,7 @@
 
 /*
   @test
-  @bug 8081787 8136763
+  @bug 8081787 8136763 8160941
   @author Mikhail Cherkasov
   @run main/manual MacOsXFileAndMultipleFileCopingTest
 */
diff --git a/jdk/test/java/awt/event/KeyEvent/KeyChar/KeyCharTest.java b/jdk/test/java/awt/event/KeyEvent/KeyChar/KeyCharTest.java
index a482cea..dd50483 100644
--- a/jdk/test/java/awt/event/KeyEvent/KeyChar/KeyCharTest.java
+++ b/jdk/test/java/awt/event/KeyEvent/KeyChar/KeyCharTest.java
@@ -32,7 +32,7 @@
 
 /*
  * @test
- * @bug 8022401
+ * @bug 8022401 8160623
  * @summary Wrong key char
  * @author Alexandr Scherbatiy
  * @run main KeyCharTest
diff --git a/jdk/test/java/awt/font/TextLayout/DiacriticsDrawingTest.java b/jdk/test/java/awt/font/TextLayout/DiacriticsDrawingTest.java
new file mode 100644
index 0000000..c58bee3
--- /dev/null
+++ b/jdk/test/java/awt/font/TextLayout/DiacriticsDrawingTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2017 JetBrains s.r.o.
+ * 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 8170552
+ * @summary verify enabling text layout for complex text on macOS
+ */
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.image.BufferedImage;
+
+public class DiacriticsDrawingTest {
+    private static final Font FONT = new Font("Menlo", Font.PLAIN, 12);
+    private static final int IMAGE_WIDTH = 20;
+    private static final int IMAGE_HEIGHT = 20;
+    private static final int TEXT_X = 5;
+    private static final int TEXT_Y = 15;
+
+    public static void main(String[] args) {
+        BufferedImage composed = drawString("\u00e1"); // latin small letter a with acute
+        BufferedImage decomposed = drawString("a\u0301"); // same letter in decomposed form
+
+        if (!imagesAreEqual(composed, decomposed)) {
+            throw new RuntimeException("Text rendering is supposed to be the same");
+        }
+    }
+
+    private static BufferedImage drawString(String text) {
+        BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        Graphics g = image.createGraphics();
+        g.setColor(Color.white);
+        g.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
+        g.setColor(Color.black);
+        g.setFont(FONT);
+        g.drawString(text, TEXT_X, TEXT_Y);
+        g.dispose();
+        return image;
+    }
+
+    private static boolean imagesAreEqual(BufferedImage i1, BufferedImage i2) {
+        if (i1.getWidth() != i2.getWidth() || i1.getHeight() != i2.getHeight()) return false;
+        for (int i = 0; i < i1.getWidth(); i++) {
+            for (int j = 0; j < i1.getHeight(); j++) {
+                if (i1.getRGB(i, j) != i2.getRGB(i, j)) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+}
diff --git a/jdk/test/java/awt/geom/AffineTransform/InvalidTransformParameterTest.java b/jdk/test/java/awt/geom/AffineTransform/InvalidTransformParameterTest.java
new file mode 100644
index 0000000..f8c36ec
--- /dev/null
+++ b/jdk/test/java/awt/geom/AffineTransform/InvalidTransformParameterTest.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8158356
+ * @summary Test AffineTransform transformations do not result in SIGSEGV
+ * if NaN or infinity parameter is passed as argument.
+ * @run main InvalidTransformParameterTest
+ */
+
+import java.awt.geom.AffineTransform;
+import java.awt.image.AffineTransformOp;
+import java.awt.image.BufferedImage;
+import java.awt.image.ImagingOpException;
+import java.awt.Point;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferByte;
+import java.awt.image.PixelInterleavedSampleModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.RasterOp;
+import java.awt.image.SampleModel;
+
+public class InvalidTransformParameterTest {
+
+    public static void main(String[] args) {
+        int count = 0;
+        final int testScenarios = 12;
+        double NaNArg = 0.0 / 0.0;
+        double positiveInfArg = 1.0 / 0.0;
+        double negativeInfArg = -1.0 / 0.0;
+
+        BufferedImage img = new BufferedImage(5, 5, BufferedImage.TYPE_INT_ARGB);
+
+        AffineTransform[] inputTransforms = new AffineTransform[testScenarios];
+
+        for (int i = 0; i < inputTransforms.length; i++) {
+            inputTransforms[i] = new AffineTransform();
+        }
+
+        inputTransforms[0].rotate(NaNArg, img.getWidth()/2, img.getHeight()/2);
+        inputTransforms[1].translate(NaNArg, NaNArg);
+        inputTransforms[2].scale(NaNArg, NaNArg);
+        inputTransforms[3].shear(NaNArg, NaNArg);
+
+        inputTransforms[4].rotate(positiveInfArg, img.getWidth()/2, img.getHeight()/2);
+        inputTransforms[5].translate(positiveInfArg, positiveInfArg);
+        inputTransforms[6].scale(positiveInfArg, positiveInfArg);
+        inputTransforms[7].shear(positiveInfArg, positiveInfArg);
+
+        inputTransforms[8].rotate(negativeInfArg, img.getWidth()/2, img.getHeight()/2);
+        inputTransforms[9].translate(negativeInfArg, negativeInfArg);
+        inputTransforms[10].scale(negativeInfArg, negativeInfArg);
+        inputTransforms[11].shear(negativeInfArg, negativeInfArg);
+
+        // Test BufferedImage AffineTransform ---------------------------------
+
+        for (int i = 0; i < inputTransforms.length; i++) {
+            try {
+                testImageTransform(img, inputTransforms[i]);
+            } catch (ImagingOpException ex) {
+                count++;
+            }
+        }
+
+        if (count != testScenarios) {
+            throw new RuntimeException("Test failed. All test scenarios did not"
+                                       + " result in exception as expected.");
+        }
+
+        // Test Raster AffineTransform ---------------------------------
+
+        count = 0;
+        int[] bandOffsets = {0};
+        Point location = new Point(0, 0);
+        DataBuffer db = new DataBufferByte(10 * 10);
+        SampleModel sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,
+                                                         10, 10, 1, 10,
+                                                         bandOffsets);
+
+        Raster src = Raster.createRaster(sm, db, location);
+        WritableRaster dst = Raster.createWritableRaster(sm, db, location);
+
+        for (int i = 0; i < inputTransforms.length; i++) {
+            try {
+                testRasterTransform(src, dst, inputTransforms[i]);
+            } catch (ImagingOpException ex) {
+                count++;
+            }
+        }
+
+        if (count != testScenarios) {
+            throw new RuntimeException("Test failed. All test scenarios did not"
+                                       + " result in exception as expected.");
+        }
+    }
+
+    public static BufferedImage testImageTransform(BufferedImage image,
+                                                   AffineTransform transform) {
+        AffineTransformOp op =
+                new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
+
+        BufferedImage transformedImage = new BufferedImage(image.getWidth(),
+                                                           image.getHeight(),
+                                                           image.getType());
+
+        return op.filter(image, transformedImage);
+    }
+
+    public static Raster testRasterTransform(Raster src, WritableRaster dst,
+                                             AffineTransform transform) {
+        AffineTransformOp op =
+                new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
+
+        return op.filter(src, dst);
+    }
+}
+
diff --git a/jdk/test/java/awt/print/PageFormat/WrongPaperPrintingTest.java b/jdk/test/java/awt/print/PageFormat/WrongPaperPrintingTest.java
new file mode 100644
index 0000000..2299015
--- /dev/null
+++ b/jdk/test/java/awt/print/PageFormat/WrongPaperPrintingTest.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2017, 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 8167102
+   @summary PrintRequestAttributeSet breaks page size set using PageFormat
+   @ignore Exclude the test until 8167102 is resolved by a new reassessed fix
+   @run main/manual WrongPaperPrintingTest
+ */
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.FlowLayout;
+import java.awt.Graphics;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.print.PageFormat;
+import java.awt.print.Paper;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.Size2DSyntax;
+import javax.print.attribute.standard.Chromaticity;
+import javax.print.attribute.standard.MediaSize;
+import javax.print.attribute.standard.MediaSizeName;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+import javax.swing.Timer;
+import javax.swing.WindowConstants;
+
+public class WrongPaperPrintingTest implements Printable {
+    private static final CountDownLatch testEndedSignal = new CountDownLatch(1);
+    private static final int testTimeout = 300000;
+    private static volatile String testFailureMsg;
+    private static volatile boolean testPassed;
+    private static volatile boolean testFinished;
+
+    public static void main(String[] args) {
+        SwingUtilities.invokeLater(() -> createAndShowTestDialog());
+
+        try {
+            if (!testEndedSignal.await(testTimeout, TimeUnit.MILLISECONDS)) {
+                throw new RuntimeException(String.format(
+                    "Test timeout '%d ms' elapsed.", testTimeout));
+            }
+            if (!testPassed) {
+                String failureMsg = testFailureMsg;
+                if ((failureMsg != null) && (!failureMsg.trim().isEmpty())) {
+                    throw new RuntimeException(failureMsg);
+                } else {
+                    throw new RuntimeException("Test failed.");
+                }
+            }
+        } catch (InterruptedException ie) {
+            throw new RuntimeException(ie);
+        } finally {
+            testFinished = true;
+        }
+    }
+
+    private static void doTest() {
+        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
+        aset.add(Chromaticity.MONOCHROME);
+
+        MediaSize isoA5Size = MediaSize.getMediaSizeForName(MediaSizeName.ISO_A5);
+        float[] size = isoA5Size.getSize(Size2DSyntax.INCH);
+        Paper paper = new Paper();
+        paper.setSize(size[0] * 72.0, size[1] * 72.0);
+        paper.setImageableArea(0.0, 0.0, size[0] * 72.0, size[1] * 72.0);
+        PageFormat pf = new PageFormat();
+        pf.setPaper(paper);
+
+        PrinterJob job = PrinterJob.getPrinterJob();
+        job.setPrintable(new WrongPaperPrintingTest(), job.validatePage(pf));
+        if (job.printDialog()) {
+            try {
+                job.print(aset);
+            } catch (PrinterException pe) {
+                throw new RuntimeException(pe);
+            }
+        }
+    }
+
+    private static void pass() {
+        testPassed = true;
+        testEndedSignal.countDown();
+    }
+
+    private static void fail(String failureMsg) {
+        testFailureMsg = failureMsg;
+        testPassed = false;
+        testEndedSignal.countDown();
+    }
+
+    private static String convertMillisToTimeStr(int millis) {
+        if (millis < 0) {
+            return "00:00:00";
+        }
+        int hours = millis / 3600000;
+        int minutes = (millis - hours * 3600000) / 60000;
+        int seconds = (millis - hours * 3600000 - minutes * 60000) / 1000;
+        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
+    }
+
+    private static void createAndShowTestDialog() {
+        String description =
+            " To run this test it is required to have a virtual PDF\r\n" +
+            " printer or any other printer supporting A5 paper size.\r\n" +
+            "\r\n" +
+            " 1. Verify that NOT A5 paper size is set as default for the\r\n" +
+            " printer to be used.\r\n" +
+            " 2. Click on \"Start Test\" button.\r\n" +
+            " 3. In the shown print dialog select the printer and click\r\n" +
+            " on \"Print\" button.\r\n" +
+            " 4. Verify that a page with a drawn rectangle is printed on\r\n" +
+            " a paper of A5 size which is (5.8 x 8.3 in) or\r\n" +
+            " (148 x 210 mm).\r\n" +
+            "\r\n" +
+            " If the printed page size is correct, click on \"PASS\"\r\n" +
+            " button, otherwise click on \"FAIL\" button.";
+
+        final JDialog dialog = new JDialog();
+        dialog.setTitle("WrongPaperPrintingTest");
+        dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
+        dialog.addWindowListener(new WindowAdapter() {
+            @Override
+            public void windowClosing(WindowEvent e) {
+                dialog.dispose();
+                fail("Main dialog was closed.");
+            }
+        });
+
+        final JLabel testTimeoutLabel = new JLabel(String.format(
+            "Test timeout: %s", convertMillisToTimeStr(testTimeout)));
+        final long startTime = System.currentTimeMillis();
+        final Timer timer = new Timer(0, null);
+        timer.setDelay(1000);
+        timer.addActionListener((e) -> {
+            int leftTime = testTimeout - (int)(System.currentTimeMillis() - startTime);
+            if ((leftTime < 0) || testFinished) {
+                timer.stop();
+                dialog.dispose();
+            }
+            testTimeoutLabel.setText(String.format(
+                "Test timeout: %s", convertMillisToTimeStr(leftTime)));
+        });
+        timer.start();
+
+        JTextArea textArea = new JTextArea(description);
+        textArea.setEditable(false);
+
+        final JButton testButton = new JButton("Start Test");
+        final JButton passButton = new JButton("PASS");
+        final JButton failButton = new JButton("FAIL");
+        testButton.addActionListener((e) -> {
+            testButton.setEnabled(false);
+            new Thread(() -> {
+                try {
+                    doTest();
+
+                    SwingUtilities.invokeLater(() -> {
+                        passButton.setEnabled(true);
+                        failButton.setEnabled(true);
+                    });
+                } catch (Throwable t) {
+                    t.printStackTrace();
+                    dialog.dispose();
+                    fail("Exception occurred in a thread executing the test.");
+                }
+            }).start();
+        });
+        passButton.setEnabled(false);
+        passButton.addActionListener((e) -> {
+            dialog.dispose();
+            pass();
+        });
+        failButton.setEnabled(false);
+        failButton.addActionListener((e) -> {
+            dialog.dispose();
+            fail("Size of a printed page is wrong.");
+        });
+
+        JPanel mainPanel = new JPanel(new BorderLayout());
+        JPanel labelPanel = new JPanel(new FlowLayout());
+        labelPanel.add(testTimeoutLabel);
+        mainPanel.add(labelPanel, BorderLayout.NORTH);
+        mainPanel.add(textArea, BorderLayout.CENTER);
+        JPanel buttonPanel = new JPanel(new FlowLayout());
+        buttonPanel.add(testButton);
+        buttonPanel.add(passButton);
+        buttonPanel.add(failButton);
+        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
+        dialog.add(mainPanel);
+
+        dialog.pack();
+        dialog.setVisible(true);
+    }
+
+    @Override
+    public int print(Graphics g, PageFormat pf, int pageIndex)
+        throws PrinterException {
+        if (pageIndex == 0) {
+            g.setColor(Color.RED);
+            g.drawRect((int)pf.getImageableX(), (int)pf.getImageableY(),
+                (int)pf.getImageableWidth(), (int)pf.getImageableHeight());
+            return Printable.PAGE_EXISTS;
+        } else {
+            return Printable.NO_SUCH_PAGE;
+        }
+    }
+}
diff --git a/jdk/test/java/awt/print/PrinterJob/DlgAttrsBug.java b/jdk/test/java/awt/print/PrinterJob/DlgAttrsBug.java
new file mode 100644
index 0000000..dc31ffd
--- /dev/null
+++ b/jdk/test/java/awt/print/PrinterJob/DlgAttrsBug.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8061258
+ * @summary  PrinterJob's native Print Dialog does not reflect
+ *           specified Copies or Page Ranges
+ * @run main/manual DlgAttrsBug
+ */
+import java.awt.BorderLayout;
+import java.awt.FlowLayout;
+import java.awt.Graphics;
+import java.awt.print.PageFormat;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.standard.Copies;
+import javax.print.attribute.standard.PageRanges;
+import javax.print.attribute.standard.DialogTypeSelection;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+
+
+public class DlgAttrsBug implements Printable {
+    private static Thread mainThread;
+    private static boolean testPassed;
+    private static boolean testGeneratedInterrupt;
+
+    public static void main(String[] args)  throws Exception {
+        SwingUtilities.invokeAndWait(() -> {
+            doTest(DlgAttrsBug::printTest);
+        });
+        mainThread = Thread.currentThread();
+        try {
+            Thread.sleep(30000);
+        } catch (InterruptedException e) {
+            if (!testPassed && testGeneratedInterrupt) {
+                throw new RuntimeException("Print Dialog does not " +
+                          "reflect Copies or Page Ranges");
+            }
+        }
+        if (!testGeneratedInterrupt) {
+            throw new RuntimeException("user has not executed the test");
+        }
+    }
+
+    private static void printTest() {
+        PrinterJob job = PrinterJob.getPrinterJob();
+        if (job.getPrintService() == null) {
+            System.out.println("No printers. Test cannot continue");
+            return;
+        }
+        job.setPrintable(new DlgAttrsBug());
+        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
+        aset.add(new Copies(5));
+        aset.add(new PageRanges(3,4));
+        aset.add(DialogTypeSelection.NATIVE);
+        job.printDialog(aset);
+    }
+
+    public static synchronized void pass() {
+        testPassed = true;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    public static synchronized void fail() {
+        testPassed = false;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    private static void doTest(Runnable action) {
+        String description
+                = " Visual inspection of print dialog is required.\n"
+                + " A print dialog will be shown.\n "
+                + " Please verify Copies 5 is selected.\n"
+                + " Also verify, Page Range is selected with "
+                + " from page 3 and to Page 4.\n"
+                + " If ok, press PASS else press FAIL";
+
+        final JDialog dialog = new JDialog();
+        dialog.setTitle("printSelectionTest");
+        JTextArea textArea = new JTextArea(description);
+        textArea.setEditable(false);
+        final JButton testButton = new JButton("Start Test");
+        final JButton passButton = new JButton("PASS");
+        passButton.setEnabled(false);
+        passButton.addActionListener((e) -> {
+            dialog.dispose();
+            pass();
+        });
+        final JButton failButton = new JButton("FAIL");
+        failButton.setEnabled(false);
+        failButton.addActionListener((e) -> {
+            dialog.dispose();
+            fail();
+        });
+        testButton.addActionListener((e) -> {
+            testButton.setEnabled(false);
+            action.run();
+            passButton.setEnabled(true);
+            failButton.setEnabled(true);
+        });
+        JPanel mainPanel = new JPanel(new BorderLayout());
+        mainPanel.add(textArea, BorderLayout.CENTER);
+        JPanel buttonPanel = new JPanel(new FlowLayout());
+        buttonPanel.add(testButton);
+        buttonPanel.add(passButton);
+        buttonPanel.add(failButton);
+        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
+        dialog.add(mainPanel);
+        dialog.pack();
+        dialog.setVisible(true);
+    }
+
+    public int print(Graphics g, PageFormat pf, int pi)
+            throws PrinterException {
+        System.out.println("pi = " + pi);
+        if (pi >= 5) {
+            return NO_SUCH_PAGE;
+        }
+        g.drawString("Page : " + (pi+1), 200, 200);
+        return PAGE_EXISTS;
+    }
+
+}
diff --git a/jdk/test/java/awt/print/PrinterJob/LinearGradientPrintingTest.java b/jdk/test/java/awt/print/PrinterJob/LinearGradientPrintingTest.java
new file mode 100644
index 0000000..ab1ab17
--- /dev/null
+++ b/jdk/test/java/awt/print/PrinterJob/LinearGradientPrintingTest.java
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8162796
+ * @summary  Verifies if LinearGradientPaint is printed in osx
+ * @run main/manual LinearGradientPrintingTest
+ */
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.LinearGradientPaint;
+import java.awt.Shape;
+import java.awt.event.ActionEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.print.PageFormat;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+import javax.swing.AbstractAction;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
+
+public class LinearGradientPrintingTest extends Component implements Printable {
+    private static Thread mainThread;
+    private static boolean testPassed;
+    private static boolean testGeneratedInterrupt;
+    private static JFrame f = null;
+
+    public static void main(String[] args) {
+        SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+                //createUI();
+                doTest(LinearGradientPrintingTest::createUI);
+            }
+        });
+        mainThread = Thread.currentThread();
+        try {
+            Thread.sleep(120000);
+        } catch (InterruptedException e) {
+            if (!testPassed && testGeneratedInterrupt) {
+                throw new RuntimeException("LinearGradientPaint did not print");
+            }
+        }
+        if (!testGeneratedInterrupt) {
+            throw new RuntimeException("user has not executed the test");
+        }
+    }
+
+    public static void createUI() {
+        f = new JFrame("LinearGradient Printing Test");
+        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+        final LinearGradientPrintingTest gpt = new LinearGradientPrintingTest();
+        Container c = f.getContentPane();
+        c.add(BorderLayout.CENTER, gpt);
+
+        final JButton print = new JButton("Print");
+        print.addActionListener(new AbstractAction() {
+            @Override
+            public void actionPerformed(ActionEvent e) {
+                PrinterJob job = PrinterJob.getPrinterJob();
+                job.setPrintable(gpt);
+                final boolean doPrint = job.printDialog();
+                if (doPrint) {
+                    try {
+                        job.print();
+                    } catch (PrinterException ex) {
+                        throw new RuntimeException(ex);
+                    }
+                }
+            }
+        });
+        c.add(print, BorderLayout.SOUTH);
+
+        f.pack();
+        f.setVisible(true);
+    }
+
+    public Dimension getPreferredSize() {
+        return new Dimension(500,500);
+    }
+
+    public void paint(Graphics g) {
+        doPaint((Graphics2D)g);
+    }
+
+    public int print( Graphics graphics, PageFormat format, int index ) {
+        Graphics2D g2d = (Graphics2D)graphics;
+        g2d.translate(format.getImageableX(), format.getImageableY());
+        doPaint(g2d);
+        return index == 0 ? PAGE_EXISTS : NO_SUCH_PAGE;
+    }
+
+    static final float DIM = 100;
+    public void doPaint(Graphics2D g2d) {
+
+        g2d.translate(DIM*0.2, DIM*0.2);
+        Shape s = new Rectangle2D.Float(0, 0, DIM*2, DIM*2);
+        Point2D.Double p1 = new Point2D.Double(0.0, 0.0);
+        Point2D.Double p2 = new Point2D.Double(DIM/2.0, DIM/2.0);
+
+        // LinearGradientPaint
+        //g2d.translate(DIM*2.2, 0);
+        Color colors[] =  { Color.red, Color.blue} ;
+        float fractions[]  = { 0.0f, 1.0f };
+
+        LinearGradientPaint lgp =
+           new LinearGradientPaint(p1, p2, fractions, colors,
+              LinearGradientPaint.CycleMethod.NO_CYCLE);
+        g2d.setPaint(lgp);
+        g2d.fill(s);
+
+        g2d.translate(DIM*2.2, 0);
+        Color colors1[] =  { Color.red, Color.blue, Color.green, Color.white} ;
+        float fractions1[]  = { 0.0f, 0.3f, 0.6f, 1.0f };
+
+        LinearGradientPaint lgp1 =
+           new LinearGradientPaint(p1, p2, fractions1, colors1,
+              LinearGradientPaint.CycleMethod.REFLECT);
+        g2d.setPaint(lgp1);
+        g2d.fill(s);
+
+        g2d.translate(-DIM*2.2, DIM*2.2);
+        Color colors2[] =  { Color.red, Color.blue, Color.green, Color.white} ;
+        float fractions2[]  = { 0.0f, 0.3f, 0.6f, 1.0f };
+
+        LinearGradientPaint lgp2 =
+           new LinearGradientPaint(p1, p2, fractions2, colors2,
+              LinearGradientPaint.CycleMethod.REPEAT);
+        g2d.setPaint(lgp2);
+        g2d.fill(s);
+    }
+
+    public static synchronized void pass() {
+        testPassed = true;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    public static synchronized void fail() {
+        testPassed = false;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    private static void doTest(Runnable action) {
+        String description
+                = " A LinearGradientPaint graphics will be shown on console.\n"
+                + " The same graphics is sent to printer.\n"
+                + " Please verify if LinearGradientPaint shading is printed.\n"
+                + " If none is printed, press FAIL else press PASS";
+
+        final JDialog dialog = new JDialog();
+        dialog.setTitle("printSelectionTest");
+        JTextArea textArea = new JTextArea(description);
+        textArea.setEditable(false);
+        final JButton testButton = new JButton("Start Test");
+        final JButton passButton = new JButton("PASS");
+        passButton.setEnabled(false);
+        passButton.addActionListener((e) -> {
+            f.dispose();
+            dialog.dispose();
+            pass();
+        });
+        final JButton failButton = new JButton("FAIL");
+        failButton.setEnabled(false);
+        failButton.addActionListener((e) -> {
+            f.dispose();
+            dialog.dispose();
+            fail();
+        });
+        testButton.addActionListener((e) -> {
+            testButton.setEnabled(false);
+            action.run();
+            passButton.setEnabled(true);
+            failButton.setEnabled(true);
+        });
+        JPanel mainPanel = new JPanel(new BorderLayout());
+        mainPanel.add(textArea, BorderLayout.CENTER);
+        JPanel buttonPanel = new JPanel(new FlowLayout());
+        buttonPanel.add(testButton);
+        buttonPanel.add(passButton);
+        buttonPanel.add(failButton);
+        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
+        dialog.add(mainPanel);
+
+        dialog.pack();
+        dialog.setVisible(true);
+        dialog.addWindowListener(new WindowAdapter() {
+           @Override
+            public void windowClosing(WindowEvent e) {
+                System.out.println("main dialog closing");
+                testGeneratedInterrupt = false;
+                mainThread.interrupt();
+            }
+        });
+    }
+
+}
diff --git a/jdk/test/java/awt/print/PrinterJob/PageDlgApp.java b/jdk/test/java/awt/print/PrinterJob/PageDlgApp.java
new file mode 100644
index 0000000..e07e8ff
--- /dev/null
+++ b/jdk/test/java/awt/print/PrinterJob/PageDlgApp.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.awt.Component;
+import java.awt.print.PrinterJob;
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.standard.DialogTypeSelection;
+import javax.swing.JOptionPane;
+import javax.swing.SwingUtilities;
+
+/**
+ * @test
+ * @bug 8067059
+ * @run main/manual PageDlgApp
+ * @summary Test if cancelling dialog returns null when
+ *          PrinterJob.pageDialog() with DialogSelectionType.NATIVE is called
+ */
+public class PageDlgApp {
+
+    public static void main(String[] args) throws Exception {
+
+        String[] instructions =
+         {
+             "Visual inspection of the dialog is needed. ",
+             "It should be a Printer Job Setup Dialog",
+             "Do nothing except Cancel",
+             "You must NOT press OK",
+         };
+        SwingUtilities.invokeAndWait(() -> {
+            JOptionPane.showMessageDialog(
+                    (Component) null,
+                    instructions,
+                    "information", JOptionPane.INFORMATION_MESSAGE);
+        });
+        PrinterJob pj = PrinterJob.getPrinterJob();
+        PrintRequestAttributeSet pSet = new HashPrintRequestAttributeSet();
+        pSet.add(DialogTypeSelection.NATIVE);
+        if ((pj.pageDialog(pSet)) != null) {
+            throw
+            new RuntimeException("PrinterJob.pageDialog(PrintRequestAttributeSet)"
+                        + " does not return null when dialog is cancelled");
+        }
+    }
+}
+
diff --git a/jdk/test/java/awt/print/PrinterJob/PageDlgStackOverflowTest.java b/jdk/test/java/awt/print/PrinterJob/PageDlgStackOverflowTest.java
new file mode 100644
index 0000000..ffe695d
--- /dev/null
+++ b/jdk/test/java/awt/print/PrinterJob/PageDlgStackOverflowTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.awt.print.PrinterJob;
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.standard.DialogTypeSelection;
+
+/**
+ * @test
+ * @bug 8039412
+ * @run main/manual PageDlgStackOverflowTest
+ * @summary Calling pageDialog() after printDialog with
+ *          DialogTypeSelection.NATIVE should not result in StackOverflowError
+ */
+public class PageDlgStackOverflowTest {
+
+    public static void main(String args[]) {
+        PrinterJob job = PrinterJob.getPrinterJob();
+        if (job == null) {
+            return;
+        }
+        PrintRequestAttributeSet pSet =
+             new HashPrintRequestAttributeSet();
+        pSet.add(DialogTypeSelection.NATIVE);
+        job.printDialog(pSet);
+        try {
+            job.pageDialog(pSet);
+        } catch (StackOverflowError e) {
+            throw new RuntimeException("StackOverflowError is thrown");
+        }
+    }
+}
+
diff --git a/jdk/test/java/awt/print/PrinterJob/PrintAttributeUpdateTest.java b/jdk/test/java/awt/print/PrinterJob/PrintAttributeUpdateTest.java
new file mode 100644
index 0000000..e6be546
--- /dev/null
+++ b/jdk/test/java/awt/print/PrinterJob/PrintAttributeUpdateTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+  @test
+  @bug 8042713 8170578
+  @summary  Print Dialog does not update attribute set with page range
+  @run main/manual PrintAttributeUpdateTest
+ */
+import java.awt.Component;
+import java.awt.Graphics;
+import java.awt.print.PageFormat;
+import java.awt.print.Pageable;
+import java.awt.print.Printable;
+import java.awt.print.PrinterJob;
+import javax.print.PrintService;
+import javax.print.attribute.Attribute;
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.standard.DialogTypeSelection;
+import javax.print.attribute.standard.PageRanges;
+import javax.swing.JOptionPane;
+import javax.swing.SwingUtilities;
+
+public class PrintAttributeUpdateTest implements Pageable, Printable {
+
+    public static void main(String args[]) throws Exception {
+        String[] instructions
+                = {
+                    "Select Pages Range From instead of All in print dialog. ",
+                    "Then select Print"
+                };
+        SwingUtilities.invokeAndWait(() -> {
+            JOptionPane.showMessageDialog((Component) null,
+                    instructions, "Instructions",
+                    JOptionPane.INFORMATION_MESSAGE);
+        });
+        HashPrintRequestAttributeSet as = new HashPrintRequestAttributeSet();
+        PrinterJob j = PrinterJob.getPrinterJob();
+        j.setPageable(new PrintAttributeUpdateTest());
+        as.add(DialogTypeSelection.NATIVE);
+        j.printDialog(as);
+        if (as.containsKey(PageRanges.class) == false) {
+            throw new RuntimeException("Print Dialog did not update "
+                    + " attribute set with page range");
+        }
+        Attribute attrs[] = as.toArray();
+        for (int i = 0; i < attrs.length; i++) {
+            System.out.println("attr " + attrs[i]);
+        }
+        j.print(as);
+    }
+
+    public int getNumberOfPages() {
+        return UNKNOWN_NUMBER_OF_PAGES;
+    }
+
+    public PageFormat getPageFormat(int pageIndex) {
+        PageFormat pf = new PageFormat();
+        return pf;
+    }
+
+    public Printable getPrintable(int pageIndex) {
+        return this;
+    }
+
+    public int print(Graphics g, PageFormat pgFmt, int pi) {
+        g.drawString("Page : " + (pi + 1), 200, 200);
+
+        return PAGE_EXISTS;
+    }
+
+}
diff --git a/jdk/test/java/awt/print/PrinterJob/RadialGradientPrintingTest.java b/jdk/test/java/awt/print/PrinterJob/RadialGradientPrintingTest.java
new file mode 100644
index 0000000..61c9fae
--- /dev/null
+++ b/jdk/test/java/awt/print/PrinterJob/RadialGradientPrintingTest.java
@@ -0,0 +1,234 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8162796
+ * @summary  Verifies if RadialGradientPaint is printed in osx
+ * @run main/manual RadialGradientPrintingTest
+ */
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RadialGradientPaint;
+import java.awt.Shape;
+import java.awt.event.ActionEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.print.PageFormat;
+import java.awt.print.Printable;
+import static java.awt.print.Printable.NO_SUCH_PAGE;
+import static java.awt.print.Printable.PAGE_EXISTS;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+import javax.swing.AbstractAction;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
+
+public class RadialGradientPrintingTest extends Component implements Printable {
+    private static Thread mainThread;
+    private static boolean testPassed;
+    private static boolean testGeneratedInterrupt;
+    private static JFrame f = null;
+
+    public static void main(String[] args) {
+        SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+                //createUI();
+                doTest(RadialGradientPrintingTest::createUI);
+            }
+        });
+        mainThread = Thread.currentThread();
+        try {
+            Thread.sleep(120000);
+        } catch (InterruptedException e) {
+            if (!testPassed && testGeneratedInterrupt) {
+                throw new RuntimeException("LinearGradientPaint did not print");
+            }
+        }
+        if (!testGeneratedInterrupt) {
+            throw new RuntimeException("user has not executed the test");
+        }
+    }
+
+    public static void createUI() {
+        f = new JFrame("RadialGradient Printing Test");
+        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+        final RadialGradientPrintingTest gpt = new RadialGradientPrintingTest();
+        Container c = f.getContentPane();
+        c.add(BorderLayout.CENTER, gpt);
+
+        final JButton print = new JButton("Print");
+        print.addActionListener(new AbstractAction() {
+            @Override
+            public void actionPerformed(ActionEvent e) {
+                PrinterJob job = PrinterJob.getPrinterJob();
+                job.setPrintable(gpt);
+                final boolean doPrint = job.printDialog();
+                if (doPrint) {
+                    try {
+                        job.print();
+                    } catch (PrinterException ex) {
+                        throw new RuntimeException(ex);
+                    }
+                }
+            }
+        });
+        c.add(print, BorderLayout.SOUTH);
+
+        f.pack();
+        f.setVisible(true);
+    }
+
+    public Dimension getPreferredSize() {
+        return new Dimension(500,500);
+    }
+
+    public void paint(Graphics g) {
+        doPaint((Graphics2D)g);
+    }
+
+    public int print( Graphics graphics, PageFormat format, int index ) {
+        Graphics2D g2d = (Graphics2D)graphics;
+        g2d.translate(format.getImageableX(), format.getImageableY());
+        doPaint(g2d);
+        return index == 0 ? PAGE_EXISTS : NO_SUCH_PAGE;
+    }
+
+    static final float DIM = 100;
+    public void doPaint(Graphics2D g2d) {
+
+        g2d.translate(DIM*0.2, DIM*0.2);
+        Shape s = new Rectangle2D.Float(0, 0, DIM*2, DIM*2);
+
+        // RadialGradientPaint
+        Point2D centre = new Point2D.Float(DIM/2.0f, DIM/2.0f);
+        float radius = DIM/2.0f;
+        Point2D focus = new Point2D.Float(DIM/3.0f, DIM/3.0f);
+        float stops[] = {0.0f, 1.0f};
+        Color colors[] =  { Color.red, Color.white} ;
+
+        RadialGradientPaint rgp =
+           new RadialGradientPaint(centre, radius, focus, stops, colors,
+              RadialGradientPaint.CycleMethod.NO_CYCLE);
+        g2d.setPaint(rgp);
+        g2d.fill(s);
+
+        g2d.translate(DIM*2.2, 0);
+        Color colors1[] =  { Color.red, Color.blue, Color.green} ;
+        float stops1[] = {0.0f, 0.5f, 1.0f};
+        RadialGradientPaint rgp1 =
+           new RadialGradientPaint(centre, radius, focus, stops1, colors1,
+              RadialGradientPaint.CycleMethod.REFLECT);
+        g2d.setPaint(rgp1);
+        g2d.fill(s);
+
+        g2d.translate(-DIM*2.2, DIM*2.2);
+        Color colors2[] =  { Color.red, Color.blue, Color.green, Color.white} ;
+        float stops2[] = {0.0f, 0.3f, 0.6f, 1.0f};
+        RadialGradientPaint rgp2 =
+           new RadialGradientPaint(centre, radius, focus, stops2, colors2,
+              RadialGradientPaint.CycleMethod.REPEAT);
+        g2d.setPaint(rgp2);
+        g2d.fill(s);
+
+    }
+
+    public static synchronized void pass() {
+        testPassed = true;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    public static synchronized void fail() {
+        testPassed = false;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    private static void doTest(Runnable action) {
+        String description
+                = " A RadialGradientPaint graphics will be shown on console.\n"
+                + " The same graphics is sent to printer.\n"
+                + " Please verify if RadialGradientPaint shading is printed.\n"
+                + " If none is printed, press FAIL else press PASS";
+
+        final JDialog dialog = new JDialog();
+        dialog.setTitle("printSelectionTest");
+        JTextArea textArea = new JTextArea(description);
+        textArea.setEditable(false);
+        final JButton testButton = new JButton("Start Test");
+        final JButton passButton = new JButton("PASS");
+        passButton.setEnabled(false);
+        passButton.addActionListener((e) -> {
+            f.dispose();
+            dialog.dispose();
+            pass();
+        });
+        final JButton failButton = new JButton("FAIL");
+        failButton.setEnabled(false);
+        failButton.addActionListener((e) -> {
+            f.dispose();
+            dialog.dispose();
+            fail();
+        });
+        testButton.addActionListener((e) -> {
+            testButton.setEnabled(false);
+            action.run();
+            passButton.setEnabled(true);
+            failButton.setEnabled(true);
+        });
+        JPanel mainPanel = new JPanel(new BorderLayout());
+        mainPanel.add(textArea, BorderLayout.CENTER);
+        JPanel buttonPanel = new JPanel(new FlowLayout());
+        buttonPanel.add(testButton);
+        buttonPanel.add(passButton);
+        buttonPanel.add(failButton);
+        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
+        dialog.add(mainPanel);
+
+        dialog.pack();
+        dialog.setVisible(true);
+        dialog.addWindowListener(new WindowAdapter() {
+           @Override
+            public void windowClosing(WindowEvent e) {
+                System.out.println("main dialog closing");
+                testGeneratedInterrupt = false;
+                mainThread.interrupt();
+            }
+        });
+    }
+
+}
diff --git a/jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java b/jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java
new file mode 100644
index 0000000..a9667f6
--- /dev/null
+++ b/jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8040635
+ * @summary  Verifies if TexturePaint is printed in osx
+ * @run main/manual TexturePaintPrintingTest
+ */
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.TexturePaint;
+import java.awt.event.ActionEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.awt.print.PageFormat;
+import java.awt.print.Printable;
+import static java.awt.print.Printable.NO_SUCH_PAGE;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+import javax.swing.AbstractAction;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
+
+public class TexturePaintPrintingTest extends Component implements Printable {
+    private static void printTexture() {
+        f = new JFrame("Texture Printing Test");
+        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+        final TexturePaintPrintingTest gpt = new TexturePaintPrintingTest();
+        Container c = f.getContentPane();
+        c.add(BorderLayout.CENTER, gpt);
+
+        final JButton print = new JButton("Print");
+        print.addActionListener(new AbstractAction() {
+            @Override
+            public void actionPerformed(ActionEvent e) {
+                PrinterJob job = PrinterJob.getPrinterJob();
+                job.setPrintable(gpt);
+                final boolean doPrint = job.printDialog();
+                if (doPrint) {
+                    try {
+                        job.print();
+                    } catch (PrinterException ex) {
+                        throw new RuntimeException(ex);
+                    }
+                }
+            }
+        });
+        c.add(print, BorderLayout.SOUTH);
+
+        f.pack();
+        f.setVisible(true);
+    }
+
+    public Dimension getPreferredSize() {
+        return new Dimension(500,500);
+    }
+
+    public void paint(Graphics g) {
+        doPaint((Graphics2D)g);
+    }
+
+    public int print( Graphics graphics, PageFormat format, int index ) {
+        Graphics2D g2d = (Graphics2D)graphics;
+        g2d.translate(format.getImageableX(), format.getImageableY());
+        doPaint(g2d);
+        return index == 0 ? PAGE_EXISTS : NO_SUCH_PAGE;
+    }
+
+    static final float DIM = 100;
+    public void doPaint(Graphics2D g2d) {
+        BufferedImage patternImage = new BufferedImage(2,2,BufferedImage.TYPE_INT_ARGB);
+                Graphics gImage = patternImage.getGraphics();
+                gImage.setColor(Color.WHITE);
+                gImage.drawLine(0,1,1,0);
+                gImage.setColor(Color.BLACK);
+                gImage.drawLine(0,0,1,1);
+                gImage.dispose();
+
+                Rectangle2D.Double shape = new Rectangle2D.Double(0,0,DIM*6/5, DIM*8/5);
+                g2d.setPaint(new TexturePaint(patternImage, new Rectangle2D.Double(0,0,
+                        DIM*6/50, DIM*8/50)));
+                g2d.fill(shape);
+                g2d.setPaint(Color.BLACK);
+                g2d.draw(shape);
+
+    }
+
+    public static synchronized void pass() {
+        testPassed = true;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    public static synchronized void fail() {
+        testPassed = false;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    private static Thread mainThread;
+    private static boolean testPassed;
+    private static boolean testGeneratedInterrupt;
+    private static JFrame f = null;
+
+    public static void main(String[] args) {
+        SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+                //createUI();
+                doTest(TexturePaintPrintingTest::printTexture);
+            }
+        });
+        mainThread = Thread.currentThread();
+        try {
+            Thread.sleep(120000);
+        } catch (InterruptedException e) {
+            if (!testPassed && testGeneratedInterrupt) {
+                throw new RuntimeException("TexturePaint did not print");
+            }
+        }
+        if (!testGeneratedInterrupt) {
+            throw new RuntimeException("user has not executed the test");
+        }
+    }
+
+    private static void doTest(Runnable action) {
+        String description
+                = " A TexturePaint graphics will be shown on console.\n"
+                + " The same graphics is sent to printer.\n"
+                + " Please verify if TexturePaint shading is printed.\n"
+                + " If none is printed, press FAIL else press PASS";
+
+        final JDialog dialog = new JDialog();
+        dialog.setTitle("printSelectionTest");
+        JTextArea textArea = new JTextArea(description);
+        textArea.setEditable(false);
+        final JButton testButton = new JButton("Start Test");
+        final JButton passButton = new JButton("PASS");
+        passButton.setEnabled(false);
+        passButton.addActionListener((e) -> {
+            f.dispose();
+            dialog.dispose();
+            pass();
+        });
+        final JButton failButton = new JButton("FAIL");
+        failButton.setEnabled(false);
+        failButton.addActionListener((e) -> {
+            f.dispose();
+            dialog.dispose();
+            fail();
+        });
+        testButton.addActionListener((e) -> {
+            testButton.setEnabled(false);
+            action.run();
+            passButton.setEnabled(true);
+            failButton.setEnabled(true);
+        });
+        JPanel mainPanel = new JPanel(new BorderLayout());
+        mainPanel.add(textArea, BorderLayout.CENTER);
+        JPanel buttonPanel = new JPanel(new FlowLayout());
+        buttonPanel.add(testButton);
+        buttonPanel.add(passButton);
+        buttonPanel.add(failButton);
+        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
+        dialog.add(mainPanel);
+
+        dialog.pack();
+        dialog.setVisible(true);
+        dialog.addWindowListener(new WindowAdapter() {
+           @Override
+            public void windowClosing(WindowEvent e) {
+                System.out.println("main dialog closing");
+                testGeneratedInterrupt = false;
+                mainThread.interrupt();
+            }
+        });
+    }
+}
diff --git a/jdk/test/java/beans/Introspector/8159696/UnloadClassBeanInfo.java b/jdk/test/java/beans/Introspector/8159696/UnloadClassBeanInfo.java
new file mode 100644
index 0000000..8c77b35
--- /dev/null
+++ b/jdk/test/java/beans/Introspector/8159696/UnloadClassBeanInfo.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.beans.BeanInfo;
+import java.beans.Introspector;
+import java.beans.MethodDescriptor;
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.Arrays;
+
+/**
+ * @test
+ * @bug 8159696
+ * @library /javax/swing/regtesthelpers
+ * @compile ./stub/Stub.java
+ * @run main/othervm -mx32M UnloadClassBeanInfo
+ */
+public class UnloadClassBeanInfo {
+
+    private static URLClassLoader loader;
+
+    public static void main(final String[] args) throws Exception {
+        Class cl = getStub();
+        System.out.println("cl.getClassLoader() = " + cl.getClassLoader());
+        final BeanInfo beanInfo = Introspector.getBeanInfo(cl, Object.class);
+        MethodDescriptor[] mds = beanInfo.getMethodDescriptors();
+        System.out.println("mds = " + Arrays.toString(mds));
+        loader.close();
+        loader=null;
+        cl=null;
+        Util.generateOOME();
+        mds = beanInfo.getMethodDescriptors();
+        System.out.println("mds = " + Arrays.toString(mds));
+    }
+
+    /**
+     * The Stub class is compiled by jtreg, but we want to move it so it is not
+     * on the application classpath. We want to load it through a separate
+     * classloader.
+     */
+    static Class<?> getStub() throws Exception {
+        final String testclasses = System.getProperty("test.classes");
+        final File subdir = new File(testclasses, "stub");
+        subdir.mkdir();
+
+        final Path src = Paths.get(testclasses, "Stub.class");
+        final Path dest = subdir.toPath().resolve("Stub.class");
+        Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING);
+
+        loader = new URLClassLoader(new URL[]{subdir.toURL()});
+        return Class.forName("Stub", true, loader);
+    }
+}
diff --git a/jdk/test/java/beans/Introspector/8159696/stub/Stub.java b/jdk/test/java/beans/Introspector/8159696/stub/Stub.java
new file mode 100644
index 0000000..2c093ec
--- /dev/null
+++ b/jdk/test/java/beans/Introspector/8159696/stub/Stub.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public final class Stub {
+
+    public void test() {
+
+    }
+}
diff --git a/jdk/test/java/io/CharArrayReader/OverflowInRead.java b/jdk/test/java/io/CharArrayReader/OverflowInRead.java
new file mode 100644
index 0000000..0c30e8c
--- /dev/null
+++ b/jdk/test/java/io/CharArrayReader/OverflowInRead.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8163518
+ * @summary Integer overflow when reading in large buffer
+ * @ignore This test has huge memory requirements
+ * @requires (sun.arch.data.model == "64" & os.maxMemory > 8g)
+ * @run main/othervm -Xmx8g OverflowInRead
+ */
+
+import java.io.CharArrayReader;
+
+public class OverflowInRead {
+    public static void main(String[] args) throws Exception {
+        char[] a = "_123456789_123456789_123456789_123456789"
+                .toCharArray(); // a.length > 33
+        try (CharArrayReader car = new CharArrayReader(a)) {
+            int len1 = 33;
+            char[] buf1 = new char[len1];
+            if (car.read(buf1, 0, len1) != len1)
+                throw new Exception("Expected to read " + len1 + " chars");
+
+            int len2 = Integer.MAX_VALUE - 32;
+            char[] buf2 = new char[len2];
+            int expLen2 = a.length - len1;
+            if (car.read(buf2, 0, len2) != expLen2)
+                throw new Exception("Expected to read " + expLen2 + " chars");
+        }
+    }
+}
diff --git a/jdk/test/java/io/CharArrayReader/OverflowInSkip.java b/jdk/test/java/io/CharArrayReader/OverflowInSkip.java
new file mode 100644
index 0000000..94c04a0
--- /dev/null
+++ b/jdk/test/java/io/CharArrayReader/OverflowInSkip.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8163518
+ * @summary Integer overflow when skipping a lot
+ */
+
+import java.io.CharArrayReader;
+
+public class OverflowInSkip {
+    public static void main(String[] args) throws Exception {
+        char[] a = "_123456789_123456789_123456789_123456789"
+                .toCharArray(); // a.length > 33
+        try (CharArrayReader car = new CharArrayReader(a)) {
+            long small = 33;
+            long big = Long.MAX_VALUE;
+
+            long smallSkip = car.skip(small);
+            if (smallSkip != small)
+                throw new Exception("Expected to skip " + small
+                        + " chars, but skipped " + smallSkip);
+
+            long expSkip = a.length - small;
+            long bigSkip = car.skip(big);
+            if (bigSkip != expSkip)
+                throw new Exception("Expected to skip " + expSkip
+                        + " chars, but skipped " + bigSkip);
+        }
+    }
+}
diff --git a/jdk/test/java/io/StringBufferInputStream/OverflowInRead.java b/jdk/test/java/io/StringBufferInputStream/OverflowInRead.java
new file mode 100644
index 0000000..ed5c370e
--- /dev/null
+++ b/jdk/test/java/io/StringBufferInputStream/OverflowInRead.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8163518
+ * @summary Integer overflow when reading in large buffer
+ * @ignore This test has huge memory requirements
+ * @requires (sun.arch.data.model == "64" & os.maxMemory > 4g)
+ * @run main/othervm -Xmx4g OverflowInRead
+ */
+
+import java.io.StringBufferInputStream;
+
+public class OverflowInRead {
+    public static void main(String[] args) throws Exception {
+        String s = "_123456789_123456789_123456789_123456789"; // s.length() > 33
+        try (StringBufferInputStream sbis = new StringBufferInputStream(s)) {
+            int len1 = 33;
+            byte[] buf1 = new byte[len1];
+            if (sbis.read(buf1, 0, len1) != len1)
+                throw new Exception("Expected to read " + len1 + " bytes");
+
+            int len2 = Integer.MAX_VALUE - 32;
+            byte[] buf2 = new byte[len2];
+            int expLen2 = s.length() - len1;
+            if (sbis.read(buf2, 0, len2) != expLen2)
+                throw new Exception("Expected to read " + expLen2 + " bytes");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/FindLibrary.java b/jdk/test/java/lang/ClassLoader/FindLibrary.java
new file mode 100644
index 0000000..cbb231a
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/FindLibrary.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2017, 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 8181205
+   @summary JRE fails to load/register security providers when started from UNC pathname
+*/
+
+import java.io.File;
+import java.lang.reflect.Method;
+import java.lang.reflect.Constructor;
+
+    public class FindLibrary {
+        public static void main(String[] args) throws Exception {
+            // this test is most relevant to windows. should pass silently on
+            // other OSes
+
+            Class<?> innerClazz = Class.forName("sun.misc.Launcher$ExtClassLoader");
+            Class<?>[] ctorArgTypes = {File[].class};
+
+            File tmpFile = new File(System.getProperty("java.home"));
+            File[] f = new File[1];
+            String uncFileName = "\\\\127.0.0.1\\" + tmpFile.getAbsolutePath().replace(':', '$');
+            System.out.println("Testing UNC path of :" + uncFileName);
+
+            f[0] = new File(uncFileName); // a UNC path that must exist
+            Object[] ctorArgs = {f};
+            Constructor constructor = innerClazz.getDeclaredConstructor(File[].class);
+            constructor.setAccessible(true);
+            Object o = constructor.newInstance(ctorArgs);
+            Method m = innerClazz.getMethod("findLibrary", String.class);
+            m.setAccessible(true);
+            //buggy JDK will throw IllegalArgumentException with next call
+            m.invoke(o, "test");
+        }
+    }
diff --git a/jdk/test/java/net/DatagramSocket/B8035653.java b/jdk/test/java/net/DatagramSocket/B8035653.java
new file mode 100644
index 0000000..6955646
--- /dev/null
+++ b/jdk/test/java/net/DatagramSocket/B8035653.java
@@ -0,0 +1,42 @@
+/*
+ * 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 8035653
+ * @run main/othervm -Xcheck:jni B8035653
+ * @summary InetAddress.getLocalHost crash
+ */
+
+import java.net.*;
+import java.util.*;
+
+public class B8035653 {
+   public static void main(String[] args) throws Exception {
+      try (DatagramSocket ds = new DatagramSocket();){
+            ds.getLocalAddress();
+        } catch (SocketException e) {
+            e.printStackTrace();
+        }
+   }
+}
diff --git a/jdk/test/java/net/NetworkInterface/GetMacAddress.java b/jdk/test/java/net/NetworkInterface/GetMacAddress.java
new file mode 100644
index 0000000..3b7a78c
--- /dev/null
+++ b/jdk/test/java/net/NetworkInterface/GetMacAddress.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2017, 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 8182672
+ * @summary Java 8u121 on Linux intermittently returns null for MAC address
+ */
+
+import java.net.NetworkInterface;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.Phaser;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class GetMacAddress implements Callable<Exception> {
+    static final int NUM_THREADS = 5;
+    static final int NUM_ITERS = 100;
+    static volatile boolean failed; // false
+
+    final String threadName;
+    final NetworkInterface ni;
+    final Phaser startingGate;
+
+    public GetMacAddress(NetworkInterface ni, String name, Phaser phaser) {
+        this.ni = ni;
+        this.threadName = name;
+        this.startingGate = phaser;
+    }
+
+    @Override
+    public Exception call() {
+        int count = 0;
+        startingGate.arriveAndAwaitAdvance();
+        try {
+            for (int i = 0; i < NUM_ITERS; i++) {
+                ni.getMTU();
+                byte[] addr = ni.getHardwareAddress();
+                if (addr == null) {
+                    System.out.println(threadName + ". mac id is null");
+                    failed = true;
+                }
+                count = count + 1;
+                if (count % 100 == 0) {
+                    System.out.println(threadName + ". count is " + count);
+                }
+            }
+        } catch (Exception ex) {
+            System.out.println(threadName + ". Not expecting exception:" + ex.getMessage());
+            failed = true;
+            return ex;
+        }
+        return null;
+    }
+
+    static final Predicate<NetworkInterface> hasHardwareAddress = ni -> {
+        try {
+            if (ni.getHardwareAddress() == null) {
+                System.out.println("Not testing null addr: " + ni.getName());
+                return false;
+            }
+        } catch (Exception ex) {
+            System.out.println("Not testing: " + ni.getName() +
+                    " " + ex.getMessage());
+            return false;
+        }
+        return true;
+    };
+
+    public static Stream<NetworkInterface> getNetworkInterfacesAsStream() throws Exception {
+        // JDK 9 and later
+        //return NetworkInterface.networkInterfaces();
+        // pre JDK 9
+        return Collections.list(NetworkInterface.getNetworkInterfaces()).stream();
+    }
+
+    public static void main(String[] args) throws Exception {
+        List<NetworkInterface> toTest = getNetworkInterfacesAsStream()
+                        .filter(hasHardwareAddress)
+                        .collect(Collectors.toList());
+
+        ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
+
+        for (NetworkInterface ni : toTest) {
+            Phaser startingGate = new Phaser(NUM_THREADS);
+            System.out.println("Testing: " + ni.getName());
+            List<Callable<Exception>> list = new ArrayList<>();
+            for (int i = 0; i < NUM_THREADS; i++)
+                list.add(new GetMacAddress(ni, ni.getName() + "-Thread-" + i, startingGate));
+            List<Future<Exception>> futures = executor.invokeAll(list);
+            for (Future<Exception> f : futures) {
+                if (f.get() != null)
+                    f.get().printStackTrace(System.out);
+            }
+            if (failed)
+                break;
+        }
+        executor.shutdownNow();
+        if (!failed) {
+            System.out.println("PASSED - Finished all threads");
+        } else {
+            throw new RuntimeException("Failed");
+        }
+    }
+}
diff --git a/jdk/test/java/net/ProxySelector/B8035158.java b/jdk/test/java/net/ProxySelector/B8035158.java
new file mode 100644
index 0000000..21b1e99
--- /dev/null
+++ b/jdk/test/java/net/ProxySelector/B8035158.java
@@ -0,0 +1,262 @@
+/*
+ * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8035158 8145732
+ * @run main/othervm B8035158
+ */
+
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.util.*;
+import java.util.concurrent.Callable;
+
+public class B8035158 {
+
+    public static void main(String[] args) {
+        for (TestCase t : emptyNonProxiesHosts()) t.run();
+        for (TestCase t : nonEmptyNonProxiesHosts()) t.run();
+        for (TestCase t : misc()) t.run();
+    }
+
+    // Setting http.nonProxyHosts to an empty string has an effect of
+    // not including default hosts to the list of exceptions
+    // (i.e. if you want everything to be connected directly rather than
+    // through proxy, you should set this property to an empty string)
+    private static Collection<TestCase> emptyNonProxiesHosts() {
+        List<TestCase> tests = new LinkedList<>();
+        String[] loopbacks = {"localhost", "[::1]", "[::0]", "0.0.0.0",
+                "127.0.0.0", "127.0.0.1", "127.0.1.0", "127.0.1.1",
+                "127.1.0.0", "127.1.0.1", "127.1.1.0", "127.1.1.1"};
+        Map<String, String> properties = new HashMap<>();
+        properties.put("http.proxyHost", "http://proxy.example.com");
+        properties.put("http.nonProxyHosts", "");
+        for (String s : loopbacks) {
+            tests.add(new TestCase(properties, "http://" + s, true));
+        }
+        return tests;
+    }
+
+    // No matter what is set into the http.nonProxyHosts (as far as it is not
+    // an empty string) loopback address aliases must be always connected
+    // directly
+    private static Collection<TestCase> nonEmptyNonProxiesHosts() {
+        List<TestCase> tests = new LinkedList<>();
+        String[] nonProxyHosts = {
+                "google.com",
+                "localhost", "[::1]", "[::0]", "0.0.0.0",
+                "127.0.0.0", "127.0.0.1", "127.0.1.0", "127.0.1.1",
+                "127.1.0.0", "127.1.0.1", "127.1.1.0", "127.1.1.1"};
+        String[] loopbacks = {"localhost", "[::1]", "[::0]", "0.0.0.0",
+                "127.0.0.0", "127.0.0.1", "127.0.1.0", "127.0.1.1",
+                "127.1.0.0", "127.1.0.1", "127.1.1.0", "127.1.1.1"};
+        for (String h : nonProxyHosts) {
+            for (String s : loopbacks) {
+                Map<String, String> properties = new HashMap<>();
+                properties.put("http.proxyHost", "http://proxy.example.com");
+                properties.put("http.nonProxyHosts", h);
+                tests.add(new TestCase(properties, "http://" + s, false));
+            }
+        }
+        return tests;
+    }
+
+    // unsorted tests
+    private static Collection<TestCase> misc() {
+        List<TestCase> t = new LinkedList<>();
+        t.add(new TestCase("oracle.com", "http://137.254.16.101", true));
+        t.add(new TestCase("google.com", "http://74.125.200.101", true));
+
+        t.add(new TestCase("google.com|google.ie", "http://google.co.uk",
+                true));
+        t.add(new TestCase("google.com|google.ie", "http://google.com",
+                false));
+        t.add(new TestCase("google.com|google.ie", "http://google.ie",
+                false));
+        t.add(new TestCase("google.com|google.com|google.ie",
+                "http://google.ie", false));
+
+        t.add(new TestCase("google.com|bing.com|yahoo.com",
+                "http://127.0.0.1", false));
+        t.add(new TestCase("google.com|bing.com|yahoo.com",
+                "http://google.com", false));
+        t.add(new TestCase("google.com|bing.com|yahoo.com",
+                "http://bing.com", false));
+        t.add(new TestCase("google.com|bing.com|yahoo.com",
+                "http://yahoo.com", false));
+
+        t.add(new TestCase("google.com|bing.com", "http://google.com", false));
+        t.add(new TestCase("google.com|bing.com", "http://bing.com", false));
+        t.add(new TestCase("google.com|bing.com", "http://yahoo.com",
+                true));
+        t.add(new TestCase("google.com|bing.co*", "http://google.com", false));
+        t.add(new TestCase("google.com|bing.co*", "http://bing.com", false));
+        t.add(new TestCase("google.com|bing.co*", "http://yahoo.com",
+                true));
+        t.add(new TestCase("google.com|*ing.com", "http://google.com", false));
+        t.add(new TestCase("google.com|*ing.com", "http://bing.com", false));
+        t.add(new TestCase("google.com|*ing.com", "http://yahoo.com",
+                true));
+        t.add(new TestCase("google.co*|bing.com", "http://google.com", false));
+        t.add(new TestCase("google.co*|bing.com", "http://bing.com", false));
+        t.add(new TestCase("google.co*|bing.com", "http://yahoo.com",
+                true));
+        t.add(new TestCase("google.co*|bing.co*", "http://google.com", false));
+        t.add(new TestCase("google.co*|bing.co*", "http://bing.com", false));
+        t.add(new TestCase("google.co*|bing.co*", "http://yahoo.com",
+                true));
+        t.add(new TestCase("google.co*|*ing.com", "http://google.com", false));
+        t.add(new TestCase("google.co*|*ing.com", "http://bing.com", false));
+        t.add(new TestCase("google.co*|*ing.com", "http://yahoo.com",
+                true));
+        t.add(new TestCase("*oogle.com|bing.com", "http://google.com", false));
+        t.add(new TestCase("*oogle.com|bing.com", "http://bing.com", false));
+        t.add(new TestCase("*oogle.com|bing.com", "http://yahoo.com",
+                true));
+        t.add(new TestCase("*oogle.com|bing.co*", "http://google.com", false));
+        t.add(new TestCase("*oogle.com|bing.co*", "http://bing.com", false));
+        t.add(new TestCase("*oogle.com|bing.co*", "http://yahoo.com",
+                true));
+        t.add(new TestCase("*oogle.com|*ing.com", "http://google.com", false));
+        t.add(new TestCase("*oogle.com|*ing.com", "http://bing.com", false));
+        t.add(new TestCase("*oogle.com|*ing.com", "http://yahoo.com",
+                true));
+
+        t.add(new TestCase("google.com|bing.com|yahoo.com", "http://google.com", false));
+        t.add(new TestCase("google.com|bing.com|yahoo.com", "http://bing.com", false));
+        t.add(new TestCase("google.com|bing.com|yahoo.com", "http://yahoo.com", false));
+        t.add(new TestCase("google.com|bing.com|yahoo.com",
+                "http://duckduckgo.com", true));
+
+        t.add(new TestCase("p-proxy.com", "http://p-proxy.com", false));
+        t.add(new TestCase("google.co*|google.ie", "http://google.co.uk",
+                false));
+
+        t.add(new TestCase("*oracle.com", "http://my.oracle.com", false));
+        t.add(new TestCase("google.com|bing.com|yahoo.com", "http://127.0.0.1", false));
+        t.add(new TestCase("google.com|bing.com|yahoo.com", "http://yahoo.com", false));
+
+        // example from
+        // http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html
+        t.add(new TestCase("localhost|host.example.com", "http://localhost",
+                false));
+        t.add(new TestCase("localhost|host.example.com",
+                "http://host.example.com", false));
+        t.add(new TestCase("localhost|host.example.com",
+                "http://google.com", true));
+        return t;
+    }
+
+
+    private static <T> T withSystemPropertiesSet(
+            Map<String, String> localProperties,
+            Callable<? extends T> code) {
+        Map<String, String> backup = new HashMap<>();
+        try {
+            backupAndSetProperties(localProperties, backup);
+            return code.call();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            restoreProperties(backup);
+        }
+    }
+
+    private static void backupAndSetProperties(
+            Map<String, String> localProperties,
+            Map<String, String> oldProperties) {
+        for (Map.Entry<String, String> e : localProperties.entrySet()) {
+            String oldValue = System.setProperty(e.getKey(), e.getValue());
+            oldProperties.put(e.getKey(), oldValue);
+        }
+    }
+
+    private static void restoreProperties(Map<String, String> oldProperties) {
+        for (Map.Entry<String, String> e : oldProperties.entrySet()) {
+            String oldValue = e.getValue();
+            String key = e.getKey();
+            if (oldValue == null)
+                System.getProperties().remove(key);
+            else
+                System.setProperty(key, oldValue);
+        }
+    }
+
+    private static class TestCase {
+
+        final Map<String, String> localProperties;
+        final String urlhost;
+        final boolean expectedProxying;
+
+        TestCase(String nonProxyHosts, String urlhost,
+                 boolean expectedProxying) {
+            this(nonProxyHosts, "proxy.example.com", urlhost,
+                    expectedProxying);
+        }
+
+        TestCase(String nonProxyHosts, String proxyHost, String urlhost,
+                 boolean expectedProxying) {
+            this(new HashMap<String, String>() {
+                {
+                    put("http.nonProxyHosts", nonProxyHosts);
+                    put("http.proxyHost", proxyHost);
+                }
+            }, urlhost, expectedProxying);
+        }
+
+        TestCase(Map<String, String> localProperties, String urlhost,
+                 boolean expectedProxying) {
+            this.localProperties = localProperties;
+            this.urlhost = urlhost;
+            this.expectedProxying = expectedProxying;
+        }
+
+        void run() {
+            System.out.printf("urlhost=%s properties=%s: proxied? %s%n",
+                    urlhost, localProperties, expectedProxying);
+
+            List<Proxy> proxies = withSystemPropertiesSet(localProperties,
+                    () -> ProxySelector.getDefault().select(
+                            URI.create(urlhost))
+            );
+
+            verify(proxies);
+        }
+
+        void verify(List<? extends Proxy> proxies) {
+
+            boolean actualProxying = !(proxies.size() == 1 &&
+                    proxies.get(0).type() == Proxy.Type.DIRECT);
+
+            if (actualProxying != expectedProxying)
+                throw new AssertionError(String.format(
+                        "Expected %s connection for %s (given " +
+                                "properties=%s). Here's the list of proxies " +
+                                "returned: %s",
+                        expectedProxying ? "proxied" : "direct", urlhost,
+                        localProperties, proxies
+                ));
+        }
+    }
+}
diff --git a/jdk/test/java/net/Socket/GetLocalAddress.java b/jdk/test/java/net/Socket/GetLocalAddress.java
index e9573d2..3133f92 100644
--- a/jdk/test/java/net/Socket/GetLocalAddress.java
+++ b/jdk/test/java/net/Socket/GetLocalAddress.java
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 4106601 8026245
+ * @bug 4106601 8026245 8071424
  * @run main/othervm GetLocalAddress
  * @run main/othervm -Djava.net.preferIPv4Stack=true GetLocalAddress
  * @run main/othervm -Djava.net.preferIPv6Addresses=true GetLocalAddress
@@ -39,6 +39,8 @@
     static int port;
 
     public static void main(String args[]) throws Exception {
+        testBindNull();
+
         boolean      error = true;
         int          linger = 65546;
         int          value = 0;
@@ -66,4 +68,19 @@
         }
     }
 
+    static void testBindNull() throws Exception {
+        try (Socket soc = new Socket()) {
+            soc.bind(null);
+            if (!soc.isBound())
+                throw new RuntimeException(
+                    "should be bound after bind(null)");
+            if (soc.getLocalPort() <= 0)
+                throw new RuntimeException(
+                   "bind(null) failed, local port: " + soc.getLocalPort());
+            if (soc.getLocalAddress() == null)
+                 throw new RuntimeException(
+                   "bind(null) failed, local address is null");
+        }
+    }
+
 }
diff --git a/jdk/test/java/nio/file/WatchService/DeleteInterference.java b/jdk/test/java/nio/file/WatchService/DeleteInterference.java
new file mode 100644
index 0000000..6a11271
--- /dev/null
+++ b/jdk/test/java/nio/file/WatchService/DeleteInterference.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2016, Red Hat, Inc. and/or its affiliates.
+ * 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.
+ */
+
+/**
+ * @test
+ * @bug 8153925
+ * @summary Tests potential interference between a thread creating and closing
+ *     a WatchService with another thread that is deleting and re-creating the
+ *     directory at around the same time. This scenario tickled a timing bug
+ *     in the Windows implementation.
+ */
+
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.WatchService;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import static java.nio.file.StandardWatchEventKinds.*;
+
+public class DeleteInterference {
+
+    private static final int ITERATIONS_COUNT = 1024;
+
+    /**
+     * Execute two tasks in a thread pool. One task loops on creating and
+     * closing a WatchService, the other task deletes and re-creates the
+     * directory.
+     */
+    public static void main(String[] args) throws Exception {
+        Path dir = Files.createTempDirectory("work");
+        ExecutorService pool = Executors.newCachedThreadPool();
+        try {
+            Future<?> task1 = pool.submit(() -> openAndCloseWatcher(dir));
+            Future<?> task2 = pool.submit(() -> deleteAndRecreateDirectory(dir));
+            task1.get();
+            task2.get();
+        } finally {
+            pool.shutdown();
+            deleteFileTree(dir);
+        }
+    }
+
+    private static void openAndCloseWatcher(Path dir) {
+        FileSystem fs = FileSystems.getDefault();
+        for (int i = 0; i < ITERATIONS_COUNT; i++) {
+            try (WatchService watcher = fs.newWatchService()) {
+                dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
+            } catch (IOException ioe) {
+                // ignore
+            }
+        }
+    }
+
+    private static void deleteAndRecreateDirectory(Path dir) {
+        for (int i = 0; i < ITERATIONS_COUNT; i++) {
+            try {
+                deleteFileTree(dir);
+                Path subdir = Files.createDirectories(dir.resolve("subdir"));
+                Files.createFile(subdir.resolve("test"));
+            } catch (IOException ioe) {
+                // ignore
+            }
+        }
+    }
+
+    private static void deleteFileTree(Path file) {
+        try {
+            if (Files.isDirectory(file)) {
+                try (DirectoryStream<Path> stream = Files.newDirectoryStream(file)) {
+                    for (Path pa : stream) {
+                        deleteFileTree(pa);
+                    }
+                }
+            }
+            Files.delete(file);
+        } catch (IOException ioe) {
+            // ignore
+        }
+    }
+}
diff --git a/jdk/test/java/nio/file/WatchService/UpdateInterference.java b/jdk/test/java/nio/file/WatchService/UpdateInterference.java
new file mode 100644
index 0000000..5bd8812
--- /dev/null
+++ b/jdk/test/java/nio/file/WatchService/UpdateInterference.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8145981
+ * @summary LinuxWatchService sometimes reports inotify events against wrong directory
+ * @run main UpdateInterference
+ */
+import java.io.IOException;
+import java.nio.file.*;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import static java.nio.file.StandardWatchEventKinds.*;
+
+public class UpdateInterference {
+    public static void main(String[] args) throws IOException, InterruptedException {
+        final Path root = Files.createTempDirectory("test");
+        final Path foo = root.resolve("foo");
+        final Path bar = root.resolve("bar");
+        final Path baz = root.resolve("baz");
+
+        Files.createDirectory(foo);
+        Files.createDirectory(bar);
+        Files.createDirectory(baz);
+
+        final WatchService watcher = root.getFileSystem().newWatchService();
+        final WatchKey fooKey = foo.register(watcher, ENTRY_CREATE);
+        final WatchKey barKey = bar.register(watcher, ENTRY_CREATE);
+
+        new Thread() {
+            { setDaemon(true); }
+
+            @Override
+            public void run() {
+                while (true) {
+                    try {
+                        final Path temp = Files.createTempFile(foo, "temp", ".tmp");
+                        Files.delete(temp);
+                        Thread.sleep(10);
+                    } catch (IOException | InterruptedException e) {
+                        throw new RuntimeException(e);
+                    }
+                }
+            }
+        }.start();
+
+        new Thread() {
+            { setDaemon(true); }
+
+            @Override
+            public void run() {
+                WatchKey bazKeys[] = new WatchKey[32];
+                while (true) {
+                    try {
+                        for( int i = 0; i < bazKeys.length; i++) {
+                            bazKeys[i] = baz.register(watcher, ENTRY_CREATE);
+                        }
+                        for( int i = 0; i < bazKeys.length; i++) {
+                            bazKeys[i].cancel();
+                        }
+                        Thread.sleep(1);
+                    } catch (IOException | InterruptedException e) {
+                        throw new RuntimeException(e);
+                    }
+                }
+            }
+        }.start();
+
+        long time = System.currentTimeMillis();
+        while ((System.currentTimeMillis() - time) < 15000) {
+            final WatchKey key = watcher.poll(60, TimeUnit.SECONDS);
+            if (key == null) continue;
+
+            if (key != fooKey) {
+                List<WatchEvent<?>> pollEvents = key.pollEvents();
+                for (WatchEvent<?> watchEvent : pollEvents) {
+                    System.out.println(watchEvent.count() + " " +
+                                       watchEvent.kind() + " " +
+                                       watchEvent.context());
+                }
+                throw new RuntimeException("Event received for unexpected key");
+            }
+            key.reset();
+        }
+    }
+}
+
diff --git a/jdk/test/java/security/KeyPairGenerator/FinalizeHalf.java b/jdk/test/java/security/KeyPairGenerator/FinalizeHalf.java
new file mode 100644
index 0000000..a2a1eb3
--- /dev/null
+++ b/jdk/test/java/security/KeyPairGenerator/FinalizeHalf.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8163896
+ * @summary Finalizing one key of a KeyPair invalidates the other key
+ */
+
+import java.security.Key;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.Provider;
+import java.security.ProviderException;
+import java.security.Security;
+import java.util.function.Consumer;
+import java.util.ArrayList;
+import java.util.List;
+
+public class FinalizeHalf {
+
+    static int failures = 0;
+
+    public static void main(String[] args) throws Throwable {
+        List<Consumer<Key>> methods = new ArrayList<>();
+        methods.add((Key k) -> k.getEncoded());
+        methods.add((Key k) -> k.toString());
+
+        for (String algo : new String[] {"DiffieHellman", "DSA", "RSA"}) {
+            for (Provider provider : Security.getProviders()) {
+                for (boolean priv : new boolean[] {true, false}) {
+                    for (Consumer<Key> method : methods) {
+                        test(algo, provider, priv, method);
+                    }
+                }
+            }
+        }
+
+        if (failures > 0) {
+            throw new RuntimeException(failures + " test(s) failed.");
+        }
+    }
+
+    static void test(String algo, Provider provider, boolean priv,
+            Consumer<Key> method) throws Exception {
+        KeyPairGenerator generator;
+        try {
+            generator = KeyPairGenerator.getInstance(algo, provider);
+        } catch (NoSuchAlgorithmException nsae) {
+            return;
+        }
+
+        System.out.println("Checking " + provider.getName() + ", " + algo);
+
+        KeyPair pair = generator.generateKeyPair();
+        Key key = priv ? pair.getPrivate() : pair.getPublic();
+
+        pair = null;
+        for (int i = 0; i < 32; ++i) {
+            System.gc();
+        }
+
+        try {
+            method.accept(key);
+        } catch (ProviderException pe) {
+            failures++;
+        }
+    }
+}
diff --git a/jdk/test/java/security/Signature/NoProvider.java b/jdk/test/java/security/Signature/NoProvider.java
new file mode 100644
index 0000000..4fa4499
--- /dev/null
+++ b/jdk/test/java/security/Signature/NoProvider.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8165751
+ * @summary Verify that that a subclass of Signature that does not contain a
+ *     provider can be used verify.
+ * @run main/othervm -Djava.security.debug=provider NoProvider
+ */
+
+import java.security.*;
+
+public class NoProvider {
+
+    private static class NoProviderPublicKey implements PublicKey {
+
+        public String getAlgorithm() {
+            return "NoProvider";
+        }
+        public String getFormat() {
+            return "none";
+        }
+        public byte[] getEncoded() {
+            return new byte[1];
+        }
+    }
+
+    private static class NoProviderSignature extends Signature {
+
+        public NoProviderSignature() {
+            super("NoProvider");
+        }
+
+        protected void engineInitVerify(PublicKey publicKey)
+            throws InvalidKeyException {
+            // do nothing
+        }
+
+        protected void engineInitSign(PrivateKey privateKey)
+            throws InvalidKeyException {
+            // do nothing
+        }
+
+        protected void engineUpdate(byte b) throws SignatureException {
+            // do nothing
+        }
+
+        protected void engineUpdate(byte[] b, int off, int len)
+            throws SignatureException {
+            // do nothing
+        }
+
+        protected byte[] engineSign() throws SignatureException {
+            return new byte[1];
+        }
+
+        protected boolean engineVerify(byte[] sigBytes)
+            throws SignatureException {
+            return false;
+        }
+
+        @Deprecated
+        protected void engineSetParameter(String param, Object value)
+            throws InvalidParameterException {
+            // do nothing
+        }
+
+        @Deprecated
+        protected Object engineGetParameter(String param)
+            throws InvalidParameterException {
+            return null;
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        new NoProviderSignature().initVerify(new NoProviderPublicKey());
+    }
+}
diff --git a/jdk/test/java/time/tck/java/time/TCKZoneOffset.java b/jdk/test/java/time/tck/java/time/TCKZoneOffset.java
index c121079..7646643 100644
--- a/jdk/test/java/time/tck/java/time/TCKZoneOffset.java
+++ b/jdk/test/java/time/tck/java/time/TCKZoneOffset.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -419,6 +419,21 @@
         ZoneOffset.ofHoursMinutesSeconds(-19, 0, 0);
     }
 
+    @Test(expectedExceptions=DateTimeException.class)
+    public void test_factory_int_hours_minutes_seconds_minutesMinValue() {
+        ZoneOffset.ofHoursMinutesSeconds(0, Integer.MIN_VALUE, -1);
+    }
+
+    @Test(expectedExceptions=DateTimeException.class)
+    public void test_factory_int_hours_minutes_seconds_secondsMinValue() {
+        ZoneOffset.ofHoursMinutesSeconds(0, 0, Integer.MIN_VALUE);
+    }
+
+    @Test(expectedExceptions=DateTimeException.class)
+    public void test_factory_int_hours_minutes_seconds_minutesAndSecondsMinValue() {
+        ZoneOffset.ofHoursMinutesSeconds(0, Integer.MIN_VALUE, Integer.MIN_VALUE);
+    }
+
     //-----------------------------------------------------------------------
     @Test
     public void test_factory_ofTotalSeconds() {
@@ -437,6 +452,11 @@
         ZoneOffset.ofTotalSeconds(-18 * 60 * 60 - 1);
     }
 
+    @Test(expectedExceptions=DateTimeException.class)
+    public void test_factory_ofTotalSeconds_minValue() {
+        ZoneOffset.ofTotalSeconds(Integer.MIN_VALUE);
+    }
+
     //-----------------------------------------------------------------------
     // from()
     //-----------------------------------------------------------------------
diff --git a/jdk/test/java/util/Base64/TestBase64.java b/jdk/test/java/util/Base64/TestBase64.java
index bbde587..5ddaafe 100644
--- a/jdk/test/java/util/Base64/TestBase64.java
+++ b/jdk/test/java/util/Base64/TestBase64.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,8 +23,11 @@
 
 /**
  * @test 4235519 8004212 8005394 8007298 8006295 8006315 8006530 8007379 8008925
- *       8014217 8025003 8026330 8028397
+ *       8014217 8025003 8026330 8028397 8165243
  * @summary tests java.util.Base64
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.*
+ * @run main TestBase64
  */
 
 import java.io.ByteArrayInputStream;
@@ -34,11 +37,17 @@
 import java.io.OutputStream;
 import java.nio.ByteBuffer;
 import java.util.Arrays;
+import java.util.ArrayList;
 import java.util.Base64;
+import java.util.List;
 import java.util.Random;
 
+import jdk.testlibrary.RandomFactory;
+
 public class TestBase64 {
 
+    private static final Random rnd = RandomFactory.getRandom();
+
     public static void main(String args[]) throws Throwable {
         int numRuns  = 10;
         int numBytes = 200;
@@ -51,7 +60,6 @@
         test(Base64.getUrlEncoder(), Base64.getUrlDecoder(), numRuns, numBytes);
         test(Base64.getMimeEncoder(), Base64.getMimeDecoder(), numRuns, numBytes);
 
-        Random rnd = new java.util.Random();
         byte[] nl_1 = new byte[] {'\n'};
         byte[] nl_2 = new byte[] {'\n', '\r'};
         byte[] nl_3 = new byte[] {'\n', '\r', '\n'};
@@ -75,7 +83,7 @@
         testNull(Base64.getDecoder());
         testNull(Base64.getUrlDecoder());
         testNull(Base64.getMimeDecoder());
-        checkNull(new Runnable() { public void run() { Base64.getMimeEncoder(10, null); }});
+        checkNull(() -> Base64.getMimeEncoder(10, null));
 
         testIOE(Base64.getEncoder());
         testIOE(Base64.getUrlEncoder());
@@ -83,26 +91,23 @@
         testIOE(Base64.getMimeEncoder(10, new byte[]{'\n'}));
 
         byte[] src = new byte[1024];
-        new Random().nextBytes(src);
+        rnd.nextBytes(src);
         final byte[] decoded = Base64.getEncoder().encode(src);
         testIOE(Base64.getDecoder(), decoded);
         testIOE(Base64.getMimeDecoder(), decoded);
         testIOE(Base64.getUrlDecoder(), Base64.getUrlEncoder().encode(src));
 
         // illegal line separator
-        checkIAE(new Runnable() { public void run() { Base64.getMimeEncoder(10, new byte[]{'\r', 'N'}); }});
+        checkIAE(() -> Base64.getMimeEncoder(10, new byte[]{'\r', 'N'}));
 
         // malformed padding/ending
         testMalformedPadding();
 
         // illegal base64 character
         decoded[2] = (byte)0xe0;
-        checkIAE(new Runnable() {
-            public void run() { Base64.getDecoder().decode(decoded); }});
-        checkIAE(new Runnable() {
-            public void run() { Base64.getDecoder().decode(decoded, new byte[1024]); }});
-        checkIAE(new Runnable() { public void run() {
-            Base64.getDecoder().decode(ByteBuffer.wrap(decoded)); }});
+        checkIAE(() -> Base64.getDecoder().decode(decoded));
+        checkIAE(() -> Base64.getDecoder().decode(decoded, new byte[1024]));
+        checkIAE(() -> Base64.getDecoder().decode(ByteBuffer.wrap(decoded)));
 
         // test single-non-base64 character for mime decoding
         testSingleNonBase64MimeDec();
@@ -112,6 +117,16 @@
 
         // test mime decoding with ignored character after padding
         testDecodeIgnoredAfterPadding();
+
+        // given invalid args, encoder should not produce output
+        testEncoderKeepsSilence(Base64.getEncoder());
+        testEncoderKeepsSilence(Base64.getUrlEncoder());
+        testEncoderKeepsSilence(Base64.getMimeEncoder());
+
+        // given invalid args, decoder should not consume input
+        testDecoderKeepsAbstinence(Base64.getDecoder());
+        testDecoderKeepsAbstinence(Base64.getUrlDecoder());
+        testDecoderKeepsAbstinence(Base64.getMimeDecoder());
     }
 
     private static sun.misc.BASE64Encoder sunmisc = new sun.misc.BASE64Encoder();
@@ -282,48 +297,49 @@
     private static final String str_null = null;
     private static final ByteBuffer bb_null = null;
 
-    private static void testNull(final Base64.Encoder enc) {
-        checkNull(new Runnable() { public void run() { enc.encode(ba_null); }});
-        checkNull(new Runnable() { public void run() { enc.encodeToString(ba_null); }});
-        checkNull(new Runnable() { public void run() { enc.encode(ba_null, new byte[10]); }});
-        checkNull(new Runnable() { public void run() { enc.encode(new byte[10], ba_null); }});
-        checkNull(new Runnable() { public void run() { enc.encode(bb_null); }});
-        checkNull(new Runnable() { public void run() { enc.wrap((OutputStream)null); }});
+    private static void testNull(Base64.Encoder enc) {
+        checkNull(() -> enc.encode(ba_null));
+        checkNull(() -> enc.encodeToString(ba_null));
+        checkNull(() -> enc.encode(ba_null, new byte[10]));
+        checkNull(() -> enc.encode(new byte[10], ba_null));
+        checkNull(() -> enc.encode(bb_null));
+        checkNull(() -> enc.wrap((OutputStream)null));
     }
 
-    private static void testNull(final Base64.Decoder dec) {
-        checkNull(new Runnable() { public void run() { dec.decode(ba_null); }});
-        checkNull(new Runnable() { public void run() { dec.decode(str_null); }});
-        checkNull(new Runnable() { public void run() { dec.decode(ba_null, new byte[10]); }});
-        checkNull(new Runnable() { public void run() { dec.decode(new byte[10], ba_null); }});
-        checkNull(new Runnable() { public void run() { dec.decode(bb_null); }});
-        checkNull(new Runnable() { public void run() { dec.wrap((InputStream)null); }});
+    private static void testNull(Base64.Decoder dec) {
+        checkNull(() -> dec.decode(ba_null));
+        checkNull(() -> dec.decode(str_null));
+        checkNull(() -> dec.decode(ba_null, new byte[10]));
+        checkNull(() -> dec.decode(new byte[10], ba_null));
+        checkNull(() -> dec.decode(bb_null));
+        checkNull(() -> dec.wrap((InputStream)null));
     }
 
+    @FunctionalInterface
     private static interface Testable {
         public void test() throws Throwable;
     }
 
-    private static void testIOE(final Base64.Encoder enc) throws Throwable {
+    private static void testIOE(Base64.Encoder enc) throws Throwable {
         ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
-        final OutputStream os = enc.wrap(baos);
+        OutputStream os = enc.wrap(baos);
         os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9});
         os.close();
-        checkIOE(new Testable() { public void test() throws Throwable { os.write(10); }});
-        checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}); }});
-        checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}, 1, 4); }});
+        checkIOE(() -> os.write(10));
+        checkIOE(() -> os.write(new byte[] {10}));
+        checkIOE(() -> os.write(new byte[] {10}, 1, 4));
     }
 
-    private static void testIOE(final Base64.Decoder dec, byte[] decoded) throws Throwable {
+    private static void testIOE(Base64.Decoder dec, byte[] decoded) throws Throwable {
         ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
-        final InputStream is = dec.wrap(bais);
+        InputStream is = dec.wrap(bais);
         is.read(new byte[10]);
         is.close();
-        checkIOE(new Testable() { public void test() throws Throwable { is.read(); }});
-        checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}); }});
-        checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}, 1, 4); }});
-        checkIOE(new Testable() { public void test() throws Throwable { is.available(); }});
-        checkIOE(new Testable() { public void test() throws Throwable { is.skip(20); }});
+        checkIOE(() -> is.read());
+        checkIOE(() -> is.read(new byte[] {10}));
+        checkIOE(() -> is.read(new byte[] {10}, 1, 4));
+        checkIOE(() -> is.available());
+        checkIOE(() -> is.skip(20));
     }
 
     private static final void checkNull(Runnable r) {
@@ -415,13 +431,13 @@
                 int pos = (Integer)data[i + 2];
 
                 // decode(byte[])
-                checkIAE(new Runnable() { public void run() { dec.decode(srcBytes); }});
+                checkIAE(() -> dec.decode(srcBytes));
 
                 // decode(String)
-                checkIAE(new Runnable() { public void run() { dec.decode(srcStr); }});
+                checkIAE(() -> dec.decode(srcStr));
 
                 // decode(ByteBuffer)
-                checkIAE(new Runnable() { public void run() { dec.decode(srcBB); }});
+                checkIAE(() -> dec.decode(srcBB));
 
                 // wrap stream
                 checkIOE(new Testable() {
@@ -531,4 +547,67 @@
         }
         return ret;
     }
+
+    private static void testEncoderKeepsSilence(Base64.Encoder enc)
+            throws Throwable {
+        List<Integer> vals = Arrays.asList(Integer.MIN_VALUE,
+                Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
+                Integer.MAX_VALUE - 1, Integer.MAX_VALUE,
+                rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
+                rnd.nextInt());
+        byte[] buf = new byte[] {1, 0, 91};
+        for (int off : vals) {
+            for (int len : vals) {
+                if (off >= 0 && len >= 0 && off <= buf.length - len) {
+                    // valid args, skip them
+                    continue;
+                }
+                // invalid args, test them
+                System.out.println("testing off=" + off + ", len=" + len);
+
+                ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
+                try (OutputStream os = enc.wrap(baos)) {
+                    os.write(buf, off, len);
+                    throw new RuntimeException("Expected IOOBEx was not thrown");
+                } catch (IndexOutOfBoundsException expected) {
+                }
+                if (baos.size() > 0)
+                    throw new RuntimeException("No output was expected, but got "
+                            + baos.size() + " bytes");
+            }
+        }
+    }
+
+    private static void testDecoderKeepsAbstinence(Base64.Decoder dec)
+            throws Throwable {
+        List<Integer> vals = Arrays.asList(Integer.MIN_VALUE,
+                Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
+                Integer.MAX_VALUE - 1, Integer.MAX_VALUE,
+                rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
+                rnd.nextInt());
+        byte[] buf = new byte[3];
+        for (int off : vals) {
+            for (int len : vals) {
+                if (off >= 0 && len >= 0 && off <= buf.length - len) {
+                    // valid args, skip them
+                    continue;
+                }
+                // invalid args, test them
+                System.out.println("testing off=" + off + ", len=" + len);
+
+                String input = "AAAAAAAAAAAAAAAAAAAAAA";
+                ByteArrayInputStream bais =
+                        new ByteArrayInputStream(input.getBytes("Latin1"));
+                try (InputStream is = dec.wrap(bais)) {
+                    is.read(buf, off, len);
+                    throw new RuntimeException("Expected IOOBEx was not thrown");
+                } catch (IndexOutOfBoundsException expected) {
+                }
+                if (bais.available() != input.length())
+                    throw new RuntimeException("No input should be consumed, "
+                            + "but consumed " + (input.length() - bais.available())
+                            + " bytes");
+            }
+        }
+    }
 }
diff --git a/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.java b/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.java
new file mode 100644
index 0000000..bfb32bd
--- /dev/null
+++ b/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.java
@@ -0,0 +1,253 @@
+/*
+ * Copyright (c) 2017, 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 8054214 8173423 8177776
+ * @summary Create an equivalent test case for JDK9's SupplementalJapaneseEraTest
+ * @library /lib/testlibrary
+ * @run testng SupplementalJapaneseEraTest
+ */
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.text.SimpleDateFormat;
+import java.time.chrono.JapaneseChronology;
+import java.time.chrono.JapaneseDate;
+import java.time.chrono.JapaneseEra;
+import java.time.format.DateTimeFormatterBuilder;
+import java.time.format.TextStyle;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import static java.util.GregorianCalendar.*;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import jdk.testlibrary.ProcessTools;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+
+public class SupplementalJapaneseEraTest {
+    private static final Locale WAREKI_LOCALE = Locale.forLanguageTag("ja-JP-u-ca-japanese");
+    private static final String NEW_ERA_NAME = "NewEra";
+    private static final String NEW_ERA_ABBR = "N.E.";
+    private static final int NEW_ERA_YEAR = 200;
+    private static final int NEW_ERA_MONTH = FEBRUARY;
+    private static final int NEW_ERA_DAY = 11;
+    private static int errors = 0;
+
+    @BeforeTest
+    public void prepareTestJDK() throws IOException {
+        Path src = Paths.get(System.getProperty("test.jdk")).toAbsolutePath();
+        Path dst = Paths.get("testjava").toAbsolutePath();
+        Files.walkFileTree(src, new CopyFileVisitor(src, dst));
+    }
+
+    @Test
+    public void invokeTestJDK() throws Throwable {
+        assertTrue(ProcessTools.executeCommand(
+            Paths.get("testjava", "bin", "java").toAbsolutePath().toString(),
+            "-cp",
+            System.getProperty("test.classes"),
+            "SupplementalJapaneseEraTest")
+            .getExitValue() == 0);
+    }
+
+    public static void main(String[] args) {
+        testProperty();
+
+        if (errors != 0) {
+            throw new RuntimeException("test failed");
+        }
+    }
+
+    // copied from JDK9's test
+    private static void testProperty() {
+        Calendar jcal = new Calendar.Builder()
+            .setCalendarType("japanese")
+            .setFields(YEAR, 1, DAY_OF_YEAR, 1)
+            .build();
+        Date firstDayOfEra = jcal.getTime();
+
+        jcal.set(ERA, jcal.get(ERA) - 1); // previous era
+        jcal.set(YEAR, 1);
+        jcal.set(DAY_OF_YEAR, 1);
+        Calendar cal = new GregorianCalendar();
+        cal.setTimeInMillis(jcal.getTimeInMillis());
+        cal.add(YEAR, 199);
+        int year = cal.get(YEAR);
+
+        SimpleDateFormat sdf;
+        String expected, got;
+
+        // test long era name
+        sdf = new SimpleDateFormat("GGGG y-MM-dd", WAREKI_LOCALE);
+        got = sdf.format(firstDayOfEra);
+        expected = NEW_ERA_NAME + " 1-02-11";
+        if (!expected.equals(got)) {
+            System.err.printf("GGGG y-MM-dd: got=\"%s\", expected=\"%s\"%n", got, expected);
+            errors++;
+        }
+
+        // test era abbreviation
+        sdf = new SimpleDateFormat("G y-MM-dd", WAREKI_LOCALE);
+        got = sdf.format(firstDayOfEra);
+        expected = NEW_ERA_ABBR+" 1-02-11";
+        if (!expected.equals(got)) {
+            System.err.printf("G y-MM-dd: got=\"%s\", expected=\"%s\"%n", got, expected);
+            errors++;
+        }
+
+        // confirm the gregorian year
+        sdf = new SimpleDateFormat("y", Locale.US);
+        int y = Integer.parseInt(sdf.format(firstDayOfEra));
+        if (y != year) {
+            System.err.printf("Gregorian year: got=%d, expected=%d%n", y, year);
+            errors++;
+        }
+
+        // test java.time.chrono.JapaneseEra
+        JapaneseDate jdate = JapaneseDate.of(year, 2, 11);
+        got = jdate.toString();
+        expected = "Japanese " + NEW_ERA_NAME + " 1-02-11";
+        if (!expected.equals(got)) {
+            System.err.printf("JapaneseDate: got=\"%s\", expected=\"%s\"%n", got, expected);
+            errors++;
+        }
+        JapaneseEra jera = jdate.getEra();
+        got = jera.getDisplayName(TextStyle.FULL, Locale.US);
+        if (!NEW_ERA_NAME.equals(got)) {
+            System.err.printf("JapaneseEra (FULL): got=\"%s\", expected=\"%s\"%n", got, NEW_ERA_NAME);
+            errors++;
+        }
+        got = jera.getDisplayName(TextStyle.SHORT, Locale.US);
+        if (!NEW_ERA_NAME.equals(got)) {
+            System.err.printf("JapaneseEra (SHORT): got=\"%s\", expected=\"%s\"%n", got, NEW_ERA_NAME);
+            errors++;
+        }
+        got = jera.getDisplayName(TextStyle.NARROW, Locale.US);
+        if (!NEW_ERA_ABBR.equals(got)) {
+            System.err.printf("JapaneseEra (NARROW): got=\"%s\", expected=\"%s\"%n", got, NEW_ERA_ABBR);
+            errors++;
+        }
+        got = jera.getDisplayName(TextStyle.NARROW_STANDALONE, Locale.US);
+        if (!NEW_ERA_ABBR.equals(got)) {
+            System.err.printf("JapaneseEra (NARROW_STANDALONE): got=\"%s\", expected=\"%s\"%n", got, NEW_ERA_ABBR);
+            errors++;
+        }
+
+        // test long/abbreviated names with java.time.format
+        got = new DateTimeFormatterBuilder()
+            .appendPattern("GGGG")
+            .appendLiteral(" ")
+            .appendPattern("G")
+            .toFormatter(Locale.US)
+            .withChronology(JapaneseChronology.INSTANCE)
+            .format(jdate);
+        expected = NEW_ERA_NAME + " " + NEW_ERA_ABBR;
+        if (!expected.equals(got)) {
+            System.err.printf("java.time formatter long/abbr names: got=\"%s\", expected=\"%s\"%n", got, expected);
+            errors++;
+        }
+    }
+
+    private static class CopyFileVisitor extends SimpleFileVisitor<Path> {
+        private final Path copyFrom;
+        private final Path copyTo;
+        private final Path calProps = Paths.get("calendars.properties");
+        private final String JA_CAL_KEY = "calendar.japanese.eras";
+
+        public CopyFileVisitor(Path copyFrom, Path copyTo) {
+            this.copyFrom = copyFrom;
+            this.copyTo = copyTo;
+        }
+
+        @Override
+        public FileVisitResult preVisitDirectory(Path file,
+                BasicFileAttributes attrs) throws IOException {
+            Path relativePath = copyFrom.relativize(file);
+            Path destination = copyTo.resolve(relativePath);
+            if (!destination.toFile().exists()) {
+                Files.createDirectories(destination);
+            }
+            return FileVisitResult.CONTINUE;
+        }
+
+        @Override
+        public FileVisitResult visitFile(Path file,
+                BasicFileAttributes attrs) throws IOException {
+            if (!file.toFile().isFile()) {
+                return FileVisitResult.CONTINUE;
+            }
+            Path relativePath = copyFrom.relativize(file);
+            Path destination = copyTo.resolve(relativePath);
+            if (relativePath.getFileName().equals(calProps)) {
+                modifyCalendarProperties(file, destination);
+            } else {
+                Files.copy(file, destination, StandardCopyOption.COPY_ATTRIBUTES);
+            }
+            return FileVisitResult.CONTINUE;
+        }
+
+        private void modifyCalendarProperties(Path src, Path dst) throws IOException {
+            Properties p = new Properties();
+            try (BufferedReader br = Files.newBufferedReader(src)) {
+                p.load(br);
+            }
+
+            String eras = p.getProperty(JA_CAL_KEY);
+            if (eras != null) {
+                p.setProperty(JA_CAL_KEY,
+                    eras +
+                    "; name=" + SupplementalJapaneseEraTest.NEW_ERA_NAME +
+                    ",abbr=" + SupplementalJapaneseEraTest.NEW_ERA_ABBR +
+                    ",since=" + since());
+            }
+            try (BufferedWriter bw = Files.newBufferedWriter(dst)) {
+                p.store(bw, "test calendars.properties for supplemental Japanese era");
+            }
+        }
+
+        private long since() {
+            return new Calendar.Builder()
+                .setCalendarType("japanese")
+                .setTimeZone(TimeZone.getTimeZone("GMT"))
+                .setDate(SupplementalJapaneseEraTest.NEW_ERA_YEAR,
+                    SupplementalJapaneseEraTest.NEW_ERA_MONTH,
+                    SupplementalJapaneseEraTest.NEW_ERA_DAY)
+                .build()
+                .getTimeInMillis();
+        }
+    }
+}
diff --git a/jdk/test/java/util/Currency/ValidateISO4217.java b/jdk/test/java/util/Currency/ValidateISO4217.java
index c65c980..568de12 100644
--- a/jdk/test/java/util/Currency/ValidateISO4217.java
+++ b/jdk/test/java/util/Currency/ValidateISO4217.java
@@ -23,7 +23,7 @@
 /*
  * @test
  * @bug 4691089 4819436 4942982 5104960 6544471 6627549 7066203 7195759
- *      8074350 8074351
+ *      8074350 8074351 8145952
  * @summary Validate ISO 4217 data for Currency class.
  */
 
@@ -93,7 +93,7 @@
 
     /* Codes that are obsolete, do not have related country */
     static final String otherCodes =
-        "ADP-AFA-ATS-AYM-AZM-BEF-BGL-BOV-BYB-CHE-CHW-CLF-COU-CUC-CYP-DEM-EEK-ESP-FIM-FRF-GHC-GRD-GWP-IEP-ITL-LUF-MGF-MTL-MXV-MZM-NLG-PTE-ROL-RUR-SDD-SIT-SKK-SRG-TMM-TPE-TRL-VEF-UYI-USN-USS-VEB-XAG-XAU-XBA-XBB-XBC-XBD-XDR-XFO-XFU-XPD-XPT-XSU-XTS-XUA-XXX-YUM-ZMK-ZWD-ZWN-ZWR";
+        "ADP-AFA-ATS-AYM-AZM-BEF-BGL-BOV-BYB-BYR-CHE-CHW-CLF-COU-CUC-CYP-DEM-EEK-ESP-FIM-FRF-GHC-GRD-GWP-IEP-ITL-LUF-MGF-MTL-MXV-MZM-NLG-PTE-ROL-RUR-SDD-SIT-SKK-SRG-TMM-TPE-TRL-VEF-UYI-USN-USS-VEB-XAG-XAU-XBA-XBB-XBC-XBD-XDR-XFO-XFU-XPD-XPT-XSU-XTS-XUA-XXX-YUM-ZMK-ZWD-ZWN-ZWR";
 
     static boolean err = false;
 
diff --git a/jdk/test/java/util/Currency/tablea1.txt b/jdk/test/java/util/Currency/tablea1.txt
index 12c9f7e..10501b0 100644
--- a/jdk/test/java/util/Currency/tablea1.txt
+++ b/jdk/test/java/util/Currency/tablea1.txt
@@ -1,12 +1,12 @@
 #
 #
-# Amendments up until ISO 4217 AMENDMENT NUMBER 159
-#   (As of 15 August 2014)
+# Amendments up until ISO 4217 AMENDMENT NUMBER 162
+#   (As of 30 Auguest 2016)
 #
 
 # Version
 FILEVERSION=2
-DATAVERSION=159
+DATAVERSION=162
 
 # ISO 4217 currency data
 AF	AFN	971	2
@@ -28,7 +28,7 @@
 BH	BHD	48	3
 BD	BDT	50	2
 BB	BBD	52	2
-BY	BYR	974	0
+BY	BYN	933	2
 BE	EUR	978	2
 BZ	BZD	84	2
 BJ	XOF	952	0
diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java
index e942e18..dd80d99 100644
--- a/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java
+++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java
@@ -49,14 +49,11 @@
 public final class CancelledLockLoops {
     static final Random rng = new Random();
     static boolean print = false;
-    static final int ITERS = 1000000;
+    static final int ITERS = 5000000;
     static final long TIMEOUT = 100;
 
     public static void main(String[] args) throws Exception {
-        int maxThreads = 5;
-        if (args.length > 0)
-            maxThreads = Integer.parseInt(args[0]);
-
+        int maxThreads = (args.length > 0) ? Integer.parseInt(args[0]) : 5;
         print = true;
 
         for (int i = 2; i <= maxThreads; i += (i+1) >>> 1) {
@@ -90,7 +87,7 @@
                 threads[i] = new Thread(this);
             for (int i = 0; i < threads.length; ++i)
                 threads[i].start();
-            Thread[] cancels = (Thread[]) (threads.clone());
+            Thread[] cancels = threads.clone();
             Collections.shuffle(Arrays.asList(cancels), rng);
             barrier.await();
             Thread.sleep(TIMEOUT);
diff --git a/jdk/test/java/util/regex/RegExTest.java b/jdk/test/java/util/regex/RegExTest.java
index 7ca2f99..220d0fc 100644
--- a/jdk/test/java/util/regex/RegExTest.java
+++ b/jdk/test/java/util/regex/RegExTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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,7 +32,7 @@
  * 6358731 6178785 6284152 6231989 6497148 6486934 6233084 6504326 6635133
  * 6350801 6676425 6878475 6919132 6931676 6948903 6990617 7014645 7039066
  * 7067045 7014640 7189363 8007395 8013252 8013254 8012646 8023647 6559590
- * 8027645 6854417
+ * 8027645 6854417 8169056
  */
 
 import java.util.regex.*;
@@ -2144,6 +2144,14 @@
         if (!pattern.matcher("\u017f\u0130\u0131\u212a\u212b").matches())
             failCount++;
 
+        try {
+            Pattern.compile("[", Pattern.CANON_EQ);
+            failCount++;
+        } catch (PatternSyntaxException expected) {
+        } catch (Exception unexpected) {
+            failCount++;
+        }
+
         report("CharClass");
     }
 
diff --git a/jdk/test/javax/accessibility/JList/AccessibleJListChildNPETest.java b/jdk/test/javax/accessibility/JList/AccessibleJListChildNPETest.java
new file mode 100644
index 0000000..1185195
--- /dev/null
+++ b/jdk/test/javax/accessibility/JList/AccessibleJListChildNPETest.java
@@ -0,0 +1,103 @@
+/*
+* Copyright (c) 2017, 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.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.accessibility.Accessible;
+import javax.accessibility.AccessibleContext;
+import javax.swing.AbstractListModel;
+import javax.swing.JFrame;
+import javax.swing.JList;
+import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
+
+/* @test
+   @bug 8076249
+   @summary  NPE in AccessBridge while editing JList model
+   @author Mikhail Cherkasov
+   @run main AccessibleJListChildNPETest
+*/
+public class AccessibleJListChildNPETest {
+
+    private static String[] model = { "1", "2", "3", "4", "5", "6" };
+    private static JList<String> list;
+
+    public static void main(String[] args) throws InvocationTargetException, InterruptedException {
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                JFrame frame = new JFrame();
+                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+                final MyModel dataModel = new MyModel(Arrays.asList(model));
+                list = new JList<>(dataModel);
+                frame.getContentPane().add(list);
+                frame.pack();
+                frame.setVisible(true);
+
+            }
+        });
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                AccessibleContext ac = list.getAccessibleContext();
+                MyModel model = (MyModel)list.getModel();
+                Accessible accessibleChild = ac.getAccessibleChild(model.getSize()-1);
+                model.removeFirst();
+                accessibleChild.getAccessibleContext().getAccessibleSelection();
+                accessibleChild.getAccessibleContext().getAccessibleText();
+                accessibleChild.getAccessibleContext().getAccessibleValue();
+            }
+        });
+    }
+
+    protected static class MyModel extends AbstractListModel<String> {
+        private List<String> items = new ArrayList<>();
+
+        MyModel(final List<String> newItems) {
+            super();
+            items.addAll(newItems);
+            fireIntervalAdded(this, 0, getSize() - 1);
+        }
+
+        void removeFirst() {
+            if(getSize() > 0) {
+                items.remove(0);
+                fireIntervalRemoved(this, 0, 0);
+            }
+        }
+
+        @Override
+        public int getSize() {
+            return items.size();
+        }
+
+        @Override
+        public String getElementAt(int index) {
+            return items.get(index);
+        }
+    }
+}
diff --git a/jdk/test/javax/crypto/CryptoPermission/TestUnlimited.java b/jdk/test/javax/crypto/CryptoPermission/TestUnlimited.java
new file mode 100644
index 0000000..25d29f8
--- /dev/null
+++ b/jdk/test/javax/crypto/CryptoPermission/TestUnlimited.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  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.
+ */
+
+/**
+ * @test
+ * @bug 8157561
+ * @summary Ship the unlimited policy files in JDK Updates
+ * @run main/othervm TestUnlimited "" exception
+ * @run main/othervm TestUnlimited limited fail
+ * @run main/othervm TestUnlimited unlimited pass
+ * @run main/othervm TestUnlimited unlimited/ pass
+ * @run main/othervm TestUnlimited NosuchDir exception
+ * @run main/othervm TestUnlimited . exception
+ * @run main/othervm TestUnlimited /tmp/unlimited exception
+ * @run main/othervm TestUnlimited ../policy/unlimited exception
+ * @run main/othervm TestUnlimited ./unlimited exception
+ * @run main/othervm TestUnlimited /unlimited exception
+ */
+import javax.crypto.*;
+import java.security.Security;
+
+public class TestUnlimited {
+
+    public static void main(String[] args) throws Exception {
+        /*
+         * Override the Security property to allow for unlimited policy.
+         * Would need appropriate permissions if Security Manager were
+         * active.
+         */
+        if (args.length != 2) {
+            throw new Exception("Two args required");
+        }
+
+        boolean expected = args[1].equals("pass");
+        boolean exception = args[1].equals("exception");
+        boolean result = false;
+
+        System.out.println("Testing: " + args[0]);
+
+        if (args[0].equals("\"\"")) {
+            Security.setProperty("crypto.policy", "");
+        } else {
+            Security.setProperty("crypto.policy", args[0]);
+        }
+
+        /*
+         * Use the AES as the test Cipher
+         * If there is an error initializing, we will never get past here.
+         */
+        try {
+            int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
+            System.out.println("max AES key len:" + maxKeyLen);
+            if (maxKeyLen > 128) {
+                System.out.println("Unlimited policy is active");
+                result = true;
+            } else {
+                System.out.println("Unlimited policy is NOT active");
+                result = false;
+            }
+        } catch (Throwable e) {
+            if (!exception) {
+                throw new Exception();
+            }
+        }
+
+        System.out.println(
+                "Expected:\t" + expected + "\nResult:\t\t" + result);
+        if (expected != result) {
+            throw new Exception();
+        }
+
+        System.out.println("DONE!");
+    }
+}
diff --git a/jdk/test/javax/management/security/keystoreAgent b/jdk/test/javax/management/security/keystoreAgent
new file mode 100644
index 0000000..cfb02e0
--- /dev/null
+++ b/jdk/test/javax/management/security/keystoreAgent
Binary files differ
diff --git a/jdk/test/javax/management/security/keystoreClient b/jdk/test/javax/management/security/keystoreClient
new file mode 100644
index 0000000..f0e0b7f
--- /dev/null
+++ b/jdk/test/javax/management/security/keystoreClient
Binary files differ
diff --git a/jdk/test/javax/management/security/truststoreAgent b/jdk/test/javax/management/security/truststoreAgent
new file mode 100644
index 0000000..5b5f698
--- /dev/null
+++ b/jdk/test/javax/management/security/truststoreAgent
Binary files differ
diff --git a/jdk/test/javax/management/security/truststoreClient b/jdk/test/javax/management/security/truststoreClient
new file mode 100644
index 0000000..f6a6a00
--- /dev/null
+++ b/jdk/test/javax/management/security/truststoreClient
Binary files differ
diff --git a/jdk/test/javax/net/ssl/ciphersuites/DisabledAlgorithms.java b/jdk/test/javax/net/ssl/ciphersuites/DisabledAlgorithms.java
index 9a8e028..faada15 100644
--- a/jdk/test/javax/net/ssl/ciphersuites/DisabledAlgorithms.java
+++ b/jdk/test/javax/net/ssl/ciphersuites/DisabledAlgorithms.java
@@ -38,11 +38,10 @@
 
 /**
  * @test
- * @bug 8076221
+ * @bug 8076221 8157035
  * @summary Check if weak cipher suites are disabled
  * @run main/othervm DisabledAlgorithms default
- * @run main/othervm -Djdk.tls.namedGroups="secp256r1,secp192r1"
- *     DisabledAlgorithms empty
+ * @run main/othervm DisabledAlgorithms empty
  */
 public class DisabledAlgorithms {
 
@@ -98,11 +97,6 @@
                 System.out.println("jdk.tls.disabledAlgorithms = "
                         + Security.getProperty("jdk.tls.disabledAlgorithms"));
 
-                // some of the certs in our test are weak; disable
-                Security.setProperty("jdk.certpath.disabledAlgorithms", "");
-                System.out.println("jdk.certpath.disabledAlgorithms = "
-                        + Security.getProperty("jdk.cerpath.disabledAlgorithms"));
-
                 // check if RC4 cipher suites can be used
                 // if jdk.tls.disabledAlgorithms is empty
                 checkSuccess(rc4_ciphersuites);
diff --git a/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java b/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java
index c061d1b..89d38bc 100644
--- a/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java
+++ b/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java
@@ -23,15 +23,18 @@
 
 /*
  * @test
- * @bug 6659990
- * @summary test the immutability of the Date fields in KerberosTicket class.
+ * @bug 6659990 8147772
+ * @summary test the immutability of the Date fields in KerberosTicket class,
+ *          serialization, and behavior after being destroyed.
  * @ignore Must set up KDC and setup Kerberos configuration file
  */
 
-import java.net.InetAddress;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
 import java.util.Date;
 import java.io.*;
-import javax.security.auth.kerberos.KerberosKey;
+import javax.security.auth.RefreshFailedException;
 import javax.security.auth.kerberos.KerberosPrincipal;
 import javax.security.auth.kerberos.KerberosTicket;
 import java.util.Base64;
@@ -75,6 +78,7 @@
 
         testDateImmutability(t, originalTime);
         testS11nCompatibility(t); // S11n: Serialization
+        testDestroy(t);
     }
 
     private static void checkTime(KerberosTicket kt, long timeValue) {
@@ -137,4 +141,30 @@
 
         System.out.println("S11nCompatibility Test Passed");
     }
+
+    private static void testDestroy(KerberosTicket t) throws Exception {
+        t.destroy();
+        if (!t.isDestroyed()) {
+            throw new RuntimeException("ticket should have been destroyed");
+        }
+        // Although these methods are meaningless, they can be called
+        for (Method m: KerberosTicket.class.getDeclaredMethods()) {
+            if (Modifier.isPublic(m.getModifiers())
+                    && m.getParameterCount() == 0) {
+                System.out.println("Testing " + m.getName() + "...");
+                try {
+                    m.invoke(t);
+                } catch (InvocationTargetException e) {
+                    Throwable cause = e.getCause();
+                    if (cause instanceof RefreshFailedException ||
+                            cause instanceof IllegalStateException) {
+                        // this is OK
+                    } else {
+                        throw e;
+                    }
+                }
+            }
+        }
+        System.out.println("Destroy Test Passed");
+    }
 }
diff --git a/jdk/test/javax/swing/JMenuItem/8152981/MenuItemIconTest.java b/jdk/test/javax/swing/JMenuItem/8152981/MenuItemIconTest.java
new file mode 100644
index 0000000..1a872a5
--- /dev/null
+++ b/jdk/test/javax/swing/JMenuItem/8152981/MenuItemIconTest.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8152981
+ * @summary Double icons with JMenuItem setHorizontalTextPosition on Win 10
+ * @requires (os.family == "windows")
+ * @run main MenuItemIconTest
+ */
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Graphics;
+import java.awt.Point;
+import java.awt.Robot;
+import java.awt.image.BufferedImage;
+import javax.swing.ImageIcon;
+import javax.swing.JFrame;
+import javax.swing.JMenuBar;
+import javax.swing.JMenuItem;
+import javax.swing.SwingConstants;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+
+public class MenuItemIconTest {
+
+    private static JFrame frame;
+    private static Robot robot;
+    private static String errorMessage = "";
+    private static JMenuItem menuItem;
+    private static final int IMAGE_WIDTH_AND_HEIGHT = 25;
+
+    public static void main(String[] args) throws Exception {
+        robot = new Robot();
+        String name = UIManager.getSystemLookAndFeelClassName();
+        try {
+            UIManager.setLookAndFeel(name);
+        } catch (ClassNotFoundException | InstantiationException |
+                IllegalAccessException | UnsupportedLookAndFeelException e) {
+            throw new RuntimeException("Test Failed");
+        }
+        createUI();
+        robot.waitForIdle();
+        executeTest();
+        if (!"".equals(errorMessage)) {
+            throw new RuntimeException(errorMessage);
+        }
+    }
+
+    private static void createUI() throws Exception {
+        SwingUtilities.invokeAndWait(() -> {
+            frame = new JFrame();
+            frame.setTitle("Test");
+            JMenuBar menuBar = new JMenuBar();
+            ImageIcon icon = createIcon();
+            menuItem = new JMenuItem("Command", icon);
+            menuItem.setHorizontalTextPosition(SwingConstants.LEFT);
+            menuBar.add(menuItem);
+            frame.setJMenuBar(menuBar);
+            frame.setPreferredSize(new Dimension(500, 500));
+            frame.pack();
+            frame.setVisible(true);
+            frame.setLocationRelativeTo(null);
+        });
+    }
+
+    private static void checkPixeclColor(int x, int y) {
+        robot.delay(2000);
+        robot.mouseMove(x, y);
+        Color c = robot.getPixelColor(x, y);
+        if (c.getRed() == 255) {
+            errorMessage = "Test Failed";
+        }
+        robot.delay(5000);
+        frame.dispose();
+    }
+
+    protected static ImageIcon createIcon() {
+        BufferedImage bi = new BufferedImage(IMAGE_WIDTH_AND_HEIGHT,
+                IMAGE_WIDTH_AND_HEIGHT, BufferedImage.TYPE_INT_ARGB);
+        Graphics g = bi.createGraphics();
+        g.setColor(Color.RED);
+        g.fillOval(0, 0, IMAGE_WIDTH_AND_HEIGHT, IMAGE_WIDTH_AND_HEIGHT);
+        return new ImageIcon(bi);
+    }
+
+    private static void executeTest() throws Exception {
+        Point point = menuItem.getLocationOnScreen();
+        checkPixeclColor(point.x + IMAGE_WIDTH_AND_HEIGHT / 2,
+                point.y + IMAGE_WIDTH_AND_HEIGHT / 2);
+    }
+}
+
diff --git a/jdk/test/javax/swing/JProgressBar/8161664/ProgressBarMemoryLeakTest.java b/jdk/test/javax/swing/JProgressBar/8161664/ProgressBarMemoryLeakTest.java
new file mode 100644
index 0000000..852aacb
--- /dev/null
+++ b/jdk/test/javax/swing/JProgressBar/8161664/ProgressBarMemoryLeakTest.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8161664
+ * @summary Memory leak in com.apple.laf.AquaProgressBarUI: removed progress bar still referenced
+ * @library ../../regtesthelpers
+ * @build Util
+ * @run main/timeout=300/othervm -Xmx16m ProgressBarMemoryLeakTest
+ */
+import java.awt.EventQueue;
+import java.lang.ref.WeakReference;
+
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JProgressBar;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+
+public class ProgressBarMemoryLeakTest {
+
+  private static JFrame sFrame;
+  private static WeakReference<JProgressBar> sProgressBar;
+
+  public static void main(String[] args) throws Exception {
+    UIManager.LookAndFeelInfo[] installedLookAndFeels = UIManager.getInstalledLookAndFeels();
+    for ( UIManager.LookAndFeelInfo installedLookAndFeel : installedLookAndFeels ) {
+      executeTestCase(installedLookAndFeel.getClassName());
+    }
+  }
+
+  private static void executeTestCase(String lookAndFeelString) throws Exception{
+    if (tryLookAndFeel(lookAndFeelString)) {
+      EventQueue.invokeAndWait( new Runnable() {
+        @Override
+        public void run() {
+          showUI();
+        }
+      } );
+      EventQueue.invokeAndWait( new Runnable() {
+        @Override
+        public void run() {
+          disposeUI();
+        }
+      } );
+      Util.generateOOME();
+      JProgressBar progressBar = sProgressBar.get();
+      if ( progressBar != null ) {
+        throw new RuntimeException( "Progress bar (using L&F: " + lookAndFeelString + ") should have been GC-ed" );
+      }
+    }
+  }
+
+  private static void showUI(){
+    sFrame = new JFrame();
+
+    JProgressBar progressBar = new JProgressBar();
+    progressBar.setVisible(false);
+    progressBar.setIndeterminate(false);
+    progressBar.setIndeterminate(true);
+    progressBar.setIndeterminate(false);
+    progressBar.setValue(10);
+    progressBar.setString("Progress");
+
+    sFrame.add(progressBar);
+
+    sProgressBar = new WeakReference<>(progressBar);
+
+    sFrame.setSize(200,200);
+    sFrame.setVisible(true);
+  }
+
+  private static void disposeUI(){
+    sFrame.setContentPane(new JPanel());
+    sFrame.dispose();
+    sFrame = null;
+  }
+
+  private static boolean tryLookAndFeel(String lookAndFeelString) throws Exception {
+    try {
+      UIManager.setLookAndFeel(lookAndFeelString);
+    } catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
+      return false;
+    }
+    return true;
+  }
+}
diff --git a/jdk/test/javax/swing/plaf/basic/BasicLabelUI/bug7172652.java b/jdk/test/javax/swing/plaf/basic/BasicLabelUI/bug7172652.java
new file mode 100644
index 0000000..8a06c48
--- /dev/null
+++ b/jdk/test/javax/swing/plaf/basic/BasicLabelUI/bug7172652.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+   @bug 7172652
+   @summary With JDK 1.7 text field does not obtain focus when using mnemonic Alt/Key combin
+   @author Semyon Sadetsky
+   @library /lib/testlibrary
+   @build jdk.testlibrary.OSInfo
+   @run main bug7172652
+  */
+
+import javax.swing.*;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+import java.awt.*;
+import java.awt.event.KeyEvent;
+import jdk.testlibrary.OSInfo;
+
+public class bug7172652  {
+
+    private static JMenu menu;
+    private static JFrame frame;
+    private static Boolean selected;
+
+    public static void main(String[] args) throws Exception {
+        if (OSInfo.getOSType() != OSInfo.OSType.WINDOWS) {
+            System.out.println("ok");
+            return;
+        }
+        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                setup();
+            }
+        });
+
+        test();
+        SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+                frame.dispose();
+            }
+        });
+    }
+
+    private static void test() throws Exception {
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                menu.getModel().addChangeListener(new ChangeListener() {
+                    @Override
+                    public void stateChanged(ChangeEvent e) {
+                        selected = menu.isSelected();
+                    }
+                });
+            }
+        });
+
+        Robot robot = new Robot();
+        robot.setAutoDelay(200);
+
+        robot.keyPress(KeyEvent.VK_ALT);
+        robot.keyPress(KeyEvent.VK_F);
+        robot.keyRelease(KeyEvent.VK_F);
+        robot.keyRelease(KeyEvent.VK_ALT);
+
+        robot.waitForIdle();
+        if( selected != null ) {
+            throw new RuntimeException("Menu is notified selected= " + selected);
+        }
+
+        robot.keyPress(KeyEvent.VK_ALT);
+        robot.keyPress(KeyEvent.VK_F);
+        robot.keyRelease(KeyEvent.VK_F);
+        robot.keyRelease(KeyEvent.VK_ALT);
+        if( selected != null ) {
+            throw new RuntimeException("Menu is notified selected= " + selected);
+        }
+
+        robot.waitForIdle();
+
+        robot.keyPress(KeyEvent.VK_ALT);
+        robot.keyPress(KeyEvent.VK_F);
+        robot.keyRelease(KeyEvent.VK_F);
+        robot.keyRelease(KeyEvent.VK_ALT);
+        if( selected != null ) {
+            throw new RuntimeException("Menu is notified selected= " + selected);
+        }
+
+        robot.waitForIdle();
+
+        robot.keyPress(KeyEvent.VK_ALT);
+        robot.keyPress(KeyEvent.VK_F);
+        robot.keyRelease(KeyEvent.VK_F);
+        robot.keyRelease(KeyEvent.VK_ALT);
+        if( selected != null ) {
+            throw new RuntimeException("Menu is notified selected= " + selected);
+        }
+
+        robot.waitForIdle();
+
+        System.out.printf("ok");
+    }
+
+    private static void setup() {
+        JLabel firstLbl = new JLabel("First name");
+        JLabel lastLbl = new JLabel("Last name");
+        JMenuBar menuBar = new JMenuBar();
+
+        JTextField firstTxtFld = new JTextField(20);
+        JTextField lastTxtFld = new JTextField(20);
+        JDesktopPane desktopPane = new JDesktopPane();
+        JInternalFrame iframe = new JInternalFrame("A frame", true, true, true, true);
+
+        // Set an initial size
+        iframe.setSize(200, 220);
+
+        // By default, internal frames are not visible; make it visible
+        iframe.setVisible(true);
+
+        JPanel pane = new JPanel();
+        pane.setLayout(new FlowLayout());
+
+        pane.add(firstLbl);
+        pane.add(firstTxtFld);
+        pane.add(lastLbl);
+        pane.add(lastTxtFld);
+
+        firstLbl.setLabelFor(firstTxtFld);
+        firstLbl.setDisplayedMnemonic('F');
+
+        lastLbl.setLabelFor(lastTxtFld);
+        lastLbl.setDisplayedMnemonic('L');
+
+        iframe.getContentPane().add(pane);
+        iframe.setJMenuBar(menuBar);
+        menu = new JMenu("FirstMenu");
+        //m.setMnemonic('i');
+        menuBar.add(menu);
+        desktopPane.add(iframe);
+
+        frame = new JFrame();
+        frame.setUndecorated(true);
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+        frame.getContentPane().add(desktopPane);
+        frame.setSize(300, 300);
+        frame.setVisible(true);
+    }
+
+}
diff --git a/jdk/test/javax/swing/plaf/basic/BasicScrollPaneUI/8166591/TooMuchWheelRotationEventsTest.java b/jdk/test/javax/swing/plaf/basic/BasicScrollPaneUI/8166591/TooMuchWheelRotationEventsTest.java
index a58bc70..ba23035 100644
--- a/jdk/test/javax/swing/plaf/basic/BasicScrollPaneUI/8166591/TooMuchWheelRotationEventsTest.java
+++ b/jdk/test/javax/swing/plaf/basic/BasicScrollPaneUI/8166591/TooMuchWheelRotationEventsTest.java
@@ -40,7 +40,7 @@
 
 /*
  * @test
- * @bug 8166591
+ * @bug 8166591 8173876
  * @summary [macos 10.12] Trackpad scrolling of text on OS X 10.12 Sierra
  *    is very fast (Trackpad, Retina only)
  * @run main/manual/othervm TooMuchWheelRotationEventsTest
diff --git a/jdk/test/javax/swing/text/html/parser/Parser/HtmlCommentTagParseTest/HtmlCommentTagParseTest.java b/jdk/test/javax/swing/text/html/parser/Parser/HtmlCommentTagParseTest/HtmlCommentTagParseTest.java
new file mode 100644
index 0000000..0f36517
--- /dev/null
+++ b/jdk/test/javax/swing/text/html/parser/Parser/HtmlCommentTagParseTest/HtmlCommentTagParseTest.java
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2017, 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 javax.swing.*;
+import javax.swing.text.MutableAttributeSet;
+import javax.swing.text.html.HTML;
+import javax.swing.text.html.HTMLDocument;
+import javax.swing.text.html.HTMLEditorKit;
+import java.io.*;
+import java.lang.reflect.InvocationTargetException;
+
+/* @test
+   @bug 8177450
+   @summary  javax.swing.text.html.parser.Parser parseScript ignores a character after commend end
+   @author Mikhail Cherkasov
+   @run main HtmlCommentTagParseTest
+*/
+public class HtmlCommentTagParseTest {
+    private static volatile boolean failed = false;
+    public static void main(String[] args) throws IOException, InvocationTargetException, InterruptedException {
+        SwingUtilities.invokeAndWait(() -> {
+                MyParser cb = new MyParser();
+                HTMLEditorKit htmlKit = new HTMLEditorKit();
+                HTMLDocument htmlDoc = (HTMLDocument)
+                        htmlKit.createDefaultDocument();
+            FileReader reader = null;
+            try {
+                reader = new FileReader(getDirURL() + "test.html");
+                htmlDoc.getParser().parse(reader, cb, true);
+                if(failed) {
+                    throw new RuntimeException("Test failed");
+                }
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
+        });
+    }
+    private static String getDirURL() {
+        return new File(System.getProperty("test.src", ".")).getAbsolutePath() +
+                File.separator;
+    }
+
+    private static class MyParser extends HTMLEditorKit.ParserCallback {
+        @Override
+        public void handleError(String errorMsg, int pos) {
+            failed = errorMsg.contains("eof.script");
+        }
+    }
+}
\ No newline at end of file
diff --git a/jdk/test/javax/swing/text/html/parser/Parser/HtmlCommentTagParseTest/test.html b/jdk/test/javax/swing/text/html/parser/Parser/HtmlCommentTagParseTest/test.html
new file mode 100644
index 0000000..ded588a
--- /dev/null
+++ b/jdk/test/javax/swing/text/html/parser/Parser/HtmlCommentTagParseTest/test.html
@@ -0,0 +1,5 @@
+<html>
+<body>
+<script><!-- --></script>
+</body>
+</html>
\ No newline at end of file
diff --git a/jdk/test/javax/xml/jaxp/datatype/TestXMLGregorianCalendarTimeZone.java b/jdk/test/javax/xml/jaxp/datatype/TestXMLGregorianCalendarTimeZone.java
new file mode 100644
index 0000000..dabd58ed
--- /dev/null
+++ b/jdk/test/javax/xml/jaxp/datatype/TestXMLGregorianCalendarTimeZone.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8028363
+ * @summary XmlGregorianCalendarImpl.getTimezone() returns wrong timezone if
+ * offset's minutes value is less then 10 (e.g. GMT+10:05)
+ * @run main TestXMLGregorianCalendarTimeZone
+*/
+
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+import java.util.TimeZone;
+
+public class TestXMLGregorianCalendarTimeZone {
+
+    public static void main(String[] args) throws DatatypeConfigurationException {
+        for (int i = 0; i < 60; i++) {
+            test(i);
+        }
+    }
+
+    private static void test(int offsetMinutes)
+            throws DatatypeConfigurationException {
+        XMLGregorianCalendar calendar = DatatypeFactory.newInstance().
+                newXMLGregorianCalendar();
+        calendar.setTimezone(60 + offsetMinutes);
+        TimeZone timeZone = calendar.getTimeZone(DatatypeConstants.FIELD_UNDEFINED);
+        String expected = (offsetMinutes < 10 ? "GMT+01:0" : "GMT+01:")
+                + offsetMinutes;
+        if (!timeZone.getID().equals(expected)) {
+            throw new RuntimeException("Test failed: expected timezone: " +
+                    expected + " Actual: " + timeZone.getID());
+        }
+    }
+}
diff --git a/jdk/test/javax/xml/jaxp/transform/8162598/TransformerTest.java b/jdk/test/javax/xml/jaxp/transform/8162598/TransformerTest.java
new file mode 100644
index 0000000..749d398
--- /dev/null
+++ b/jdk/test/javax/xml/jaxp/transform/8162598/TransformerTest.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8162598
+ * @summary Test XSLTC handling of namespaces, especially empty namespace definitions to reset the
+ *          default namespace.
+ * @run testng/othervm TransformerTest
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.stream.StreamSource;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+
+import com.sun.org.apache.xml.internal.serialize.OutputFormat;
+import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
+
+public class TransformerTest {
+
+    private Transformer createTransformerFromInputstream(InputStream xslStream) throws TransformerException {
+        return TransformerFactory.newInstance().newTransformer(new StreamSource(xslStream));
+    }
+
+    private Document transformInputStreamToDocument(Transformer transformer, InputStream sourceStream) throws TransformerException {
+        DOMResult response = new DOMResult();
+        transformer.transform(new StreamSource(sourceStream), response);
+        return (Document)response.getNode();
+    }
+
+    /**
+     * Utility method for testBug8162598().
+     * Provides a convenient way to check/assert the expected namespaces
+     * of a Node and its siblings.
+     *
+     * @param test
+     * The node to check
+     * @param nstest
+     * Expected namespace of the node
+     * @param nsb
+     * Expected namespace of the first sibling
+     * @param nsc
+     * Expected namespace of the first sibling of the first sibling
+     */
+    private void checkNodeNS8162598(Node test, String nstest, String nsb, String nsc) {
+        String testNodeName = test.getNodeName();
+        if (nstest == null) {
+            Assert.assertNull(test.getNamespaceURI(), "unexpected namespace for " + testNodeName);
+        } else {
+            Assert.assertEquals(test.getNamespaceURI(), nstest, "unexpected namespace for " + testNodeName);
+        }
+        Node b = test.getChildNodes().item(0);
+        if (nsb == null) {
+            Assert.assertNull(b.getNamespaceURI(), "unexpected namespace for " + testNodeName + "->b");
+        } else {
+            Assert.assertEquals(b.getNamespaceURI(), nsb, "unexpected namespace for " + testNodeName + "->b");
+        }
+        Node c = b.getChildNodes().item(0);
+        if (nsc == null) {
+            Assert.assertNull(c.getNamespaceURI(), "unexpected namespace for " + testNodeName + "->b->c");
+        } else {
+            Assert.assertEquals(c.getNamespaceURI(), nsc, "unexpected namespace for " + testNodeName + "->b->c");
+        }
+    }
+
+    /*
+     * @bug 8162598
+     * @summary Test XSLTC handling of namespaces, especially empty namespace definitions to reset the
+     *          default namespace
+     */
+    @Test
+    public final void testBug8162598() throws IOException, TransformerException {
+        final String LINE_SEPARATOR = System.getProperty("line.separator");
+
+        final String xsl =
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + LINE_SEPARATOR +
+            "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + LINE_SEPARATOR +
+            "    <xsl:template match=\"/\">" + LINE_SEPARATOR +
+            "        <root xmlns=\"ns1\">" + LINE_SEPARATOR +
+            "            <xsl:call-template name=\"transform\"/>" + LINE_SEPARATOR +
+            "        </root>" + LINE_SEPARATOR +
+            "    </xsl:template>" + LINE_SEPARATOR +
+            "    <xsl:template name=\"transform\">" + LINE_SEPARATOR +
+            "        <test1 xmlns=\"ns2\"><b xmlns=\"ns2\"><c xmlns=\"\"></c></b></test1>" + LINE_SEPARATOR +
+            "        <test2 xmlns=\"ns1\"><b xmlns=\"ns2\"><c xmlns=\"\"></c></b></test2>" + LINE_SEPARATOR +
+            "        <test3><b><c xmlns=\"\"></c></b></test3>" + LINE_SEPARATOR +
+            "        <test4 xmlns=\"\"><b><c xmlns=\"\"></c></b></test4>" + LINE_SEPARATOR +
+            "        <test5 xmlns=\"ns1\"><b><c xmlns=\"\"></c></b></test5>" + LINE_SEPARATOR +
+            "        <test6 xmlns=\"\"/>" + LINE_SEPARATOR +
+            "    </xsl:template>" + LINE_SEPARATOR +
+            "</xsl:stylesheet>";
+
+
+        final String sourceXml =
+                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aaa></aaa>" + LINE_SEPARATOR;
+
+        System.out.println("Stylesheet:");
+        System.out.println("=============================");
+        System.out.println(xsl);
+        System.out.println();
+
+        System.out.println("Source before transformation:");
+        System.out.println("=============================");
+        System.out.println(sourceXml);
+        System.out.println();
+
+        System.out.println("Result after transformation:");
+        System.out.println("============================");
+        Document document = transformInputStreamToDocument(
+            createTransformerFromInputstream(new ByteArrayInputStream(xsl.getBytes())),
+                                             new ByteArrayInputStream(sourceXml.getBytes()));
+        OutputFormat format = new OutputFormat();
+        format.setIndenting(true);
+        new XMLSerializer(System.out, format).serialize(document);
+        System.out.println();
+        checkNodeNS8162598(document.getElementsByTagName("test1").item(0), "ns2", "ns2", null);
+        checkNodeNS8162598(document.getElementsByTagName("test2").item(0), "ns1", "ns2", null);
+        checkNodeNS8162598(document.getElementsByTagName("test3").item(0), null, null, null);
+        checkNodeNS8162598(document.getElementsByTagName("test4").item(0), null, null, null);
+        checkNodeNS8162598(document.getElementsByTagName("test5").item(0), "ns1", "ns1", null);
+        Assert.assertNull(document.getElementsByTagName("test6").item(0).getNamespaceURI(), "unexpected namespace for test6");
+    }
+}
diff --git a/jdk/test/javax/xml/jaxp/transform/8169112/Bug8169112.xsl b/jdk/test/javax/xml/jaxp/transform/8169112/Bug8169112.xsl
new file mode 100644
index 0000000..e16639b
--- /dev/null
+++ b/jdk/test/javax/xml/jaxp/transform/8169112/Bug8169112.xsl
@@ -0,0 +1,8382 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+                xmlns:TRI="http://www.exchangenetwork.net/schema/TRI/6"
+                xmlns:sc="urn:us:net:exchangenetwork:sc:1:0"
+                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+                exclude-result-prefixes="TRI sc">
+  <xsl:output method="html" version="4.0" doctype-public="-//W3C//DTD HTML 4.01 Transitional//EN" doctype-system="http://www.w3.org/TR/html4/loose.dtd" />
+  <xsl:template match="/">
+    <html>
+    <head>
+      <title>TRI Reporting Form</title>
+      <script type="text/javascript">
+				var PhantomJSPrinting = {
+					header: {
+						height: '0.0in',
+						contents: function(pageNum, numPages) { return ""; }
+						},
+					footer: {
+						height: '0.0in',
+						contents: function(pageNum, numPages) { return ""; }
+						}
+				};
+	  </script>
+      <style type="text/css">
+          p {
+            font-family: Arial;
+            padding: 0;
+            margin: 0;
+            border: 0;
+          }
+
+          .answerText {
+              color: blue;
+              font-size: 9pt;
+              font-weight: bold;
+          }
+
+          .smallAnswer {
+              color: blue;
+              font-size: 8pt;
+              font-weight: bold;
+          }
+
+          .teqAnswer {
+              color: blue;
+              font-size: 8pt;
+              font-weight: bold;
+          }
+
+          .fieldLabel {
+              font-family: Arial, Helvetica, sans-serif;
+              font-size: 12px;
+              font-weight: bold;
+              padding-right: 5px;
+          }
+
+          a { padding-right: 10px; }
+
+          @page land { size: landscape; margin: 0.1in; }
+
+          .landscapeArea { page: land; width: 1010px; page-break-before: always; }
+
+          @page { margin: 0.1in; }
+
+          }
+        </style>
+    </head>
+    <body style="font-family: arial">
+    <xsl:for-each select="//TRI:Report">
+      <xsl:variable name="formID"><xsl:value-of select="sc:ReportIdentifier"/></xsl:variable>
+	<xsl:variable name="OMBNumberFormR">
+	<xsl:choose>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2005'">2070-0093</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2006'">2070-0093</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2007'">2070-0093</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2008'">2070-0093</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2009'">2025-0009</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2010'">2025-0009</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2011'">2025-0009</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2012'">2025-0009</xsl:when>
+	        </xsl:choose>
+	</xsl:variable>
+	<xsl:variable name="OMBNumberFormA">
+	 <xsl:choose>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2005'">2070-0143</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2006'">2070-0143</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2007'">2070-0143</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2008'">2070-0143</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2009'">2025-0010</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2010'">2025-0010</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2011'">2025-0009</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2012'">2025-0009</xsl:when>
+	        </xsl:choose>
+	</xsl:variable>
+	<xsl:variable name="OMBNumberSchedule1">
+	  <xsl:choose>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2008'">2025-0007</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2009'">2025-0007</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2010'">2025-0007</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2011'">2025-0009</xsl:when>
+	          <xsl:when test="TRI:SubmissionReportingYear = '2012'">2025-0009</xsl:when>
+	        </xsl:choose>
+	</xsl:variable>
+
+      <xsl:variable name="RevisionDateFormR">
+        <xsl:choose>
+           <xsl:when test="TRI:SubmissionReportingYear = '2005'">08/2005</xsl:when>
+           <xsl:when test="TRI:SubmissionReportingYear = '2006'">08/2006</xsl:when>
+           <xsl:when test="TRI:SubmissionReportingYear = '2007'">01/2008</xsl:when>
+           <xsl:when test="TRI:SubmissionReportingYear = '2008'">08/2008</xsl:when>
+           <xsl:when test="TRI:SubmissionReportingYear = '2009'">10/2009</xsl:when>
+           <xsl:when test="TRI:SubmissionReportingYear = '2010'">10/2009</xsl:when>
+           <xsl:when test="TRI:SubmissionReportingYear = '2011'">10/2011</xsl:when>
+           <xsl:when test="TRI:SubmissionReportingYear = '2012'">10/2012</xsl:when>
+        </xsl:choose>
+      </xsl:variable>
+      <xsl:variable name="RevisionDateFormA">
+        <xsl:choose>
+          <xsl:when test="TRI:SubmissionReportingYear = '2005'">08/2005</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2006'">11/2006</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2007'">01/2008</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2008'">03/2009</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2009'">10/2009</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2010'">03/2009</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2011'">10/2011</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2012'">10/2012</xsl:when>
+        </xsl:choose>
+      </xsl:variable>
+
+      <xsl:variable name="ApprovalDateFormR">
+        <xsl:choose>
+          <xsl:when test="TRI:SubmissionReportingYear = '2005'">01/31/2008</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2006'">01/31/2008</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2007'">01/31/2010</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2008'">03/31/2011</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2009'">07/31/2011</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2010'">07/31/2011</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2011'">10/31/2014</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2012'">10/31/2014</xsl:when>
+        </xsl:choose>
+      </xsl:variable>
+      <xsl:variable name="ApprovalDateFormA">
+        <xsl:choose>
+          <xsl:when test="TRI:SubmissionReportingYear = '2005'">01/31/2008</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2006'">01/31/2008</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2007'">03/31/2011</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2008'">03/31/2011</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2009'">07/31/2011</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2010'">07/31/2011</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2011'">10/31/2014</xsl:when>
+          <xsl:when test="TRI:SubmissionReportingYear = '2012'">10/31/2014</xsl:when>
+        </xsl:choose>
+      </xsl:variable>
+      <xsl:variable name="ApprovalDateSchedule1">
+		  <xsl:choose>
+			  <xsl:when test="TRI:SubmissionReportingYear &lt; '2011'"> 07/31/2011</xsl:when>
+			  <xsl:otherwise>10/31/2014</xsl:otherwise>
+		  </xsl:choose>
+      </xsl:variable>
+
+      <xsl:variable name="ScheduleOneNA">
+      <xsl:choose>
+          <xsl:when test="TRI:SubmissionReportingYear &gt; '2007'
+                          and TRI:ChemicalIdentification/sc:CASNumber = 'N150'
+                          and count(descendant-or-self::TRI:ToxicEquivalencyIdentification[TRI:ToxicEquivalencyNAIndicator = 'false']) &gt; 0">false</xsl:when>
+          <xsl:otherwise>true</xsl:otherwise>
+      </xsl:choose>
+      </xsl:variable>
+
+      <xsl:choose>
+      <xsl:when test="TRI:ReportType/TRI:ReportTypeCode = 'TRI_FORM_R'">
+          <xsl:if test="count(preceding::TRI:Report) &gt; 0">
+            <p style="page-break-before: always">&#160;</p>
+          </xsl:if>
+
+          <!-- Page 1 : Facility Information -->
+          <br/>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" border="0">
+            <tr>
+              <td align="center" width="100%">
+                <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+                  *** Do not send to EPA: This is the final copy of your form.***
+                &#160;</span>
+              </td>
+            </tr>
+
+            <xsl:if test="SubmissionStatusText">
+              <tr>
+                <td align="left">
+                  <span class="fieldLabel" style="color:red">
+                    Form Status:
+                    <xsl:value-of select="SubmissionStatusText"/>
+                  &#160;</span>
+                </td>
+              </tr>
+            </xsl:if>
+            <xsl:if test="ValidationStatusText">
+              <tr>
+                <td align="left">
+                  <span class="fieldLabel" style="color:red">
+                    Validation Status:
+                    <xsl:value-of select="ValidationStatusText"/>
+                  &#160;</span>
+                </td>
+              </tr>
+            </xsl:if>
+
+
+          </table>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 8pt" border="0">
+            <tr>
+              <td width="30%">
+              	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+                	<p style="font-size: 8pt">
+                	  Form Approved OMB Number:
+                	  <span class="smallAnswer">
+                	    <xsl:value-of select="$OMBNumberFormR"/>
+                	  &#160;</span>
+                	</p>
+                </xsl:if>
+              </td>
+              <td width="10%">
+                <br/>
+              </td>
+            </tr>
+            <tr>
+              <td width="60%">
+              	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	                <p style="font-size: 8pt"><i>(IMPORTANT: Read instructions before completing form; type or use fill-and-print form)</i></p>
+	            </xsl:if>
+              </td>
+              <td width="30%">
+              	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	                <p style="font-size: 8pt">
+    	              Approval Expires:
+        	          <span class="smallAnswer">
+            	        <xsl:value-of select="$ApprovalDateFormR"/>
+                	  &#160;</span>
+                	</p>
+                </xsl:if>
+              </td>
+              <td width="10%">
+                <p style="font-size: 8pt">
+                  <b>Page 1 of 5 </b>
+                </p>
+              </td>
+            </tr>
+
+          </table>
+          <center>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt;">
+              <tr>
+                <td colspan="2" align="center">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="0" cellspacing="0" cellpadding="0" frame="void">
+                    <tr>
+                      <td style="font-size: 8pt">
+                        <p style="font-size: 10pt"><b>EPA</b></p>
+                      </td>
+                      <td align="center" style="font-size: 10pt">
+                        <p style="font-size: 14pt"><b>FORM R</b></p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td>
+                        <p style="font-size: 8pt">
+                          United States <br/> Environmental Protection<br/>Agency
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          Section 313 of the Emergency Planning and Community Right-to-know Act of 1986,
+                          <br/>
+                          also known as Title III of the Superfund Amendments and Reauthorization Act.
+                        </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+                <td style="font-size:8pt">
+                    TRI Facility ID Number
+                    <hr />
+                    <span class="answerText">
+                      <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                    &#160;</span>
+                  <hr />
+                  Toxic Chemical, Category, or Generic Name
+                  <hr/>
+                  <span class="answerText">
+                    <xsl:choose>
+                      <xsl:when test="TRI:ChemicalIdentification/TRI:ChemicalNameText='NA'">
+                        <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalMixtureNameText"/>
+                      </xsl:when>
+                      <xsl:otherwise>
+                        <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalNameText"/>
+                      </xsl:otherwise>
+                    </xsl:choose>
+                  &#160;</span>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="3">
+                  <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt" frame="void">
+                    <tr>
+                      <td align="center" width="15%">
+                        <p style="font-size: 8pt">WHERE TO SEND COMPLETED FORMS: </p>
+                      </td>
+                      <td nowrap="nowrap">
+                        <p style="font-size: 8pt">
+                          1. TRI Data Processing Center
+                          <br />
+                          P.O. Box 10163
+                          <br />
+                          Fairfax, VA 22038
+                          <br />
+                        </p>
+                      </td>
+                      <td nowrap="nowrap">
+                        <p style="font-size: 8pt">2. APPROPRIATE STATE OFFICE<br/>(See instructions in Appendix F)</p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td colspan="3"></td>
+                    </tr>
+                  </table>
+                  <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" frame="void">
+                    <tr>
+                      <td width="33%">
+                        <p style="font-size: 9pt">This section only applies if you are revising or withdrawing a previously submitted form, otherwise leave blank:</p>
+                      </td>
+                      <td align="center" width="33%">
+                        <p style="font-size: 9pt">
+                          Revision (Enter up to two code(s))
+                          <br/>
+                          <br/>
+                          [
+                          <span class="answerText">
+                            <xsl:value-of select="TRI:ChemicalReportRevisionCode[1]"/>
+                          &#160;</span>
+                          ] [
+                          <span class="answerText">
+                            <xsl:value-of select="TRI:ChemicalReportRevisionCode[2]"/>
+                          &#160;</span>
+                          ]
+                        </p>
+                      </td>
+                      <td align="center" width="34%">
+                        <p style="font-size: 9pt">
+                          Withdrawal (Enter up to two code(s))
+                          <br/>
+                          <br/>
+                          [
+                          <span class="answerText">
+                            <xsl:value-of select="TRI:ChemicalReportWithdrawalCode[1]"/>
+                          &#160;</span>
+                          ] [
+                          <span class="answerText">
+                            <xsl:value-of select="TRI:ChemicalReportWithdrawalCode[2]"/>
+                          &#160;</span>
+                          ]
+                        </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td align="left" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Important: See Instructions to determine when "Not Applicable (NA)" boxes should be checked.</p>
+                </td>
+              </tr>
+              <tr>
+                <td align="center" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Part I. FACILITY IDENTIFICATION INFORMATION </p>
+                </td>
+              </tr>
+              <tr>
+                <td align="left" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">SECTION 1. REPORTING YEAR :
+                    <u><span class="answerText"><xsl:value-of select="TRI:SubmissionReportingYear"/></span></u>
+                  </p>
+                </td>
+              </tr>
+              <tr>
+                <td align="left" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">SECTION 2. TRADE SECRET INFORMATION</p>
+                </td>
+              </tr>
+              <tr>
+                <td align="left" style="font-size: 8pt">
+                    <dl>
+                      <dt>2.1 Are you claiming the toxic chemical identified on
+                          page 2 trade secret?</dt>
+                      <dd>
+                        [
+                        <xsl:choose>
+                          <xsl:when test="TRI:ChemicalTradeSecretIndicator = 'true'">
+                            <span class="answerText">X</span>
+                          </xsl:when>
+                        </xsl:choose>
+                        ] Yes (Answer question 2.2; attach substantiation forms)
+                      </dd>
+                      <dd>
+                        [
+                        <xsl:choose>
+                          <xsl:when test="TRI:ChemicalTradeSecretIndicator = 'false'">
+                            <span class="answerText">X</span>
+                          </xsl:when>
+                        </xsl:choose>
+                        ] NO (Do not answer 2.2; go to Section 3)
+                      </dd>
+                    </dl>
+                </td>
+                <td align="left" style="font-size: 8pt">
+                    <dl>
+                      <dt>2.2 Is this copy</dt>
+                      <dd>
+                        [
+                        ] Sanitized [
+                        ] Unsanitized
+                      </dd>
+                      <dd>(Answer only if "Yes" in 2.1)</dd>
+                    </dl>
+                </td>
+                <td>
+                  <br/>
+                </td>
+              </tr>
+              <tr>
+                <td align="left" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">SECTION 3. CERTIFICATION (Important: Read and sign after completing all form sections.)</p>
+                </td>
+              </tr>
+              <tr>
+                <td align="left" colspan="3">
+                  <p style="font-size: 8pt">
+                        I hereby certify that I have reviewed the attached documents and that, to the best of my knowledge and belief, the submitted
+                        information is true and complete and that the amounts and values in this report are accurate based on reasonable estimates using data
+                        available to the preparers of this report.
+                  </p>
+                  <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt" frame="above">
+                    <tr>
+                      <td>Name and official title of owner/operator or senior management official:</td>
+                      <td>Signature:</td>
+                      <td>Date Signed:</td>
+                    </tr>
+                    <tr>
+                      <td>
+  						<p>
+      						<span class="answerText"><xsl:value-of select="TRI:CertifierName"/>&#160;&#160;&#160;</span>
+      						<span class="answerText"><xsl:value-of select="TRI:CertifierTitleText"/></span>
+  						</p>
+					  </td>
+					  <td>
+    					<p>
+      						<span style="font-size: 9pt; color: red; font-weight: bold;">Reference Copy: Copy of Record Resides in CDX</span>
+    					</p>
+					  </td>
+					  <td>
+     					<span class="answerText">
+					    	<xsl:if test="TRI:CertificationSignedDate != '' and TRI:CertificationSignedDate != '1900-01-01'">
+	                    		<xsl:value-of select="TRI:CertificationSignedDate"/>
+	                   		</xsl:if>
+     					</span>
+					  </td>
+                    </tr>
+                  </table>
+                  </td>
+              </tr>
+              <tr>
+                <td align="left" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">SECTION 4. FACILITY IDENTIFICATION </p>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="3">
+                  <table summary="table used for layout purposes" width="100%" cellpadding="1" cellspacing="0" border="1" frame="void" style="font-size: 8pt">
+                    <tr>
+                      <td width="5%" style="font-size: 8pt">
+                        <p style="font-size: 8pt">4.1</p>
+                      </td>
+                      <td colspan="4" width="45%">&#160;</td>
+                      <td colspan="2" width="20%">
+                        <p style="font-size: 8pt">TRI Facility ID Number</p>
+                      </td>
+                      <td colspan="2" width="30%">
+                        <p>
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                          &#160;</span>
+                        </p>
+                      </td>
+                    </tr>
+
+                    <xsl:choose>
+                      <xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+	                    <tr>
+	                      <td colspan="5">
+	                        <p style="font-size: 7pt">
+	                          <u style="font-size: 7pt">Facility or Establishment Name</u>
+	                          <br/>
+	                          <span class="answerText">
+	                            <xsl:value-of select="../TRI:Facility/sc:FacilitySiteName"/>
+	                          </span>
+	                        </p>
+	                      </td>
+	                      <td colspan="4">
+	                        <p style="font-size: 7pt">
+	                          <u style="font-size: 7pt">Facility or Establishment Name or Mailing Address(if different from street address)</u>
+	                          <br/>
+	                          <span class="answerText">
+	                            <xsl:value-of select="../TRI:Facility/TRI:MailingFacilitySiteName"/>
+	                          </span>
+	                        </p>
+	                      </td>
+	                    </tr>
+                      </xsl:when>
+                      <xsl:otherwise>
+                        <tr>
+		                  <td colspan="9">
+		                   <p>
+		                    <u style="font-size: 7pt">Facility or Establishment Name</u>
+		                   </p>
+		                   <p>
+		                    <span class="answerText">
+		                     <xsl:value-of select="../TRI:Facility/sc:FacilitySiteName"/>
+		                    &#160;</span>
+		                   </p>
+		                  </td>
+		                </tr>
+                      </xsl:otherwise>
+                    </xsl:choose>
+
+                    <tr>
+                      <td colspan="5">
+                        <p>
+                          <u style="font-size: 7pt">Street</u>
+                          <br/>
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:LocationAddressText"/>
+                          &#160;</span>
+                        </p>
+                      </td>
+                      <td colspan="4">
+                        <p>
+                          <u style="font-size: 7pt">Mailing Address (if different from physical street address)</u>
+                          <br/>
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:MailingAddressText"/>
+                          &#160;</span>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td colspan="5">
+                        <p>
+                        <xsl:choose>
+                            <xsl:when test="TRI:SubmissionReportingYear >= '2012' ">
+                               <u style="font-size: 7pt">City/County/Tribe/State/ZIP Code</u>
+                               <br/>
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:LocalityName"/>
+                          &#160;</span>
+                          /
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:CountyIdentity/sc:CountyName"/>
+                          &#160;</span>
+                           /
+                          <span class="answerText">
+                           BIA Code: <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:TribalIdentity/sc:TribalCode"/>
+                          &#160;</span>
+                          /
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:StateIdentity/sc:StateName"/>
+                          &#160;</span>
+                          /
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:AddressPostalCode"/>
+                          &#160;</span>
+                          </xsl:when>
+
+                          <xsl:otherwise>
+                            <u style="font-size: 7pt">City/County/State/ZIP Code</u>
+                               <br/>
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:LocalityName"/>
+                          &#160;</span>
+                          /
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:CountyIdentity/sc:CountyName"/>
+                          &#160;</span>
+                          /
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:StateIdentity/sc:StateName"/>
+                          &#160;</span>
+                          /
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:AddressPostalCode"/>
+                          &#160;</span>
+                          </xsl:otherwise>
+                          </xsl:choose>
+
+                        </p>
+                      </td>
+                      <td colspan="3">
+                        <p>
+                          <u style="font-size: 7pt">City/State/ZIP Code</u>
+                          <br/>
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:MailingAddressCityName"/>
+                          &#160;</span>
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/TRI:ProvinceNameText"/>
+                          &#160;</span>
+                          /
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:StateIdentity/sc:StateName"/>
+                          &#160;</span>
+                          /
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:AddressPostalCode"/>
+                          &#160;</span>
+                        </p>
+                      </td>
+                      <td colspan="1" width="15%">
+                        <p>
+                          <u style="font-size: 7pt">Country (Non-US)</u>
+                          <br/>
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:CountryIdentity/sc:CountryName"/>
+                          &#160;</span>
+                        </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="3">
+                  <table summary="table used for layout purposes" width="100%" cellpadding="1" cellspacing="0" border="1"
+                         frame="void" style="font-size: 8pt">
+                    <tr>
+                      <td width="5%" style="font-size: 8pt">
+                        <p style="font-size: 8pt">4.2</p>
+                      </td>
+                      <td nowrap="nowrap">
+                        <p style="font-size: 8pt">
+                          This report contains information for :
+                          <br/>
+                          (
+                          <u>Important: </u>
+                          check a or b; check c or d if applicable)
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          a. [
+                          <xsl:choose>
+                            <xsl:when test="TRI:SubmissionPartialFacilityIndicator = 'false'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ] An Entire facility
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          b. [
+                          <xsl:choose>
+                            <xsl:when test="TRI:SubmissionPartialFacilityIndicator = 'true'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ] Part of a facility
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          c. [
+                          <xsl:choose>
+                            <xsl:when test="TRI:SubmissionFederalFacilityIndicator = 'Y'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ] A Federal facility
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          d. [
+                          <xsl:choose>
+                            <xsl:when test="TRI:SubmissionGOCOFacilityIndicator = 'true'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ] GOCO
+                        </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="3">
+                  <table summary="table used for layout purposes" width="100%" cellpadding="1" cellspacing="0" border="1"
+                         frame="void" style="font-size: 8pt">
+                    <tr>
+                      <td width="5%" style="font-size: 8pt">
+                        <p style="font-size: 8pt">4.3</p>
+                      </td>
+                      <td colspan="2" nowrap="nowrap" align="center">
+                        <p style="font-size: 8pt">Technical Contact name </p>
+                      </td>
+                      <td colspan="2">
+                        <span class="answerText" style="width:150px; word-wrap:break-word;">
+                          <xsl:value-of select="TRI:TechnicalContactNameText/sc:IndividualFullName"/>
+                        &#160;</span>
+                      </td>
+                      <td colspan="2" nowrap="nowrap">
+                        <p style="font-size: 8pt">
+                          <u style="font-size: 7pt">Email Address</u>
+                          <br/>
+                          <span class="answerText">
+                            <xsl:value-of select="TRI:TechnicalContactEmailAddressText"/>
+                          &#160;</span>
+                        </p>
+                      </td>
+                      <td colspan="2" nowrap="nowrap">
+                        <p style="font-size: 8pt">
+       					<xsl:choose>
+							<xsl:when test="TRI:SubmissionReportingYear &gt; '2013' ">
+        						<u style="font-size: 7pt">Telephone Number (include area code and ext.)</u>
+        		 			</xsl:when>
+        					<xsl:otherwise>
+        						<u style="font-size: 7pt">Telephone Number (include area code)</u>
+        					</xsl:otherwise>
+       					</xsl:choose>
+                          <br/>
+                          <span class="answerText">
+                            <xsl:value-of select="substring(TRI:TechnicalContactPhoneText,1, 3)"/>&#45;<xsl:value-of select="substring(TRI:TechnicalContactPhoneText,4, 3)"/>&#45;<xsl:value-of select="substring(TRI:TechnicalContactPhoneText,7)"/>
+                          &#160;</span>
+                          <xsl:if test="TRI:SubmissionReportingYear &gt; '2013' ">
+                          	 <span class="answerText">
+                            	<xsl:if test="string-length(TRI:TechnicalContactPhoneExtText) &gt; 0 ">
+									&#045; &#160;<xsl:value-of select="TRI:TechnicalContactPhoneExtText"/>
+								</xsl:if>
+                          	&#160;</span>
+                          </xsl:if>
+                        </p>
+                      </td>
+                    </tr>
+                    <xsl:choose>
+                      <xsl:when test="TRI:SubmissionReportingYear >= '2007' or TRI:SubmissionReportingYear &lt;= '2004'">
+                        <tr>
+                          <td width="5%" style="font-size: 8pt">
+                            <p style="font-size: 8pt">4.4</p>
+                          </td>
+                          <td colspan="2" nowrap="nowrap" align="center">
+                            <p style="font-size: 8pt">Public Contact name </p>
+                          </td>
+                          <td colspan="2">
+                            <span class="answerText">
+                              <xsl:value-of select="TRI:PublicContactNameText"/>
+                            &#160;</span>
+                          </td>
+                          <td colspan="2" nowrap="nowrap">
+                            <p style="font-size: 8pt">
+                              <u style="font-size: 7pt">Email Address</u>
+                              <br/>
+                              <span class="answerText">
+                                <xsl:value-of select="TRI:PublicContactEmailAddressText"/>
+                              &#160;</span>
+                            </p>
+                          </td>
+                          <td colspan="2" nowrap="nowrap">
+                            <p style="font-size: 8pt">
+                            <xsl:choose>
+								<xsl:when test="TRI:SubmissionReportingYear &gt; '2013' ">
+        							<u style="font-size: 7pt">Telephone Number (include area code and ext.)</u>
+        						</xsl:when>
+        						<xsl:otherwise>
+        							<u style="font-size: 7pt">Telephone Number (include area code)</u>
+        						</xsl:otherwise>
+       						</xsl:choose>
+                              <br/>
+                              <span class="answerText">
+                              	<xsl:if test="string-length(TRI:PublicContactPhoneText)  &gt; 0">
+                              		<xsl:value-of select="substring(TRI:PublicContactPhoneText,1, 3)"/>&#45;<xsl:value-of select="substring(TRI:PublicContactPhoneText,4, 3)"/>&#45;<xsl:value-of select="substring(TRI:PublicContactPhoneText,7)"/>
+                              	</xsl:if>
+                              &#160;</span>
+                              <xsl:if test="TRI:SubmissionReportingYear &gt; '2013' ">
+                          		 <span class="answerText">
+                            		<xsl:if test="string-length(TRI:PublicContactPhoneExtText) &gt; 0 ">
+										&#045; &#160;<xsl:value-of select="TRI:PublicContactPhoneExtText"/>
+									</xsl:if>
+                          		&#160;</span>
+                          	  </xsl:if>
+                            </p>
+                          </td>
+                        </tr>
+                      </xsl:when>
+                      <xsl:otherwise>
+                        <tr>
+                          <td width="5%" style="font-size: 8pt">
+                            <p style="font-size: 8pt">4.4</p>
+                          </td>
+                          <td colspan="2" nowrap="nowrap" align="center">
+                            <p style="font-size: 8pt">Public Contact name </p>
+                          </td>
+                          <td colspan="4">
+                            <span class="answerText">
+                              <xsl:value-of select="TRI:PublicContactNameText"/>
+                            &#160;</span>
+                          </td>
+                          <td colspan="2" nowrap="nowrap">
+                            <p style="font-size: 8pt">
+                            <xsl:choose>
+								<xsl:when test="TRI:SubmissionReportingYear &gt; '2013' ">
+        							<u style="font-size: 7pt">Telephone Number (include area code and ext.)</u>
+        						</xsl:when>
+        						<xsl:otherwise>
+        							<u style="font-size: 7pt">Telephone Number (include area code)</u>
+        						</xsl:otherwise>
+       						</xsl:choose>
+                              <br/>
+                              <span class="answerText">
+                               <xsl:if test="string-length(TRI:PublicContactPhoneText)  &gt; 0">
+                                <xsl:value-of select="substring(TRI:PublicContactPhoneText,1, 3)"/>&#45;<xsl:value-of select="substring(TRI:PublicContactPhoneText,4, 3)"/>&#45;<xsl:value-of select="substring(TRI:PublicContactPhoneText,7)"/>
+                                </xsl:if>
+                              &#160;</span>
+                              <xsl:if test="TRI:SubmissionReportingYear &gt; '2013' ">
+                          		 <span class="answerText">
+                            		<xsl:if test="string-length(TRI:PublicContactPhoneExtText) &gt; 0 ">
+										&#045; &#160;<xsl:value-of select="TRI:PublicContactPhoneExtText"/>
+									</xsl:if>
+                          		&#160;</span>
+                          	  </xsl:if>
+                            </p>
+                          </td>
+                        </tr>
+                      </xsl:otherwise>
+                    </xsl:choose>
+                    <xsl:choose>
+                      <xsl:when test="TRI:SubmissionReportingYear &lt;= '2005'">
+                        <tr>
+                          <td width="5%" style="font-size: 8pt">
+                            <p style="font-size: 8pt">4.5</p>
+                          </td>
+                          <td colspan="2" nowrap="nowrap" width="35%"
+                              align="center">
+                            <p style="font-size: 8pt">SIC Code(s) (4 digits)</p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              a.
+                              <xsl:for-each select="../TRI:Facility/TRI:FacilitySIC">
+                                <xsl:choose>
+                                  <xsl:when test="sc:SICPrimaryIndicator = 'Primary'">
+                                    <span class="answerText">
+                                      <xsl:value-of select="sc:SICCode"/>
+                                      (Primary)
+                                    &#160;</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              b.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 1">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[2]/sc:SICCode"/>
+                                  &#160;</span>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              c.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 2">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[3]/sc:SICCode"/>
+                                  &#160;</span>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              d.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 3">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[4]/sc:SICCode"/>
+                                  &#160;</span>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              e.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 4">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[5]/sc:SICCode"/>
+                                  &#160;</span>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              f.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 5">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[6]/sc:SICCode"/>
+                                  &#160;</span>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                        </tr>
+                      </xsl:when>
+                      <xsl:otherwise>
+                        <tr>
+                          <td width="5%" style="font-size: 8pt">
+                            <p style="font-size: 8pt">4.5</p>
+                          </td>
+                          <td colspan="2" nowrap="nowrap" width="35%"
+                              align="center">
+                            <p style="font-size: 8pt">NAICS Code(s) (6 digits)</p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              a.
+                              <xsl:for-each select="../TRI:Facility/TRI:FacilityNAICS">
+                                <xsl:choose>
+                                  <xsl:when test="sc:NAICSPrimaryIndicator = 'Primary'">
+                                    <span class="answerText">
+                                      <xsl:value-of select="sc:NAICSCode"/>
+                                      (Primary)
+                                    &#160;</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              b.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 1">
+                                <xsl:choose>
+                                  <xsl:when test="../TRI:Facility/TRI:FacilityNAICS[1]/sc:NAICSPrimaryIndicator = 'Unknown'">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[1]/sc:NAICSCode"/>
+                                  &#160;</span>
+                                  </xsl:when>
+                                  <xsl:when test="../TRI:Facility/TRI:FacilityNAICS[2]/sc:NAICSPrimaryIndicator = 'Unknown'">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[2]/sc:NAICSCode"/>
+                                  &#160;</span>
+                                  </xsl:when>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              c.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 2">
+                                  <xsl:choose>
+                                  <xsl:when test="../TRI:Facility/TRI:FacilityNAICS[3]/sc:NAICSPrimaryIndicator = 'Unknown'">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[3]/sc:NAICSCode"/>
+                                  &#160;</span>
+                                  </xsl:when>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              d.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 3">
+                                   <xsl:choose>
+                                  <xsl:when test="../TRI:Facility/TRI:FacilityNAICS[4]/sc:NAICSPrimaryIndicator = 'Unknown'">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[4]/sc:NAICSCode"/>
+                                  &#160;</span>
+                                  </xsl:when>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              e.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 4">
+                                   <xsl:choose>
+                                  <xsl:when test="../TRI:Facility/TRI:FacilityNAICS[5]/sc:NAICSPrimaryIndicator = 'Unknown'">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[5]/sc:NAICSCode"/>
+                                  &#160;</span>
+                                  </xsl:when>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                          <td colspan="1" width="10%">
+                            <p style="font-size: 8pt">
+                              f.
+                              <xsl:choose>
+                                <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 5">
+                                   <xsl:choose>
+                                  <xsl:when test="../TRI:Facility/TRI:FacilityNAICS[6]/sc:NAICSPrimaryIndicator = 'Unknown'">
+                                  <span class="answerText">
+                                    <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[6]/sc:NAICSCode"/>
+                                  &#160;</span>
+                                  </xsl:when>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </p>
+                          </td>
+                        </tr>
+                      </xsl:otherwise>
+                    </xsl:choose>
+                    <tr>
+                      <td colspan="9">
+                        <table summary="table used for layout purposes" width="100%" cellpadding="1" cellspacing="0"
+                               border="1" frame="void" style="font-size: 8pt"
+                               rules="all">
+                          <tr>
+                            <td width="5%" style="font-size: 8pt">
+                              <p style="font-size: 8pt">4.6</p>
+                            </td>
+                            <td nowrap="nowrap">
+                              <p style="font-size: 8pt">
+                                Dun and Bradstreet
+                                <br/>
+                                Number(s) (9 digits)
+                              </p>
+                            </td>
+                          </tr>
+                          <tr>
+                            <td colspan="2">
+                              <p style="font-size: 8pt">
+                                a.
+                                <span class="answerText">
+                                  <xsl:value-of select="../TRI:Facility/TRI:FacilityDunBradstreetCode[1]"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                          </tr>
+                          <tr>
+                            <td colspan="2">
+                              <p style="font-size: 8pt">
+                                b.
+                                <span class="answerText">
+                                  <xsl:value-of select="../TRI:Facility/TRI:FacilityDunBradstreetCode[2]"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                          </tr>
+                        </table>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td align="left" colspan="9" style="font-size: 8pt">
+                        <p style="font-size: 8pt">SECTION 5. PARENT COMPANY INFORMATION</p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" style="font-size: 8pt">
+                        <p style="font-size: 8pt">5.1</p>
+                      </td>
+                      <td colspan="2" align="left">
+                        <p style="font-size: 8pt">
+                        <xsl:choose>
+						  <xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+						    Name of Parent Company
+						  </xsl:when>
+						  <xsl:otherwise>
+						    Name of U.S. Parent Company (for TRI Reporting purposes)
+						  </xsl:otherwise>
+						</xsl:choose>
+                        </p>
+                      </td>
+                      <xsl:choose>
+						  <xsl:when test="TRI:SubmissionReportingYear &gt; '2010'">
+						  <td colspan="5">
+                        <span class="answerText">
+                        <xsl:if test="../TRI:Facility/TRI:ParentCompanyNameText != 'NA'">
+                    		<xsl:value-of select="../TRI:Facility/TRI:ParentCompanyNameText"/>
+                   		</xsl:if>
+                        &#160;</span>
+                        <br/>
+                      </td>
+                      <td colspan="1">
+                        <p style="font-size: 8pt">
+						    No U.S. Parent Company (for TRI Reporting purposes) [
+					    <xsl:choose>
+                            <xsl:when test="../TRI:Facility/TRI:ParentCompanyNameNAIndicator = 'true'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ]
+                        </p>
+                      </td>
+						  </xsl:when>
+						  <xsl:otherwise>
+					                       <td colspan="1">
+                        <p style="font-size: 8pt">
+						    NA [
+
+					    <xsl:choose>
+                            <xsl:when test="../TRI:Facility/TRI:ParentCompanyNameNAIndicator = 'true'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ]
+                        </p>
+                      </td>
+                      <td colspan="5">
+                        <span class="answerText">
+                          <xsl:value-of select="../TRI:Facility/TRI:ParentCompanyNameText"/>
+                        &#160;</span>
+                        <br/>
+                      </td>
+					  	  </xsl:otherwise>
+					  </xsl:choose>
+
+                    </tr>
+                    <tr>
+                      <td width="5%" style="font-size: 8pt">
+                        <p style="font-size: 8pt">5.2</p>
+                      </td>
+                      <td colspan="2" align="left">
+                        <p style="font-size: 8pt">Parent Company's Dun &amp; Bradstreet Number </p>
+                      </td>
+                      <td colspan="1">
+                        <p style="font-size: 8pt">
+                          NA [
+                          <xsl:choose>
+                            <xsl:when test="../TRI:Facility/TRI:ParentDunBradstreetCode = 'NA'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ]
+                        </p>
+                      </td>
+                      <td colspan="5">
+                        <xsl:choose>
+                          <xsl:when test="../TRI:Facility/TRI:ParentDunBradstreetCode != 'NA'">
+                            <span class="answerText">
+                              <xsl:value-of select="../TRI:Facility/TRI:ParentDunBradstreetCode"/>
+                            &#160;</span>
+                          </xsl:when>
+                        </xsl:choose>
+                        <br/>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+            </table>
+          </center>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 7pt" border="0">
+            <tr>
+              <td width="60%">
+                <p style="font-size: 8pt">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+                  		EPA Form 9350-1 (Rev. <xsl:value-of select="$RevisionDateFormR"/>) - Previous editions are obsolete.
+                  	</xsl:if>
+                </p>
+              </td>
+              <td width="30%">
+                <p style="font-size: 8pt">Printed using TRI-MEweb</p>
+              </td>
+            </tr>
+          </table>
+
+          <p style="page-break-before: always">&#160;</p>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="1" style="font-size: 8pt" border="0">
+            <tr>
+            <!--<td width="90%">
+                <a name="PG-2_{$formID}"></a>
+                <p style="font-size: 8pt">
+                  <a href="#PG-1_{$formID}">1</a>
+                  <a href="#PG-2_{$formID}">2</a>
+                  <a href="#PG-3_{$formID}">3</a>
+                  <a href="#PG-4_{$formID}">4</a>
+                  <a href="#PG-5_{$formID}">5</a>
+                  <a href="#PG-6_{$formID}">Additional Info</a>
+                  <xsl:if test="$ScheduleOneNA = 'false'">
+                      <a href="#S1_PG-1_{$formID}">Schedule 1</a>
+                  </xsl:if>
+                </p>
+              </td>-->
+              <td width="10%">
+                <p style="font-size: 8pt">
+                  <b>Page 2 of 5 </b>
+                </p>
+              </td>
+            </tr>
+          </table>
+          <center>
+          <tr>
+	              <td align="center" width="100%">
+	                <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+	                  *** Do not send to EPA: This is the final copy of your form.***
+	                &#160;</span>
+	              </td>
+           </tr>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt">
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+                         cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td width="65%" align="center" style="font-size: 10pt">
+                        <p style="font-size: 10pt">
+                          <b>EPA FORM R</b>
+                          <br/>
+                          <b>PART II. CHEMICAL - SPECIFIC INFORMATION</b>
+                        </p>
+                      </td>
+                      <td>
+                          TRI Facility ID Number
+                          <hr />
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                          &#160;</span>
+                        <hr />
+                        Toxic Chemical, Category, or Generic Name
+                        <hr/>
+                        <span class="answerText">
+                          <xsl:choose>
+                            <xsl:when test="TRI:ChemicalIdentification/TRI:ChemicalNameText='NA'">
+                              <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalMixtureNameText"/>
+                            </xsl:when>
+                            <xsl:otherwise>
+                              <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalNameText"/>
+                            </xsl:otherwise>
+                          </xsl:choose>
+                        &#160;</span>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0"
+                         cellpadding="1">
+                    <tr>
+                      <td align="left" style="font-size: 8pt">
+                        <p style="font-size: 8pt">SECTION 1. TOXIC CHEMICAL IDENTITY </p>
+                      </td>
+                      <td align="left" style="font-size: 8pt">
+                        <p style="font-size: 8pt">(Important: DO NOT complete this section if you are reporting a mixture component in Section 2 below.)</p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td align="center" width="5%">
+                  <p style="font-size: 8pt">1.1</p>
+                </td>
+                <td width="95%" style="font-size: 8pt">
+                    CAS Number (Important: Enter only one number exactly as it
+                    appears on the Section 313 list. Enter category code if
+                    reporting a chemical category.)
+                    <hr />
+                    <span style="color: blue;text-indent: 5em;font-weight:bold">
+                      <xsl:value-of select="TRI:ChemicalIdentification/sc:CASNumber"/>
+                    &#160;</span>
+                </td>
+              </tr>
+              <tr>
+                <td align="center" width="5%">
+                  <p style="font-size: 8pt">1.2</p>
+                </td>
+                <td style="font-size: 8pt">
+                    Toxic Chemical or Chemical Category Name (Important: Enter
+                    only one name exactly as it appears on the Section 313 list.)
+                    <hr />
+                    <span style="color: blue;font-size: 8pt;text-indent: 5em;font-weight:bold">
+                      <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalNameText"/>
+                    &#160;</span>
+                </td>
+              </tr>
+              <tr>
+                <td align="center" width="5%">
+                  <p style="font-size: 8pt">1.3</p>
+                </td>
+                <td style="font-size: 8pt">
+                    Generic Chemical Name (Important: Complete only if Part I,
+                    Section 2.1 is checked "Yes". Generic Name must be
+                    structurally descriptive).
+                    <hr />
+                    <span style="color: blue;font-size: 8pt;text-indent: 5em;font-weight:bold">NA&#160;</span>
+                </td>
+              </tr>
+
+              <!-- Section 1.4, only display if < RY08 -->
+              <xsl:if test="TRI:SubmissionReportingYear &lt;= '2008' and TRI:SubmissionReportingYear >= '2000'">
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1" cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td align="center" width="5%">
+                        <p style="font-size: 8pt">1.4</p>
+                      </td>
+                      <td colspan="17">
+                        <p style="font-size: 8pt">
+                          Distribution of Each Member of the Dioxin and
+                          Dioxin-like Compounds Category.
+                          <br/>
+                          (If there are any numbers in boxes 1-17, then every
+                          field must be filled in with either 0 or some number
+                          between 0.01 and 100. Distribution should be reported
+                          in percentages and the total should equal 100%. If you
+                          do not have speciation data available, indicate NA.)
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <xsl:for-each select="TRI:ChemicalIdentification">
+                        <xsl:choose>
+                          <xsl:when test="TRI:DioxinDistributionNAIndicator= 'true'">
+                            <td align="center" width="5%">
+                              <p style="font-size: 8pt">
+                                NA [
+                                <span class="answerText">X</span>
+                                ]
+                              </p>
+                            </td>
+                            <td><p style="font-size: 8pt">1<hr/></p></td>
+                            <td><p style="font-size: 8pt">2<hr/></p></td>
+                            <td><p style="font-size: 8pt">3<hr/></p></td>
+                            <td><p style="font-size: 8pt">4<hr/></p></td>
+                            <td><p style="font-size: 8pt">5<hr/></p></td>
+                            <td><p style="font-size: 8pt">6<hr/></p></td>
+                            <td><p style="font-size: 8pt">7<hr/></p></td>
+                            <td><p style="font-size: 8pt">8<hr/></p></td>
+                            <td><p style="font-size: 8pt">9<hr/></p></td>
+                            <td><p style="font-size: 8pt">10<hr/></p></td>
+                            <td><p style="font-size: 8pt">11<hr/></p></td>
+                            <td><p style="font-size: 8pt">12<hr/></p></td>
+                            <td><p style="font-size: 8pt">13<hr/></p></td>
+                            <td><p style="font-size: 8pt">14<hr/></p></td>
+                            <td><p style="font-size: 8pt">15<hr/></p></td>
+                            <td><p style="font-size: 8pt">16<hr/></p></td>
+                            <td><p style="font-size: 8pt">17<hr/></p></td>
+                          </xsl:when>
+                          <xsl:otherwise>
+                            <td align="center" width="5%">
+                              <p style="font-size: 8pt">NA [ ]</p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                1
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution1Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                2
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution2Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                3
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution3Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                4
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution4Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                5
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution5Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                6
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution6Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                7
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution7Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                8
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution8Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                9
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution9Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                10
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution10Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                11
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution11Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                12
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution12Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                13
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution13Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                14
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution14Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                15
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution15Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                16
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution16Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                17
+                                <hr/>
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:DioxinDistribution17Percent"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                          </xsl:otherwise>
+                        </xsl:choose>
+                      </xsl:for-each>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              </xsl:if>
+              <!-- End prior to RY08 dioxin section -->
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0"
+                         cellpadding="1">
+                    <tr>
+                      <td align="left" colspan="2" style="font-size: 8pt">
+                        <p style="font-size: 8pt">SECTION 2. MIXTURE COMPONENT
+                                                  IDENTITY (Important: DO NOT
+                                                  complete this section if you
+                                                  completed Section 1.)</p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td align="center" width="5%">
+                  <p style="font-size: 8pt">2.1</p>
+                </td>
+                <td style="font-size: 8pt">
+                    Generic Chemical Name Provided by Supplier (Important:
+                    Maximum of 70 characters, including numbers, spaces, and
+                    punctuation.)
+                    <hr />
+                    <b style="color: blue;font-size: 9pt; font-family:arial">
+                      <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalMixtureNameText"/>
+                    </b>
+                    <br />
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0" cellpadding="1">
+                    <tr>
+                      <td align="left" colspan="2" style="font-size: 8pt">
+                          SECTION 3. ACTIVITIES AND USES OF THE TOXIC CHEMICAL AT THE FACILITY
+                          <br />
+                          (Important: Check all that apply.)
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1" cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td align="center" width="5%">3.1</td>
+                      <td>Manufacture the toxic chemical:</td>
+                      <td align="center" width="5%">3.2</td>
+                      <td>Process the toxic chemical:</td>
+                      <td align="center" width="5%">3.3</td>
+                      <td>Otherwise use the toxic chemical:</td>
+                    </tr>
+                    <tr>
+                      <td colspan="2" align="center">
+                          a. [
+                          <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                            <xsl:choose>
+                              <xsl:when test="TRI:ChemicalProducedIndicator = 'true'">
+                                <span class="answerText">X</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          ] Produce b. [
+                          <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                            <xsl:choose>
+                              <xsl:when test="TRI:ChemicalImportedIndicator = 'true'">
+                                <span class="answerText">X</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          ] Import
+                      </td>
+                      <td colspan="4"><br /></td>
+                    </tr>
+                    <tr>
+                      <td colspan="2" style="font-size: 8pt">
+                          <dl>
+                            <dt>If produce or import:</dt>
+                            <dd>
+                              c. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalUsedProcessedIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] For on-site use/processing
+                            </dd>
+                            <dd>
+                              d. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalSalesDistributionIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] For sale/distribution
+                            </dd>
+                            <dd>
+                              e. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalByproductIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] As a byproduct
+                            </dd>
+                            <dd>
+                              f. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalManufactureImpurityIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] As an impurity
+                            </dd>
+                          </dl>
+                      </td>
+                      <td colspan="2" style="font-size: 8pt">
+                          <dl>
+                            <dd>
+                              a. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalReactantIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] As a reactant
+                            </dd>
+                            <dd>
+                              b. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalFormulationComponentIndicator= 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] As a formulation component
+                            </dd>
+                            <dd>
+                              c. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalArticleComponentIndicator= 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] As an article component
+                            </dd>
+                            <dd>
+                              d. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalRepackagingIndicator= 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] Repackaging
+                            </dd>
+                            <dd>
+                              e. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalProcessImpurityIndicator= 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] As an impurity
+                            </dd>
+                          </dl>
+                      </td>
+                      <td colspan="2" style="font-size: 8pt">
+                          <dl>
+                            <dd>
+                              a. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalProcessingAidIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] As a chemical processing aid
+                            </dd>
+                            <dd>
+                              b. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalManufactureAidIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] As a manufacturing aid
+                            </dd>
+                            <dd>
+                              c. [
+                              <xsl:for-each select="TRI:ChemicalActivitiesAndUses">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:ChemicalAncillaryUsageIndicator= 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:for-each>
+                              ] Ancillary or other use
+                            </dd>
+                          </dl>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0"
+                         cellpadding="1">
+                    <tr>
+                      <td align="left" colspan="2" style="font-size: 8pt">
+                        <p style="font-size: 8pt">SECTION 4. MAXIMUM AMOUNT OF
+                                                  THE TOXIC CHEMICAL ON-SITE AT
+                                                  ANY TIME DURING THE CALENDAR
+                                                  YEAR </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td align="right" width="5%">
+                  <p style="font-size: 8pt">4.1</p>
+                </td>
+                <td style="font-size: 8pt">
+                  [
+                  <span class="answerText">
+                    <xsl:if test="not(string-length(TRI:MaximumChemicalAmountCode)=0)">
+                      <xsl:value-of select="TRI:MaximumChemicalAmountCode"/>
+                    </xsl:if>
+                  &#160;</span>
+                  ] (Enter two-digit code from instruction package.)
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0"
+                         cellpadding="1">
+                    <tr>
+                      <td align="left" colspan="2" style="font-size: 8pt">
+                        <p style="font-size: 8pt">SECTION 5.QUANTITY OF THE
+                                                  TOXIC CHEMICAL ENTERING EACH
+                                                  ENVIRONMENTAL MEDIUM ON-SITE </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+                         cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td colspan="3"></td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          A. Total Release (pounds/year*)
+                          <br/>
+                          (Enter range code or estimate**)
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          B. Basis of Estimate
+                          <br/>
+                          (Enter code)
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">C. Percent from Stormwater</p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td align="center" width="5%">
+                        <p style="font-size: 8pt">5.1</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Fugitive or non-point
+                          <br/>
+                          air emissions
+                        </p>
+                      </td>
+                      <td style="font-size: 8pt">
+                        <p style="font-size: 8pt">
+                          NA [
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'AIR FUG'">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          ]
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'AIR FUG'">
+                                <span class="answerText">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+                                      <br/>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+                                      <br/>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                &#160;</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'AIR FUG'">
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+                                &#160;</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td style="background-color: gray">&#160;</td>
+                    </tr>
+                    <tr>
+                      <td align="center" width="5%">
+                        <p style="font-size: 8pt">5.2</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Stack or point
+                          <br/>
+                          air emissions
+                        </p>
+                      </td>
+                      <td style="font-size: 8pt">
+                        <p style="font-size: 8pt">
+                          NA [
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'AIR STACK'">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          ]
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'AIR STACK'">
+                                <span class="answerText">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+                                      <br/>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+                                      <br/>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                &#160;</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'AIR STACK'">
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+                                &#160;</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td style="background-color: gray">&#160;</td>
+                    </tr>
+                    <tr>
+                      <td align="center" width="5%">
+                        <p style="font-size: 8pt">5.3</p>
+                      </td>
+	                  <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Discharges to receiving streams or
+	                          <br/>
+	                          water bodies (Enter one name per box)
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <xsl:choose>
+							  <xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+							    &#160;
+							  </xsl:when>
+							  <xsl:otherwise>
+								<p style="font-size: 8pt">
+								  NA [
+								  <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+									<xsl:choose>
+									  <xsl:when test="TRI:EnvironmentalMediumCode = 'WATER'">
+										<xsl:choose>
+										  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+											<span class="answerText">X</span>
+										  </xsl:when>
+										</xsl:choose>
+									  </xsl:when>
+									</xsl:choose>
+								  </xsl:for-each>
+								  ]
+								</p>
+							  </xsl:otherwise>
+							</xsl:choose>
+	                  </td>
+					  <td colspan="2" style="background-color: gray">&#160;</td>
+                      <td style="background-color: gray">&#160;</td>
+                    </tr>
+                    <tr>
+                      <td colspan="2" style="font-size: 9pt" align="center">
+                        <p style="font-size: 8pt">Stream or Water Body Name </p>
+                      </td>
+                      <xsl:choose>
+                      	<xsl:when test="TRI:SubmissionReportingYear &gt; '2013'">
+                      		<td style="font-size: 9pt" align="center">
+                      			<p style="font-size: 8pt">Reach Code (optional)</p>
+                      		</td>
+                      	</xsl:when>
+                      </xsl:choose>
+                      <td>
+                        <br/>
+                      </td>
+                      <td>
+                        <br/>
+                      </td>
+                      <td>
+                        <br/>
+                      </td>
+                    </tr>
+                    <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                      <xsl:choose>
+                        <xsl:when test="TRI:EnvironmentalMediumCode = 'WATER'">
+                          <xsl:choose>
+                            <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+                              <tr>
+                                <td align="center" width="5%">
+                                  <p style="font-size: 8pt">5.3.1</p>
+                                </td>
+                                <td colspan="2">
+                                  <p style="font-size: 8pt">
+                                    <span class="answerText">NA&#160;</span>
+                                    <br/>
+                                  </p>
+                                </td>
+                                <td></td>
+                                <td></td>
+                                <td></td>
+                                <xsl:choose>
+                                	<xsl:when test="TRI:SubmissionReportingYear &gt; '2013'">
+                                		<td></td>
+                               	 	</xsl:when>
+                                </xsl:choose>
+                              </tr>
+                            </xsl:when>
+                            <xsl:otherwise>
+                              <tr>
+                                <td align="center" width="5%">
+                                  <p style="font-size: 8pt">
+                                    5.3.<xsl:value-of select="TRI:WaterStream/TRI:WaterSequenceNumber"/>
+                                  </p>
+                                </td>
+                                <td>
+                                  <p style="font-size: 8pt">
+                                    <span class="answerText">
+                                      <xsl:value-of select="TRI:WaterStream/TRI:StreamName"/>
+                                    &#160;</span>
+                                    <br/>
+                                  </p>
+                                </td>
+                                <xsl:choose>
+	                            <xsl:when test="../TRI:SubmissionReportingYear &gt; '2013'">
+	                                	<td>
+	                                	  <p style="font-size: 8pt">
+	                                	    <span class="answerText">
+	                                	      <xsl:value-of select="TRI:WaterStream/TRI:StreamReachCode"/>
+	                                	    &#160;</span>
+	                                	    <br/>
+	                                	  </p>
+	                                	</td>
+	                                </xsl:when>
+                                </xsl:choose>
+                                <td>
+                                  <p style="font-size: 8pt">
+                                    <span class="answerText">
+                                      <xsl:choose>
+                                        <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+                                          <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+                                        </xsl:when>
+                                        <xsl:otherwise>
+                                          <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+                                        </xsl:otherwise>
+                                      </xsl:choose>
+                                    &#160;</span>
+                                    <br/>
+                                  </p>
+                                </td>
+                                <td>
+                                  <p style="font-size: 8pt">
+                                    <span class="answerText">
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+                                    &#160;</span>
+                                    <br/>
+                                  </p>
+                                </td>
+                                <td>
+                                  <p style="font-size: 8pt">
+                                    <span class="answerText">
+                                      <xsl:choose>
+                                      <xsl:when test="TRI:WaterStream/TRI:ReleaseStormWaterNAIndicator = 'true'">NA</xsl:when>
+                                      <xsl:otherwise><xsl:value-of select="TRI:WaterStream/TRI:ReleaseStormWaterPercent"/>%</xsl:otherwise>
+                                      </xsl:choose>
+                                    &#160;</span>
+                                    <br/>
+                                  </p>
+                                </td>
+                              </tr>
+                            </xsl:otherwise>
+                          </xsl:choose>
+                        </xsl:when>
+                      </xsl:choose>
+                    </xsl:for-each>
+                  </table>
+                </td>
+              </tr>
+            </table>
+          </center>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0"
+                 style="font-size: 8pt" border="0">
+            <tr>
+              <td colspan="2" align="right">
+                <p style="font-size: 8pt">*For Dioxin and Dioxin-like Compounds,
+                                          report in grams/year</p>
+              </td>
+            </tr>
+            <tr>
+              <td width="50%">
+                <p style="font-size: 8pt">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+                  		EPA Form 9350-1 (Rev. <xsl:value-of select="$RevisionDateFormR"/>) - Previous editions are obsolete.
+                  	</xsl:if>
+                </p>
+              </td>
+              <td width="50%" align="right">
+                <p style="font-size: 8pt">**Range Codes: A=1-10 pounds; B=11-499
+                                          pounds; C=500-999 pounds.</p>
+              </td>
+            </tr>
+          </table>
+          <p style="page-break-before: always">&#160;</p>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="1"
+                 style="font-size: 8pt" border="0">
+            <tr>
+             <!--<td width="90%">
+                <a name="PG-3_{$formID}"></a>
+                <p style="font-size: 8pt">
+                  <a href="#PG-1_{$formID}">1</a>
+                  <a href="#PG-2_{$formID}">2</a>
+                  <a href="#PG-3_{$formID}">3</a>
+                  <a href="#PG-4_{$formID}">4</a>
+                  <a href="#PG-5_{$formID}">5</a>
+                  <a href="#PG-6_{$formID}">Additional Info</a>
+                  <xsl:if test="$ScheduleOneNA = 'false'">
+                      <a href="#S1_PG-1_{$formID}">Schedule 1</a>
+                  </xsl:if>
+                </p>
+              </td>-->
+              <td width="10%">
+                <p style="font-size: 8pt">
+                  <b>Page 3 of 5 </b>
+                </p>
+              </td>
+            </tr>
+          </table>
+          <center>
+          <tr>
+	              <td align="center" width="100%">
+	                <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+	                  *** Do not send to EPA: This is the final copy of your form.***
+	                &#160;</span>
+	              </td>
+          </tr>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%"
+                   style="font-size: 8pt">
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1" cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td width="65%" align="center" style="font-size: 10pt">
+                        <p style="font-size: 10pt">
+                          <b>EPA FORM R</b>
+                          <br/>
+                          <b>PART II. CHEMICAL - SPECIFIC INFORMATION (CONTINUED)</b>
+                        </p>
+                      </td>
+                      <td>
+                          TRI Facility ID Number
+                          <hr />
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                          &#160;</span>
+                        <hr />
+                        Toxic Chemical, Category, or Generic Name
+                        <hr />
+                        <span class="answerText">
+                          <xsl:choose>
+                            <xsl:when test="TRI:ChemicalIdentification/TRI:ChemicalNameText='NA'">
+                              <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalMixtureNameText"/>
+                            </xsl:when>
+                            <xsl:otherwise>
+                              <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalNameText"/>
+                            </xsl:otherwise>
+                          </xsl:choose>
+                        &#160;</span>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0"
+                         cellpadding="1">
+                    <tr>
+                      <td align="left" style="font-size: 8pt" colspan="2">
+                        <p style="font-size: 8pt">
+                          SECTION 5. QUANTITY OF THE TOXIC CHEMICAL ENTERING
+                          EACH ENVIRONMENTAL MEDIUM ON-SITE
+                          <font style="font-size: 7pt">(Continued)</font>
+                        </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+                         cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td colspan="2"></td>
+                      <td style="font-size: 8pt" align="center">
+                        <p style="font-size: 8pt">
+                          <b>NA</b>
+                        </p>
+                      </td>
+                      <td align="center">
+                        <p style="font-size: 8pt">A. Total Release
+                                                  (pounds/year*) (Enter range
+                                                  code** or estimate)</p>
+                      </td>
+                      <td align="center">
+                        <p style="font-size: 8pt">B. Basis of Estimate (Enter
+                                                  code)</p>
+                      </td>
+                    </tr>
+                    <xsl:choose>
+                    	<xsl:when test="TRI:SubmissionReportingYear &gt; '2013'">
+                    		<tr>
+                    	  		<td width="5%" align="center">
+                    	  			<p style="font-size: 8pt">5.4-5.5</p>
+                    	  		</td>
+                    	  		<td align="left">
+                    	  	  		<p style="font-size: 8pt">
+                    		      		Disposal to land on-site
+                    		      		<br/>
+                    		    	</p>
+                    		  	</td>
+                    		  	<td colspan="3" style="background-color: gray">&#160;</td>
+                    		</tr>
+                    	</xsl:when>
+                    </xsl:choose>
+                    <xsl:choose>
+          		      <xsl:when test="TRI:SubmissionReportingYear &gt;= '1991' and TRI:SubmissionReportingYear &lt;= '1995'">
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.4</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          UIC Injections Aggregate
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ8795'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ8795'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ8795'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+		                </tr>
+	                  </xsl:when>
+	                  <xsl:otherwise>
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.4.1</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+		                        <xsl:choose>
+		                        	<xsl:when test="TRI:SubmissionReportingYear &gt; '2013'">
+		                          		Class I Underground
+		                          		<br/>
+		                          		Injection wells
+		                        	</xsl:when>
+		                        	<xsl:otherwise>
+		                        		Underground Injection onsite
+		                        	  	<br/>
+		                        	  	to Class I wells
+		                        	</xsl:otherwise>
+		                        </xsl:choose>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ I'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ I'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                        </p>
+	                        <br/>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ I'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                        </p>
+	                        <br/>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.4.2</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                        <xsl:choose>
+	                        	<xsl:when test="TRI:SubmissionReportingYear &gt; '2013'">
+	                        		Class II-V Underground
+	                          		<br/>
+	                          		Injection wells
+								</xsl:when>
+								<xsl:otherwise>
+									Underground Injection onsite
+	                          		<br/>
+	                          		to Class II-V wells
+								</xsl:otherwise>
+	                        </xsl:choose>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ IIV'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ IIV'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'UNINJ IIV'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+		                </tr>
+	                  </xsl:otherwise>
+                    </xsl:choose>
+                    <xsl:if test="TRI:SubmissionReportingYear &lt; '2014'">
+                    	<tr>
+                      		<td width="5%" align="center">
+                        		<p style="font-size: 8pt">5.5</p>
+                      		</td>
+                      		<td align="left">
+                        		<p style="font-size: 8pt">
+                          			Disposal to land on-site
+                          			<br/>
+                        		</p>
+                      		</td>
+                      		<td colspan="3" style="background-color: gray">&#160;</td>
+                    	</tr>
+                    </xsl:if>
+                    <xsl:choose>
+          		      <xsl:when test="TRI:SubmissionReportingYear &gt;= '1991' and TRI:SubmissionReportingYear &lt;= '1995'">
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.5.1</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Total Landfill Releases
+	                          <br/>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'LANDF8795'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'LANDF8795'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'LANDF8795'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+                      </xsl:when>
+                      <xsl:otherwise>
+                        <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.5.1.A</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          RCRA subtitle C landfills
+	                          <br/>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'RCRA C'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'RCRA C'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'RCRA C'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.5.1.B</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Other landfills
+	                          <br/>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'OTH LANDF'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'OTH LANDF'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'OTH LANDF'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+	                 </xsl:otherwise>
+                    </xsl:choose>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">5.5.2</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Land treatment/application
+                          <br/>
+                          farming
+                        </p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          [
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'LAND TREA'">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          ]
+                        </p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'LAND TREA'">
+                                <span class="answerText">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+                                      <br/>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+                                      <br/>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                &#160;</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'LAND TREA'">
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+                                &#160;</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <xsl:choose>
+          		      <xsl:when test="TRI:SubmissionReportingYear &gt;= '1991' and TRI:SubmissionReportingYear &lt;= '2002'">
+          		        <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.5.3</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Surface impoundment
+	                          <br/>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SURF IMP'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SURF IMP'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SURF IMP'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+          		      </xsl:when>
+          		      <xsl:otherwise>
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.5.3A</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          RCRA Subtitle C
+	                          <br/>
+	                          surface impoundments
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SI 5.5.3A'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SI 5.5.3A'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SI 5.5.3A'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">5.5.3B</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Other surface impoundments
+	                          <br/>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SI 5.5.3B'">
+	                                <xsl:choose>
+	                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+	                                    <span class="answerText">X</span>
+	                                  </xsl:when>
+	                                </xsl:choose>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          ]
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SI 5.5.3B'">
+	                                <span class="answerText">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+	                                      <br/>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+	                                      <br/>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+	                            <xsl:choose>
+	                              <xsl:when test="TRI:EnvironmentalMediumCode = 'SI 5.5.3B'">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+	                                &#160;</span>
+	                              </xsl:when>
+	                            </xsl:choose>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+	                  </xsl:otherwise>
+	                </xsl:choose>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">5.5.4</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Other disposal
+                          <br/>
+                          <br/>
+                        </p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          [
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'OTH DISP'">
+                                <xsl:choose>
+                                  <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+                                    <span class="answerText">X</span>
+                                  </xsl:when>
+                                </xsl:choose>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          ]
+                        </p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'OTH DISP'">
+                                <span class="answerText">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityMeasure"/>
+                                      <br/>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:WasteQuantityRangeCode"/>
+                                      <br/>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                &#160;</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:OnsiteReleaseQuantity">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnvironmentalMediumCode = 'OTH DISP'">
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:OnsiteWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+                                &#160;</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+                         cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                    	<xsl:choose>
+                    		<xsl:when test="TRI:SubmissionReportingYear &lt; '2014'">
+                    			<td align="left" colspan="8" style="font-size: 8pt">
+                        			<p style="font-size: 8pt">SECTION 6. TRANSFER(S) OF THE
+                                                  TOXIC CHEMICAL IN WASTES TO
+                                                  OFF-SITE LOCATIONS </p>
+                      			</td>
+                    		</xsl:when>
+                    		<xsl:otherwise>
+                    			<td align="left" colspan="10" style="font-size: 8pt">
+                        			<p style="font-size: 8pt">SECTION 6. TRANSFER(S) OF THE
+                                                  TOXIC CHEMICAL IN WASTES TO
+                                                  OFF-SITE LOCATIONS </p>
+                      			</td>
+                    		</xsl:otherwise>
+                    	</xsl:choose>
+                    </tr>
+
+                    <xsl:choose>
+                      <xsl:when test="TRI:SubmissionReportingYear &gt; '2010'">
+                      <xsl:choose>
+	                      <xsl:when test="TRI:POTWWasteQuantity/TRI:WasteQuantityNAIndicator = 'true' or not(TRI:POTWWasteQuantity)">
+		                    <tr>
+		                      <td align="left" style="font-size: 8pt;">
+		                        <p style="font-size: 8pt">6.1 DISCHARGES TO PUBLICLY
+		                                                  OWNED TREATMENT WORKS (POTWs)</p>
+		                      </td>
+		                      <td align="left" style="font-size: 8pt">
+		                        <p style="font-size: 8pt">
+		                          NA [
+		                            <xsl:if test="TRI:POTWWasteQuantity/TRI:WasteQuantityNAIndicator = 'true' or not(TRI:POTWWasteQuantity)">
+		                              <span class="answerText">X</span>
+		                            </xsl:if>
+		                          ]
+		                        </p>
+		                      </td>
+		                    </tr>
+		                  </xsl:when>
+		                  <xsl:otherwise>
+		                    <tr>
+		                      <td align="left" style="font-size: 8pt;" colspan="3">
+		                        <p style="font-size: 8pt">6.1 DISCHARGES TO PUBLICLY
+		                                                  OWNED TREATMENT WORKS (POTWs)</p>
+		                      </td>
+		                      	<xsl:choose>
+									<xsl:when test="TRI:SubmissionReportingYear &gt; '2013' ">
+											<td align="left" style="font-size: 8pt" colspan="8">  <!-- 2014 -->
+		                        				<p style="font-size: 8pt">
+		                          				NA [
+		                            				<xsl:if test="TRI:POTWWasteQuantity/TRI:WasteQuantityNAIndicator = 'true' or not(TRI:POTWWasteQuantity)">
+		                            					<span class="answerText">X</span>
+		                            				</xsl:if>
+		                          				]
+		                        				</p>
+		                      				</td>
+								    	</xsl:when>
+        								<xsl:otherwise>
+											<td align="left" style="font-size: 6pt" colspan="6">  <!-- 2013 Issue here -->
+		                        				<p style="font-size: 8pt">
+		                          				NA [
+		                            				<xsl:if test="TRI:POTWWasteQuantity/TRI:WasteQuantityNAIndicator = 'true' or not(TRI:POTWWasteQuantity)">
+		                            					<span class="answerText">X</span>
+		                            				</xsl:if>
+		                          				]
+		                        				</p>
+		                      				</td>
+        								</xsl:otherwise>
+								</xsl:choose>
+		                    </tr>
+		                  </xsl:otherwise>
+	                  </xsl:choose>
+	                </xsl:when>
+	                <xsl:otherwise>
+						<tr>
+						  <td align="left" colspan="8" style="font-size: 8pt">
+							<p style="font-size: 8pt">6.1 DISCHARGES TO PUBLICLY
+													  OWNED TREATMENT WORKS (POTWs)</p>
+						  </td>
+						</tr>
+						<tr>
+						  <td align="left" colspan="8" style="font-size: 8pt">
+							<p style="font-size: 8pt">6.1.A Total Quantity
+													  Transferred to POTWs and Basis
+													  of Estimate</p>
+						  </td>
+						</tr>
+						<tr>
+						  <td align="left" colspan="4">
+							<p style="font-size: 8pt">
+							  6.1.A.1 Total Transfers (pounds/year*)
+							  <br/>
+							  (Enter range code** or estimate)
+							</p>
+						  </td>
+						  <td align="center" colspan="4">
+							<p style="font-size: 8pt">
+							  6.1.A.2 Basis of Estimate
+							  <br/>
+							  (Enter code)
+							</p>
+						  </td>
+						</tr>
+						<tr>
+						  <td align="center" colspan="4">
+							<p style="font-size: 8pt">
+							  <span class="answerText">
+								<xsl:choose>
+								  <xsl:when test="TRI:POTWWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">NA</xsl:when>
+								  <xsl:otherwise>
+									<xsl:choose>
+									  <xsl:when test="TRI:POTWWasteQuantity/TRI:WasteQuantityMeasure >= '0'">
+										<xsl:value-of select="TRI:POTWWasteQuantity/TRI:WasteQuantityMeasure"/>
+										<br/>
+									  </xsl:when>
+									  <xsl:otherwise>
+										<xsl:value-of select="TRI:POTWWasteQuantity/TRI:WasteQuantityRangeCode"/>
+										<br/>
+									  </xsl:otherwise>
+									</xsl:choose>
+								  </xsl:otherwise>
+								</xsl:choose>
+							  </span>
+							  <br/>
+							</p>
+						  </td>
+						  <td align="center" colspan="4">
+							<p style="font-size: 8pt">
+							  <span class="answerText">
+								<xsl:value-of select="TRI:POTWWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+							  </span>
+							  <br/>
+							</p>
+						  </td>
+						</tr>
+                      </xsl:otherwise>
+                    </xsl:choose>
+
+                    <xsl:for-each select="TRI:TransferLocation">
+                      <xsl:if test="TRI:POTWIndicator = 'true'">
+                        <tr>
+                          <td align="center" colspan="2">
+                            <p style="font-size: 8pt">
+                              <br/>
+                               <xsl:choose>
+							     <xsl:when test="../TRI:SubmissionReportingYear &gt; '2010'">
+								  6.1.<xsl:value-of select="TRI:TransferLocationSequenceNumber"/>
+							     </xsl:when>
+							     <xsl:otherwise>
+							      6.1.B.<xsl:value-of select="TRI:TransferLocationSequenceNumber"/>
+							     </xsl:otherwise>
+							   </xsl:choose>
+                              <br/>
+                              <u>POTW Name</u>
+                              <br/>
+                            </p>
+                          </td>
+								<xsl:choose>
+									<xsl:when test="../TRI:SubmissionReportingYear &gt; '2013' ">
+                          				<td align="left" colspan="8"> <!-- 2014  -->
+                            				<p style="font-size: 8pt">
+                              				<span class="answerText">
+                                			<xsl:value-of select="sc:FacilitySiteName"/>
+                              				&#160;</span>
+                              				<br/>
+                            				</p>
+                          				</td>
+
+								    </xsl:when>
+        							<xsl:otherwise>
+			                          <td align="left" colspan="6"> <!-- 2013  -->
+                            			<p style="font-size: 8pt">
+                              				<span class="answerText">
+                                		<xsl:value-of select="sc:FacilitySiteName"/>
+                              			&#160;</span>
+                              			<br/>
+                            			</p>
+                          			</td>
+     								</xsl:otherwise>
+							</xsl:choose>
+                        </tr>
+                        <tr>
+                          <td align="center" colspan="2" width="25%">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              POTW Address
+                              <br/>
+                            </p>
+                          </td>
+                          <xsl:choose>
+                          	<xsl:when test="../TRI:SubmissionReportingYear &gt; '2013' ">
+					                    <td align="left" colspan="8"> <!-- 2014  -->
+                            				<p style="font-size: 8pt">
+                              				<span class="answerText">
+                                			<xsl:value-of select="sc:LocationAddress/sc:LocationAddressText"/>
+				                              &#160; </span>
+                              				<br/>
+                            				</p>
+                          				</td>
+                          	</xsl:when>
+                          	<xsl:otherwise>
+                          	            <td align="left" colspan="6"> <!-- 2013  -->
+                            				<p style="font-size: 8pt">
+                              				<span class="answerText">
+                                				<xsl:value-of select="sc:LocationAddress/sc:LocationAddressText"/>
+                              					&#160; </span>
+                              					<br/>
+                            				</p>
+                          				</td>
+                          	</xsl:otherwise>
+                          </xsl:choose>
+                        </tr>
+                        <tr>
+                          <td width="5%">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              City
+                              <br/>
+                            </p>
+                          </td>
+                          <td>
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:LocalityName"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+                          <xsl:choose>
+							<xsl:when test="../TRI:SubmissionReportingYear &lt; '2011'">
+							  <td width="5%">
+								<p style="font-size: 8pt">
+								  <br/>
+								  State
+								  <br/>
+								</p>
+							  </td>
+							  <td>
+								<p style="font-size: 8pt">
+								  <span class="answerText">
+									<xsl:value-of select="sc:LocationAddress/sc:StateIdentity/sc:StateName"/>
+								  </span>
+                              <br/>
+                            </p>
+                          </td>
+                          <td width="5%">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              County
+                              <br/>
+                            </p>
+                          </td>
+                          <td>
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:CountyIdentity/sc:CountyName"/>
+                              &#160;</span>
+	  <br/>
+								</p>
+							  </td>
+                          </xsl:when>
+						  <xsl:otherwise>
+						  <td width="5%">
+								<p style="font-size: 8pt">
+								  <br/>
+								  County
+								  <br/>
+								</p>
+							  </td>
+							  <td>
+								<p style="font-size: 8pt">
+								  <span class="answerText">
+									<xsl:value-of select="sc:LocationAddress/sc:CountyIdentity/sc:CountyName"/>
+								  </span>
+                              <br/>
+                            </p>
+                          </td>
+                          <td width="5%">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              State
+                              <br/>
+                            </p>
+                          </td>
+                          <td>
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:StateIdentity/sc:StateName"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+						  </xsl:otherwise>
+						</xsl:choose>
+                          <td width="5%">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              ZIP
+                              <br/>
+                            </p>
+                          </td>
+                          <td>
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:AddressPostalCode"/>
+                              </span>
+                              <br/>
+                            </p>
+                          </td>
+                               <!-- Country column for RY-2014 and later -->
+                          <xsl:if test="../TRI:SubmissionReportingYear &gt; '2013' ">
+                          <td width="5%">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              Country
+                              <br/>
+                              (Non-US)
+                            </p>
+                          </td>
+
+                          <td>
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:CountryIdentity/sc:CountryName"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+                          </xsl:if>
+
+                        </tr>
+
+                         <xsl:if test="../TRI:SubmissionReportingYear &gt; '2010'">
+	                        <tr>
+		                            <xsl:choose>
+										<xsl:when test="../TRI:SubmissionReportingYear &gt; '2013' ">
+											<td align="center" colspan="5">  <!-- 2014-->
+											<p style="font-size: 8pt">
+		                          				A. Quantity Transferred to this POTW
+		                          				<br/>
+		                          				(pounds/year*) (Enter range code**or estimate)
+		                        			</p>
+		                      				</td>
+								    	</xsl:when>
+        								<xsl:otherwise>
+											<td align="center" colspan="4">  <!-- 2013 -->
+											<p style="font-size: 8pt">
+		                          				A. Quantity Transferred to this POTW
+		                          				<br/>
+		                          				(pounds/year*) (Enter range code**or estimate)
+		                        			</p>
+		                      				</td>
+
+        								</xsl:otherwise>
+       								</xsl:choose>
+		                           <xsl:choose>
+										<xsl:when test="../TRI:SubmissionReportingYear &gt; '2013' ">
+											<td align="center" colspan="5"> <!-- 2014-->
+											<p style="font-size: 8pt">
+		                          			B. Basis of Estimate
+		                          				<br/>
+		                          			(Enter code)
+		                        			</p>
+		                      				</td>
+								    	</xsl:when>
+        								<xsl:otherwise>
+											<td align="center" colspan="4"> <!-- 2013 -->
+											<p style="font-size: 8pt">
+		                          			B. Basis of Estimate
+		                          				<br/>
+		                          			(Enter code)
+		                        			</p>
+		                      				</td>
+
+        								</xsl:otherwise>
+       								</xsl:choose>
+		                    </tr>
+
+		                    <xsl:variable name="locationSequence" select="TRI:TransferLocationSequenceNumber"/>
+		                    <xsl:for-each select="../TRI:POTWWasteQuantity">
+			                    <xsl:if test="TRI:POTWSequenceNumber = $locationSequence">
+				                 <tr>
+       								<xsl:choose>
+									<xsl:when test="../TRI:SubmissionReportingYear &gt; '2013' ">
+									<td align="center" colspan="5">  <!-- 2014 -->
+			                        <p style="font-size: 8pt">
+			                          <span class="answerText">
+			                            <xsl:choose>
+			                              <xsl:when test="TRI:WasteQuantityNAIndicator = 'true'">NA</xsl:when>
+			                              <xsl:otherwise>
+			                                <xsl:choose>
+			                                  <xsl:when test="TRI:WasteQuantityMeasure >= '0'">
+			                                    <xsl:value-of select="TRI:WasteQuantityMeasure"/>
+			                                  </xsl:when>
+			                                  <xsl:otherwise>
+			                                    <xsl:value-of select="TRI:WasteQuantityRangeCode"/>
+			                                    <br/>
+			                                  </xsl:otherwise>
+			                                </xsl:choose>
+			                              </xsl:otherwise>
+			                            </xsl:choose>
+			                          &#160;</span>
+			                          <br/>
+			                        </p>
+			                      </td>
+								  </xsl:when>
+        						  <xsl:otherwise>
+									<td align="center" colspan="4">  <!-- 2013 -->
+										<p style="font-size: 8pt">
+			                          <span class="answerText">
+			                            <xsl:choose>
+			                              <xsl:when test="TRI:WasteQuantityNAIndicator = 'true'">NA</xsl:when>
+			                              <xsl:otherwise>
+			                                <xsl:choose>
+			                                  <xsl:when test="TRI:WasteQuantityMeasure >= '0'">
+			                                    <xsl:value-of select="TRI:WasteQuantityMeasure"/>
+			                                  </xsl:when>
+			                                  <xsl:otherwise>
+			                                    <xsl:value-of select="TRI:WasteQuantityRangeCode"/>
+			                                    <br/>
+			                                  </xsl:otherwise>
+			                                </xsl:choose>
+			                              </xsl:otherwise>
+			                            </xsl:choose>
+			                          &#160;</span>
+			                          <br/>
+			                        </p>
+			                      </td>
+    								</xsl:otherwise>
+								</xsl:choose>
+								<xsl:choose>
+										<xsl:when test="../TRI:SubmissionReportingYear &gt; '2013' ">
+											<td align="center" colspan="5"> <!-- 2014 -->
+					                        <p style="font-size: 8pt">
+					                          <span class="answerText">
+			                            	<xsl:value-of select="TRI:QuantityBasisEstimationCode"/>
+			                          			&#160;</span>
+			                          			<br/>
+			                        		</p>
+			                      			</td>
+								    	</xsl:when>
+        								<xsl:otherwise>
+											<td align="center" colspan="4"> <!-- 2013 -->
+					                        <p style="font-size: 8pt">
+					                          <span class="answerText">
+			                            	<xsl:value-of select="TRI:QuantityBasisEstimationCode"/>
+			                          			&#160;</span>
+			                          			<br/>
+			                        		</p>
+			                      			</td>
+
+        								</xsl:otherwise>
+									</xsl:choose>
+			                    </tr>
+			                   </xsl:if>
+		                  	</xsl:for-each>
+	                    </xsl:if>
+
+
+                      </xsl:if>
+                    </xsl:for-each>
+                  </table>
+                </td>
+              </tr>
+            </table>
+          </center>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="1"
+                 style="font-size: 8pt" border="0">
+            <tr>
+              <td colspan="2" align="right">
+                <p style="font-size: 8pt">*For Dioxin and Dioxin-like Compounds, report in grams/year</p>
+              </td>
+            </tr>
+            <tr>
+              <td width="50%">
+                <p style="font-size: 8pt">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+                  		EPA Form 9350-1 (Rev. <xsl:value-of select="$RevisionDateFormR"/>) - Previous editions are obsolete.
+                  	</xsl:if>
+                </p>
+              </td>
+              <td width="50%" align="right">
+                <p style="font-size: 8pt">**Range Codes: A=1-10 pounds; B=11-499 pounds; C=500-999 pounds.</p>
+              </td>
+            </tr>
+          </table>
+          <p style="page-break-before: always">&#160;</p>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="1"
+                 style="font-size: 8pt" border="0" rules="all">
+            <tr>
+            <!--<td width="90%">
+                <a name="PG-4_{$formID}"></a>
+                <p style="font-size: 8pt">
+                  <a href="#PG-1_{$formID}">1</a>
+                  <a href="#PG-2_{$formID}">2</a>
+                  <a href="#PG-3_{$formID}">3</a>
+                  <a href="#PG-4_{$formID}">4</a>
+                  <a href="#PG-5_{$formID}">5</a>
+                  <a href="#PG-6_{$formID}">Additional Info</a>
+                  <xsl:if test="$ScheduleOneNA = 'false'">
+                      <a href="#S1_PG-1_{$formID}">Schedule 1</a>
+                  </xsl:if>
+                </p>
+              </td>-->
+              <td width="10%">
+                <p style="font-size: 8pt">
+                  <b>Page 4 of 5 </b>
+                </p>
+              </td>
+            </tr>
+          </table>
+          <center>
+          <tr>
+	              <td align="center" width="100%">
+	                <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+	                  *** Do not send to EPA: This is the final copy of your form.***
+	                &#160;</span>
+	              </td>
+          </tr>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%"
+                   style="font-size: 8pt">
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1" cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td width="65%" align="center" style="font-size: 10pt">
+                        <p style="font-size: 10pt">
+                          <b>EPA FORM R</b>
+                          <br/>
+                          <b>PART II. CHEMICAL - SPECIFIC INFORMATION (CONTINUED)</b>
+                        </p>
+                      </td>
+                      <td>
+                          TRI Facility ID Number
+                          <hr />
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                          &#160;</span>
+                        <hr />
+                        Toxic Chemical, Category, or Generic Name
+                        <hr />
+                        <span class="answerText">
+                          <xsl:choose>
+                            <xsl:when test="TRI:ChemicalIdentification/TRI:ChemicalNameText='NA'">
+                              <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalMixtureNameText"/>
+                            </xsl:when>
+                            <xsl:otherwise>
+                              <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalNameText"/>
+                            </xsl:otherwise>
+                          </xsl:choose>
+                        &#160;</span>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+               <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" border="0" style="font-size: 8pt" cellspacing="0"
+                         cellpadding="1">
+                    <xsl:if test="TRI:SubmissionReportingYear &gt; '2010'">
+	                    <tr>
+	                      <td align="left" style="font-size: 8pt; width: 405px; border-right: ridge 2px;">
+	                        <p style="font-size: 8pt">SECTION 6.2 TRANSFERS TO OTHER OFF-SITE LOCATIONS </p>
+	                      </td>
+	                      <td align="left" style="font-size: 8pt;">
+	                        <p style="font-size: 8pt">
+		                      NA [
+
+		                      	  <xsl:if test="not(TRI:TransferLocation)">
+
+			                              <span class="answerText">X</span>
+
+		                      	  </xsl:if>
+
+	                      	 ]
+		                    </p>
+	                      </td>
+	                    </tr>
+                    </xsl:if>
+                    <xsl:if test="TRI:SubmissionReportingYear &lt; '2011'">
+                      <tr>
+                    	<td align="left" style="font-size: 8pt;">
+	                        <p style="font-size: 8pt">SECTION 6.2 TRANSFERS TO OTHER OFF-SITE LOCATIONS </p>
+	                    </td>
+	                  </tr>
+                    </xsl:if>
+                  </table>
+                </td>
+              </tr>
+              <xsl:for-each select="TRI:TransferLocation">
+                <xsl:if test="TRI:POTWIndicator = 'false'">
+                  <tr>
+                    <td colspan="2">
+                      <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1" cellspacing="0" cellpadding="1" frame="void">
+                        <tr>
+                          <xsl:choose>
+                            <xsl:when test="../TRI:TransferLocation[1]/TRI:POTWIndicator = 'true'">
+                              <td width="55%" style="font-size: 10pt">
+                                <p style="font-size: 8pt">
+                                  6.2.<xsl:value-of select="count(preceding-sibling::TRI:TransferLocation) - 1"/>
+                                  Off-Site EPA Identification Number (RCRA ID
+                                  No.)
+                                </p>
+                              </td>
+                            </xsl:when>
+                            <xsl:otherwise>
+                              <td width="55%" style="font-size: 10pt">
+                                <p style="font-size: 8pt">
+                                  6.2.<xsl:value-of select="count(preceding-sibling::TRI:TransferLocation) + 1"/>
+                                  Off-Site EPA Identification Number (RCRA ID No.)
+                                </p>
+                              </td>
+                            </xsl:otherwise>
+                          </xsl:choose>
+                          <td>
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="TRI:RCRAIdentificationNumber"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+                        </tr>
+                        <tr>
+                          <td width="25%" style="text-indent: 2em">
+                            <p style="font-size: 8pt">Off-Site Location Name: </p>
+                          </td>
+                          <td>
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:FacilitySiteName"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+                        </tr>
+                        <tr>
+                          <td width="25%" style="text-indent: 2em">
+                            <p style="font-size: 8pt">Off-Site Address: </p>
+                          </td>
+                          <td>
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:LocationAddressText"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+                        </tr>
+                      </table>
+                    </td>
+                  </tr>
+                  <tr>
+                    <td colspan="2">
+                      <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+                             cellspacing="0" cellpadding="1" frame="void">
+                        <tr>
+                          <td width="5%">
+                            <p style="font-size: 8pt">City</p>
+                          </td>
+                          <td width="20%">
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:LocalityName"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+						<xsl:choose>
+						<xsl:when test="../TRI:SubmissionReportingYear &lt; '2011'">
+						  <td width="5%">
+							<p style="font-size: 8pt">State</p>
+						  </td>
+						  <td width="5%">
+							<p style="font-size: 8pt">
+							  <span class="answerText">
+								<xsl:value-of select="sc:LocationAddress/sc:StateIdentity/sc:StateName"/>
+							  </span>
+							  <br/>
+							</p>
+						  </td>
+						  <td width="10%">
+							<p style="font-size: 8pt">County</p>
+						  </td>
+						  <td width="20%">
+							<p style="font-size: 8pt">
+							  <span class="answerText">
+								<xsl:value-of select="sc:LocationAddress/sc:CountyIdentity/sc:CountyName"/>
+							  </span>
+							  <br/>
+							</p>
+						  </td>
+						</xsl:when>
+						<xsl:otherwise>
+                          <td width="10%">
+                            <p style="font-size: 8pt">County</p>
+                          </td>
+                          <td width="20%">
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:CountyIdentity/sc:CountyName"/>
+                              </span>
+                              <br/>
+                            </p>
+                          </td>
+                          <td width="5%">
+                            <p style="font-size: 8pt">State</p>
+                          </td>
+                          <td width="5%">
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:StateIdentity/sc:StateName"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+						</xsl:otherwise>
+						</xsl:choose>
+                          <td width="5%">
+                            <p style="font-size: 8pt">ZIP</p>
+                          </td>
+                          <td width="15%">
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:AddressPostalCode"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+                          <td width="10%">
+                            <p style="font-size: 8pt">
+                              Country
+                              <br/>
+                              (Non-US)
+                            </p>
+                          </td>
+                          <td width="5%">
+                            <p style="font-size: 8pt">
+                              <span class="answerText">
+                                <xsl:value-of select="sc:LocationAddress/sc:CountryIdentity/sc:CountryName"/>
+                              &#160;</span>
+                              <br/>
+                            </p>
+                          </td>
+                        </tr>
+                        <tr>
+                          <td colspan="6" style="text-indent: 4em">
+                            <p style="font-size: 8pt">Is location under control
+                                                      of reporting facility or
+                                                      parent company?</p>
+                          </td>
+                          <td colspan="4" style="font-size: 8pt">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              [
+                              <xsl:choose>
+                                <xsl:when test="sc:FacilitySiteName = 'NA'"></xsl:when>
+                                <xsl:otherwise>
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:ControlledLocationIndicator = 'true'">
+                                      <span class="answerText">X</span>
+                                    </xsl:when>
+                                  </xsl:choose>
+                                </xsl:otherwise>
+                              </xsl:choose>
+                              ] Yes [
+                              <xsl:choose>
+                                <xsl:when test="sc:FacilitySiteName = 'NA'"></xsl:when>
+                                <xsl:otherwise>
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:ControlledLocationIndicator = 'false'">
+                                      <span class="answerText">X</span>
+                                    </xsl:when>
+                                  </xsl:choose>
+                                </xsl:otherwise>
+                              </xsl:choose>
+                              ] No
+                              <br/>
+                            </p>
+                          </td>
+                        </tr>
+                      </table>
+                    </td>
+                  </tr>
+                  <tr>
+                    <td colspan="2">
+                      <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+                             cellspacing="0" cellpadding="1" frame="void">
+                        <tr>
+                          <td align="center">
+                            <p style="font-size: 8pt">
+                              A. Total Transfer (pounds/year*)
+                              <br/>
+                              (Enter range code** or estimate)
+                            </p>
+                          </td>
+                          <td align="center">
+                            <p style="font-size: 8pt">
+                              B. Basis of Estimate
+                              <br/>
+                              (Enter code)
+                            </p>
+                          </td>
+                          <td align="center">
+                            <p style="font-size: 8pt">
+                              C. Type of Waste Treatment/Disposal/
+                              <br/>
+                              Recycling/Energy Recovery (Enter code)
+                            </p>
+                          </td>
+                        </tr>
+                        <xsl:for-each select="TRI:TransferQuantity">
+                          <tr style="height: 25px">
+                            <td style="text-indent: 2em">
+                              <p style="font-size: 8pt">
+                                <xsl:value-of select="count(preceding-sibling::TRI:TransferQuantity) + 1"/>
+                                .
+                                <span class="answerText">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TransferWasteQuantity/TRI:WasteQuantityMeasure[.!='']">
+                                      <xsl:value-of select="TRI:TransferWasteQuantity/TRI:WasteQuantityMeasure"/>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <xsl:value-of select="TRI:TransferWasteQuantity/TRI:WasteQuantityRangeCode"/>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td style="text-indent: 1em">
+                              <p style="font-size: 8pt">
+                                <xsl:value-of select="count(preceding-sibling::TRI:TransferQuantity) + 1"/>
+                                .
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:TransferWasteQuantity/TRI:QuantityBasisEstimationCode"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                            <td style="text-indent: 2em">
+                              <p style="font-size: 8pt">
+                                <xsl:value-of select="count(preceding-sibling::TRI:TransferQuantity) + 1"/>
+                                .
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:WasteManagementTypeCode"/>
+                                &#160;</span>
+                              </p>
+                            </td>
+                          </tr>
+                        </xsl:for-each>
+                      </table>
+                    </td>
+                  </tr>
+                </xsl:if>
+              </xsl:for-each>
+              <tr>
+                <td colspan="2">
+                  <xsl:choose>
+                    <xsl:when test="TRI:SubmissionReportingYear &gt;= '1991' and TRI:SubmissionReportingYear &lt; '2005'">
+                      <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+	                         cellspacing="0" cellpadding="1" frame="void">
+	                    <tr>
+	                      <td colspan="7" style="font-size: 8pt">
+	                        <p style="font-size: 8pt">SECTION 7A. ONSITE WASTE TREATMENT METHODS AND EFFICIENCY</p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td colspan="7">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:choose>
+	                            <xsl:when test="TRI:WasteTreatmentNAIndicator = 'true'">
+	                              <span class="answerText">X</span>
+	                            </xsl:when>
+	                            <xsl:otherwise></xsl:otherwise>
+	                          </xsl:choose>
+	                          ] Not Applicable (NA) - Check here if no on-site waste
+	                          treatment is applied to any waste stream containing
+	                          the toxic chemical or chemical category.
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td width="15%" align="center">
+	                        <p style="font-size: 8pt">
+	                          a. General
+	                          <br/>
+	                          Waste Stream
+	                          <br/>
+	                          (enter code)
+	                        </p>
+	                      </td>
+	                      <td width="45%" align="center">
+	                        <p style="font-size: 8pt">
+	                          b. Waste Treatment Method(s) Sequence
+	                          <br/>
+	                          [enter 3-character code(s)]
+	                        </p>
+	                      </td>
+	                      <td align="center">
+	                      	<p style="font-size: 8pt">
+	                          c. Influent Concentration
+	                        </p>
+	                      </td>
+	                      <td align="center">
+	                        <p style="font-size: 8pt">
+	                          d. % Waste Treatment
+	                          <br/>
+	                          Efficiency
+	                        </p>
+	                      </td>
+	                      <td align="center">
+	                        <p style="font-size: 8pt">
+	                          e. Based on
+	                          <br/>
+	                          Operating Data?
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <xsl:choose>
+	                      <xsl:when test="TRI:WasteTreatmentNAIndicator = 'true'"></xsl:when>
+	                      <xsl:otherwise>
+	                        <xsl:for-each select="TRI:WasteTreatmentDetails">
+	                          <tr>
+	                            <td align="center">
+	                              <p style="font-size: 8pt">
+	                                <b style="color: black;font-size: 9pt">
+	                                  7A.
+	                                  <xsl:value-of select="count(preceding-sibling::TRI:WasteTreatmentDetails) + 1"/>
+	                                  a
+	                                </b>
+	                                <br/>
+	                              </p>
+	                            </td>
+	                            <td width="45%" align="center">
+	                              <p style="font-size: 8pt">
+	                                <b style="color: black;font-size: 9pt">
+	                                  7A.
+	                                  <xsl:value-of select="count(preceding-sibling::TRI:WasteTreatmentDetails) + 1"/>
+	                                  b
+	                                </b>
+	                              </p>
+	                            </td>
+	                            <td align="center">
+	                              <p style="font-size: 8pt">
+	                                <b style="color: black;font-size: 9pt">
+	                                  7A.
+	                                  <xsl:value-of select="count(preceding-sibling::TRI:WasteTreatmentDetails) + 1"/>
+	                                  c
+	                                </b>
+	                                <br/>
+	                              </p>
+	                            </td>
+	                            <td align="center">
+	                              <p style="font-size: 8pt">
+	                                <b style="color: black;font-size: 9pt">
+	                                  7A.
+	                                  <xsl:value-of select="count(preceding-sibling::TRI:WasteTreatmentDetails) + 1"/>
+	                                  d
+	                                </b>
+	                                <br/>
+	                              </p>
+	                            </td>
+	                            <td align="center">
+	                              <p style="font-size: 8pt">
+	                                <b style="color: black;font-size: 9pt">
+	                                  7A.
+	                                  <xsl:value-of select="count(preceding-sibling::TRI:WasteTreatmentDetails) + 1"/>
+	                                  e
+	                                </b>
+	                                <br/>
+	                              </p>
+	                            </td>
+	                          </tr>
+	                          <tr>
+	                            <td align="center">
+	                              <p style="font-size: 8pt">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:WasteStreamTypeCode"/>
+	                                &#160;</span>
+	                              </p>
+	                            </td>
+	                            <td width="45%" align="center">
+	                              <p style="font-size: 8pt">
+	                                <xsl:for-each select="TRI:WasteTreatmentMethod">
+	                                  <xsl:value-of select="TRI:WasteTreatmentSequenceNumber + 1"/>
+	                                  :
+	                                  <span class="answerText">
+	                                    <xsl:value-of select="TRI:WasteTreatmentMethodCode"/>
+	                                    <xsl:text> </xsl:text>
+	                                  &#160;</span>
+	                                </xsl:for-each>
+	                              </p>
+	                            </td>
+	                            <td align="center">
+	                              <span class="answerText">
+	                                <xsl:value-of select="TRI:InfluentConcentrationRangeCode"/>
+	                              &#160;</span>
+	                            </td>
+	                            <td align="center">
+	                              <span class="answerText">
+	                                <xsl:value-of select="TRI:TreatmentEfficiencyEstimatePercent"/>
+	                              &#160;</span>
+	                            </td>
+	                            <td align="center">
+	                              <span class="answerText">
+	                                <xsl:choose>
+		                              <xsl:when test="TRI:OperatingDataIndicator = 'true'">
+		                                <span class="answerText">X</span>
+		                              </xsl:when>
+		                              <xsl:otherwise></xsl:otherwise>
+		                            </xsl:choose>
+	                              &#160;</span>
+	                            </td>
+	                          </tr>
+	                        </xsl:for-each>
+	                      </xsl:otherwise>
+	                    </xsl:choose>
+	                  </table>
+                    </xsl:when>
+                    <xsl:otherwise>
+	                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+	                         cellspacing="0" cellpadding="1" frame="void">
+	                    <tr>
+	                      <td colspan="5" style="font-size: 8pt">
+	                        <p style="font-size: 8pt">SECTION 7A. ONSITE WASTE TREATMENT METHODS AND EFFICIENCY</p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td colspan="5">
+	                        <p style="font-size: 8pt">
+	                          [
+	                          <xsl:choose>
+	                            <xsl:when test="TRI:WasteTreatmentNAIndicator = 'true'">
+	                              <span class="answerText">X</span>
+	                            </xsl:when>
+	                            <xsl:otherwise></xsl:otherwise>
+	                          </xsl:choose>
+	                          ] Not Applicable (NA) - Check here if no on-site waste
+	                          treatment is applied to any waste stream containing
+	                          the toxic chemical or chemical category.
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td width="15%" align="center">
+	                        <p style="font-size: 8pt">
+	                          a. General
+	                          <br/>
+	                          Waste Stream
+	                          <br/>
+	                          (enter code)
+	                        </p>
+	                      </td>
+	                      <td width="45%" align="center">
+	                        <p style="font-size: 8pt">
+	                          b. Waste Treatment Method(s) Sequence
+	                          <br/>
+	                          [enter 3-character code(s)]
+	                        </p>
+	                      </td>
+	                      <td align="center">
+	                        <p style="font-size: 8pt">
+	                          d. Waste Treatment
+	                          <br/>
+	                          Efficiency
+	                          <br/>
+	                          Estimate
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <xsl:choose>
+	                      <xsl:when test="TRI:WasteTreatmentNAIndicator = 'true'"></xsl:when>
+	                      <xsl:otherwise>
+	                        <xsl:for-each select="TRI:WasteTreatmentDetails">
+	                          <tr>
+	                            <td align="center">
+	                              <p style="font-size: 8pt">
+	                                <b style="color: black;font-size: 9pt">
+	                                  7A.
+	                                  <xsl:value-of select="count(preceding-sibling::TRI:WasteTreatmentDetails) + 1"/>
+	                                  a
+	                                </b>
+	                                <br/>
+	                              </p>
+	                            </td>
+	                            <td width="45%" align="center">
+	                              <p style="font-size: 8pt">
+	                                <b style="color: black;font-size: 9pt">
+	                                  7A.
+	                                  <xsl:value-of select="count(preceding-sibling::TRI:WasteTreatmentDetails) + 1"/>
+	                                  b
+	                                </b>
+	                              </p>
+	                            </td>
+	                            <td align="center">
+	                              <p style="font-size: 8pt">
+	                                <b style="color: black;font-size: 9pt">
+	                                  7A.
+	                                  <xsl:value-of select="count(preceding-sibling::TRI:WasteTreatmentDetails) + 1"/>
+	                                  d
+	                                </b>
+	                                <br/>
+	                              </p>
+	                            </td>
+	                          </tr>
+	                          <tr>
+	                            <td align="center">
+	                              <p style="font-size: 8pt">
+	                                <span class="answerText">
+	                                  <xsl:value-of select="TRI:WasteStreamTypeCode"/>
+	                                &#160;</span>
+	                              </p>
+	                            </td>
+	                            <td width="45%" align="center">
+	                              <p style="font-size: 8pt">
+	                                <xsl:for-each select="TRI:WasteTreatmentMethod">
+	                                  <xsl:value-of select="TRI:WasteTreatmentSequenceNumber + 1"/>
+	                                  :
+	                                  <span class="answerText">
+	                                    <xsl:value-of select="TRI:WasteTreatmentMethodCode"/>
+	                                    <xsl:text> </xsl:text>
+	                                  &#160;</span>
+	                                </xsl:for-each>
+	                              </p>
+	                            </td>
+	                            <td align="center">
+	                              <span class="answerText">
+	                                <xsl:value-of select="TRI:TreatmentEfficiencyRangeCode"/>
+	                              &#160;</span>
+	                            </td>
+	                          </tr>
+	                        </xsl:for-each>
+	                      </xsl:otherwise>
+	                    </xsl:choose>
+	                  </table>
+	                </xsl:otherwise>
+                  </xsl:choose>
+                </td>
+              </tr>
+            </table>
+          </center>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="1"
+                 style="font-size: 8pt" border="0">
+            <tr>
+              <td colspan="2" align="right">
+                <p style="font-size: 8pt">*For Dioxin and Dioxin-like Compounds,
+                                          report in grams/year</p>
+              </td>
+            </tr>
+            <tr>
+              <td width="50%">
+                <p style="font-size: 8pt">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+                  		EPA Form 9350-1 (Rev. <xsl:value-of select="$RevisionDateFormR"/>) - Previous editions are obsolete.
+                  	</xsl:if>
+                </p>
+              </td>
+              <td width="50%" align="right">
+                <p style="font-size: 8pt">**Range Codes: A=1-10 pounds; B=11-499
+                                          pounds; C=500-999 pounds.</p>
+              </td>
+            </tr>
+          </table>
+          <p style="page-break-before: always">&#160;</p>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="1"
+                 style="font-size: 8pt" border="0">
+            <tr>
+             <!--<td width="90%">
+                <a name="PG-5_{$formID}"></a>
+                <p style="font-size: 8pt">
+                  <a href="#PG-1_{$formID}">1</a>
+                  <a href="#PG-2_{$formID}">2</a>
+                  <a href="#PG-3_{$formID}">3</a>
+                  <a href="#PG-4_{$formID}">4</a>
+                  <a href="#PG-5_{$formID}">5</a>
+                  <a href="#PG-6_{$formID}">Additional Info</a>
+                  <xsl:if test="$ScheduleOneNA = 'false'">
+                      <a href="#S1_PG-1_{$formID}">Schedule 1</a>
+                  </xsl:if>
+                </p>
+              </td>-->
+              <td width="10%">
+                <p style="font-size: 8pt">
+                  <b>Page 5 of 5 </b>
+                </p>
+              </td>
+            </tr>
+          </table>
+          <center>
+          <tr>
+	              <td align="center" width="100%">
+	                <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+	                  *** Do not send to EPA: This is the final copy of your form.***
+	                &#160;</span>
+	              </td>
+          </tr>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%"
+                   style="font-size: 8pt">
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1" cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td width="65%" align="center" style="font-size: 10pt">
+                        <p style="font-size: 10pt">
+                          <b>EPA FORM R</b>
+                          <br/>
+                          <b>PART II. CHEMICAL - SPECIFIC INFORMATION (CONTINUED)</b>
+                        </p>
+                      </td>
+                      <td>
+                          TRI Facility ID Number
+                          <hr />
+                          <span class="answerText">
+                            <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                          &#160;</span>
+                        <hr />
+                        Toxic Chemical, Category, or Generic Name
+                        <hr />
+                        <span class="answerText">
+                          <xsl:choose>
+                            <xsl:when test="TRI:ChemicalIdentification/TRI:ChemicalNameText='NA'">
+                              <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalMixtureNameText"/>
+                            </xsl:when>
+                            <xsl:otherwise>
+                              <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalNameText"/>
+                            </xsl:otherwise>
+                          </xsl:choose>
+                        &#160;</span>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0" cellpadding="1" border="0" frame="void">
+                    <tr>
+                      <td align="left" colspan="8">SECTION 7B. ON-SITE ENERGY RECOVERY PROCESSES</td>
+                    </tr>
+                    <tr>
+                      <td align="left" colspan="8">
+                          [
+                          <xsl:for-each select="TRI:OnsiteRecoveryProcess">
+                            <xsl:choose>
+                              <xsl:when test="TRI:EnergyRecoveryNAIndicator = 'true'">
+                                <span class="answerText">X</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          ] NA - Check here if no on-site
+                          energy recovery is applied to any waste
+                          <br />
+                          stream containing the toxic chemical or chemical
+                          category.
+                      </td>
+                    </tr>
+                    <tr>
+                      <td align="left" colspan="8">
+                        <p style="font-size: 8pt">
+                          Energy Recovery Methods [Enter 3-character code(s)]
+                          <br/>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td align="left" colspan="8">
+                      <xsl:for-each select="TRI:OnsiteRecoveryProcess">
+                        <xsl:choose>
+                          <xsl:when test="TRI:EnergyRecoveryNAIndicator = 'true'"></xsl:when>
+                          <xsl:otherwise>
+                            <xsl:for-each select="TRI:EnergyRecoveryMethodCode">
+                              <span style="border: solid; border-width: thin; padding-left:20px; padding-right:20px;">
+                                  <xsl:value-of select="count(preceding-sibling::*) + 1"/>.
+                                  <span class="answerText">
+                                    <xsl:value-of select="."/>
+                                  &#160;</span>
+                              &#160;</span>&#160;&#160;
+                            </xsl:for-each>
+                          </xsl:otherwise>
+                        </xsl:choose>
+                      </xsl:for-each>
+                      &#160;
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0" cellpadding="1" border="0" frame="void">
+                    <tr>
+                      <td align="left" colspan="6">
+                        SECTION 7C. ON-SITE RECYCLING PROCESSES
+                      </td>
+                    </tr>
+                    <tr>
+                      <td align="left" colspan="6">
+                          [
+                          <xsl:for-each select="TRI:OnsiteRecyclingProcess">
+                            <xsl:choose>
+                              <xsl:when test="TRI:OnsiteRecyclingNAIndicator = 'true'">
+                                <span class="answerText">X</span>
+                              </xsl:when>
+                            </xsl:choose>
+                          </xsl:for-each>
+                          ] NA - Check here if no on-site
+                          recycling is applied to any waste
+                          <br/>
+                          stream containing the toxic chemical or chemical
+                          category.
+                      </td>
+                    </tr>
+                    <tr>
+                      <td align="left" colspan="6">
+                        <p style="font-size: 8pt">
+                          Recycling Methods [Enter 3-character code(s)]
+                          <br/>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td>
+                      <xsl:for-each select="TRI:OnsiteRecyclingProcess">
+                        <xsl:choose>
+                          <xsl:when test="TRI:OnsiteRecyclingNAIndicator = 'true'"></xsl:when>
+                          <xsl:otherwise>
+                            <xsl:for-each select="TRI:OnsiteRecyclingMethodCode">
+                              <span style="border: solid; border-width: thin; padding-left: 20px; padding-right:20px; width: 85px;">
+                                  <xsl:value-of select="count(preceding-sibling::*) + 1"/>.
+                                  <span class="answerText">
+                                    <xsl:value-of select="."/>
+                                  &#160;</span>
+                              &#160;</span>&#160;&#160;
+                            </xsl:for-each>
+                          </xsl:otherwise>
+                        </xsl:choose>
+                      </xsl:for-each>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+              <tr>
+                <td colspan="2">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1" cellspacing="0" cellpadding="1" frame="void">
+                    <tr>
+                      <td colspan="6" align="left" style="font-size: 8pt">
+                        <p style="font-size: 8pt">SECTION 8. SOURCE REDUCTION AND WASTE MANAGEMENT</p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td colspan="2"></td>
+                      <td align="center">
+                        <p style="font-size: 8pt">
+                          Column A
+                          <br />
+                          Prior Year
+                          <br />
+                          (pounds/year*)
+                        </p>
+                      </td>
+                      <td align="center">
+                        <p style="font-size: 8pt">
+                          Column B
+                          <br/>
+                          Current Reporting Year
+                          <br/>
+                          (pounds/year*)
+                        </p>
+                      </td>
+                      <td align="center">
+                        <p style="font-size: 8pt">
+                          Column C
+                          <br/>
+                          Following Year
+                          <br/>
+                          (pounds/year*)
+                        </p>
+                      </td>
+                      <td align="center">
+                        <p style="font-size: 8pt">
+                          Column D
+                          <br/>
+                          Second Following Year
+                          <br/>
+                          (pounds/year*)
+                        </p>
+                      </td>
+                    </tr>
+                    <xsl:choose>
+                      <xsl:when test="TRI:SubmissionReportingYear &gt;= '1991' and TRI:SubmissionReportingYear &lt;= '2002'">
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">8.1</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Quantity Released
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+                      </xsl:when>
+                      <xsl:otherwise>
+	                    <tr>
+	                    	<xsl:choose>
+	                    		<xsl:when test="TRI:SubmissionReportingYear &lt; '2014'">
+	                    			<td width="5%" align="center">
+	                        			<p style="font-size: 8pt">8.1</p>
+	                      			</td>
+	                      			<td align="center">
+	                        			<p style="font-size: 8pt">&#160;</p>
+	                      			</td>
+	                    		</xsl:when>
+	                    		<xsl:otherwise>
+	                    			<td width="5%" align="center" colspan="2">
+	                        			<p style="font-size: 8pt">8.1 - 8.7 Production-Related Waste Managed</p>
+	                      			</td>
+	                    		</xsl:otherwise>
+	                    	</xsl:choose>
+
+	                      <td>
+	                        <p style="background-color: gray">
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="background-color: gray">
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="background-color: gray">
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="background-color: gray">
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">8.1a</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Total on-site disposal to Class I
+	                          <br/>
+	                          Underground Injection Wells, RCRA
+	                          <br/>
+	                          Subtitle C landfills, and other landfills
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">8.1b</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Total other on-site disposal or other
+	                          <br/>
+	                          releases
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteOtherDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteOtherDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteOtherDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OnsiteOtherDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">8.1c</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Total off-site disposal to Class I
+	                          <br/>
+	                          Underground Injection Wells, RCRA
+	                          <br/>
+	                          Subtitle C landfills, and other landfills
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OffsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OffsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OffsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OffsiteUICDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+	                    <tr>
+	                      <td width="5%" align="center">
+	                        <p style="font-size: 8pt">8.1d</p>
+	                      </td>
+	                      <td align="left">
+	                        <p style="font-size: 8pt">
+	                          Total other off-site disposal or other
+	                          <br/>
+	                          releases
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OffsiteOtherDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OffsiteOtherDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OffsiteOtherDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                      <td>
+	                        <p style="font-size: 8pt">
+	                          <xsl:for-each select="TRI:SourceReductionQuantity">
+	                            <xsl:for-each select="TRI:OffsiteOtherDisposalQuantity">
+	                              <xsl:choose>
+	                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+	                                  <xsl:choose>
+	                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+	                                      <span class="answerText">NA&#160;</span>
+	                                    </xsl:when>
+	                                    <xsl:otherwise>
+	                                      <span class="answerText">
+	                                        <xsl:value-of select="TRI:TotalQuantity"/>
+	                                      &#160;</span>
+	                                    </xsl:otherwise>
+	                                  </xsl:choose>
+	                                </xsl:when>
+	                              </xsl:choose>
+	                            </xsl:for-each>
+	                          </xsl:for-each>
+	                          <br/>
+	                        </p>
+	                      </td>
+	                    </tr>
+	                  </xsl:otherwise>
+                    </xsl:choose>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.2</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Quantity used for energy recovery
+                          <br/>
+                          on-site
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteEnergyRecoveryQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteEnergyRecoveryQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteEnergyRecoveryQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteEnergyRecoveryQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.3</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Quantity used for energy recovery
+                          <br/>
+                          off-site
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteEnergyRecoveryQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteEnergyRecoveryQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteEnergyRecoveryQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteEnergyRecoveryQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.4</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Quantity recycled on-site
+                          <br/>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteRecycledQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteRecycledQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteRecycledQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteRecycledQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.5</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Quantity recycled off-site
+                          <br/>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteRecycledQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteRecycledQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteRecycledQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteRecycledQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.6</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Quantity treated on-site
+                          <br/>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteTreatedQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteTreatedQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteTreatedQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OnsiteTreatedQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.7</p>
+                      </td>
+                      <td align="left">
+                        <p style="font-size: 8pt">
+                          Quantity treated off-site
+                          <br/>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteTreatedQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '-1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteTreatedQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '0'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteTreatedQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '1'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                          <xsl:for-each select="TRI:SourceReductionQuantity">
+                            <xsl:for-each select="TRI:OffsiteTreatedQuantity">
+                              <xsl:choose>
+                                <xsl:when test="TRI:YearOffsetMeasure = '2'">
+                                  <xsl:choose>
+                                    <xsl:when test="TRI:TotalQuantityNAIndicator = 'true'">
+                                      <span class="answerText">NA&#160;</span>
+                                    </xsl:when>
+                                    <xsl:otherwise>
+                                      <span class="answerText">
+                                        <xsl:value-of select="TRI:TotalQuantity"/>
+                                      &#160;</span>
+                                    </xsl:otherwise>
+                                  </xsl:choose>
+                                </xsl:when>
+                              </xsl:choose>
+                            </xsl:for-each>
+                          </xsl:for-each>
+                          <br/>
+                        </p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.8</p>
+                      </td>
+                      <td colspan="2" align="left">
+                        <p style="font-size: 8pt">
+                        	<xsl:choose>
+                        		<xsl:when test="TRI:SubmissionReportingYear &lt; '2014'">
+                        			Quantity released to the environment as a result of
+                          			remedial actions,
+                          			<br/>
+                          			catastrophic events, or one-time events not associated
+                          			with production processes (pounds/year)
+                        		</xsl:when>
+                        		<xsl:otherwise>
+                        			Non-production-related waste managed**
+                        		</xsl:otherwise>
+                        	</xsl:choose>
+                        </p>
+                      </td>
+                      <td colspan="3">
+                        <span class="answerText">
+                          <xsl:choose>
+                            <xsl:when test="TRI:SourceReductionQuantity/TRI:OneTimeReleaseNAIndicator = 'true'">NA</xsl:when>
+                            <xsl:otherwise>
+                              <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OneTimeReleaseQuantity"/>
+                            </xsl:otherwise>
+                          </xsl:choose>
+                        &#160;</span>
+                        <br/>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.9</p>
+                      </td>
+                      <xsl:choose>
+	                      <xsl:when test="TRI:SubmissionReportingYear &gt; '2013'">
+	                      	<td colspan="2" align="left">
+		                        <p style="font-size: 8pt">
+		                          <xsl:choose>
+		                            <xsl:when test="TRI:SourceReductionQuantity/TRI:ProductionRatioType = 'PRODUCTION'">[<span class="answerText">X</span>]</xsl:when>
+		                            <xsl:otherwise>[&#160;]</xsl:otherwise>
+		                          </xsl:choose>
+		                          Production ratio or
+		                          <xsl:choose>
+		                            <xsl:when test="TRI:SourceReductionQuantity/TRI:ProductionRatioType = 'ACTIVITY'">[<span class="answerText">X</span>]</xsl:when>
+		                            <xsl:otherwise>[&#160;]</xsl:otherwise>
+		                          </xsl:choose>
+		                          Activity ratio (select one and enter value to right)
+		                        </p>
+		                      </td>
+	                      </xsl:when>
+	                      <xsl:otherwise>
+		                      <td colspan="2" align="left">
+		                        <p style="font-size: 8pt">Production ratio or activity index</p>
+		                      </td>
+	                      </xsl:otherwise>
+                      </xsl:choose>
+                      <td colspan="3">
+                        <span class="answerText">
+                          <xsl:choose>
+                            <xsl:when test="TRI:SourceReductionQuantity/TRI:ProductionRatioNAIndicator = 'true'">NA</xsl:when>
+                            <xsl:otherwise>
+                              <xsl:value-of select="TRI:SourceReductionQuantity/TRI:ProductionRatioMeasure"/>
+                            </xsl:otherwise>
+                          </xsl:choose>
+                        &#160;</span>
+                        <br/>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td width="5%" align="center">
+                        <p style="font-size: 8pt">8.10</p>
+                      </td>
+                      <xsl:choose>
+						<xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+						   <td colspan="5">
+						   <p style="font-size: 8pt">
+						     Did your facility engage in any source reduction activities for this chemical during the reporting
+year? If not, enter "NA" in Section 8.10.1 and answer Section 8.11.
+						   </p>
+						  </td>
+						</xsl:when>
+						<xsl:otherwise>
+						   <td colspan="2">
+						   <p style="font-size: 8pt">
+							  Did your facility engage in any newly implemented source reduction activities for this
+							  chemical during the reporting year?
+							  <br/>
+							  If so, complete the following section; if not, check NA.
+							</p>
+						  </td>
+						  <td colspan="3">
+								NA [
+	                          <xsl:choose>
+	                            <xsl:when test="TRI:SourceReductionNAIndicator = 'true'">
+	                              <span class="answerText">X</span>
+	                            </xsl:when>
+	                            <xsl:otherwise>&#160;</xsl:otherwise>
+	                          </xsl:choose>
+	                          ]
+
+							<br/>
+							</td>
+						</xsl:otherwise>
+					</xsl:choose>
+
+                    </tr>
+                  </table>
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1"
+                         cellspacing="0" cellpadding="1" frame="above">
+                    <tr>
+                      <td width="5%"></td>
+                      <td align="center">
+                        <p style="font-size: 8pt">
+                          Source Reduction Activities
+                          <br/>
+                          (Enter code(s))
+                        </p>
+                      </td>
+                      <td colspan="3" align="center">
+                        <p style="font-size: 8pt">Methods to Identify Activity
+                                                  (Enter code(s))</p>
+                      </td>
+                      <xsl:if test="TRI:SubmissionReportingYear &gt; '2013'">
+                      	<td align="center">
+                        	<p style="font-size: 8pt">Estimated annual
+                        								reduction
+                        								(Enter code(s))
+                        								(optional)</p>
+                      	</td>
+                      </xsl:if>
+                    </tr>
+                    <xsl:choose>
+                      <xsl:when test="TRI:SourceReductionNAIndicator = 'true'">
+                        <tr>
+                          <td width="5%" align="center">
+                            <p style="font-size: 8pt">8.10.1</p>
+                          </td>
+                          <td>
+                            <p style="font-size: 8pt">
+                              <b style="color: blue;font-size: 9pt">NA</b>
+                              <br/>
+                            </p>
+                          </td>
+                          <td style="text-indent: 1em">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              <br/>
+                            </p>
+                          </td>
+                          <td style="text-indent: 1em">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              <br/>
+                            </p>
+                          </td>
+                          <td style="text-indent: 1em">
+                            <p style="font-size: 8pt">
+                              <br/>
+                              <br/>
+                            </p>
+                          </td>
+                        </tr>
+                      </xsl:when>
+                      <xsl:otherwise>
+                        <xsl:for-each select="TRI:SourceReductionActivity">
+                          <tr>
+                            <td width="5%" align="center">
+                              <p style="font-size: 8pt">
+                                8.10.<xsl:value-of select="count(preceding-sibling::TRI:SourceReductionActivity) + 1"/>
+                              </p>
+                            </td>
+                            <td>
+                              <p style="font-size: 8pt">
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:SourceReductionActivityCode"/>
+                                &#160;</span>
+                                <br/>
+                              </p>
+                            </td>
+                            <td style="text-indent: 1em" width="15%"
+                                align="center">
+                              <p style="font-size: 8pt">
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:SourceReductionMethodCode[1]"/>
+                                &#160;</span>
+                                <br/>
+                                <br/>
+                              </p>
+                            </td>
+                            <td style="text-indent: 1em" width="15%"
+                                align="center">
+                              <p style="font-size: 8pt">
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:SourceReductionMethodCode[2]"/>
+                                &#160;</span>
+                                <br/>
+                                <br/>
+                              </p>
+                            </td>
+                            <td style="text-indent: 1em" width="15%"
+                                align="center">
+                              <p style="font-size: 8pt">
+                                <span class="answerText">
+                                  <xsl:value-of select="TRI:SourceReductionMethodCode[3]"/>
+                                &#160;</span>
+                                <br/>
+                                <br/>
+                              </p>
+                            </td>
+                            <xsl:choose>
+	                            <xsl:when test="../TRI:SubmissionReportingYear &gt; '2013'">
+	                            	<td style="text-indent: 1em" width="15%"
+		                                align="center">
+		                              <p style="font-size: 8pt">
+		                                <span class="answerText">
+		                                  <xsl:value-of select="TRI:SourceReductionEfficiencyCode"/>
+		                                &#160;</span>
+		                                <br/>
+		                                <br/>
+		                              </p>
+		                            </td>
+	                            </xsl:when>
+                            </xsl:choose>
+                          </tr>
+                        </xsl:for-each>
+                      </xsl:otherwise>
+                    </xsl:choose>
+                    <xsl:if test="TRI:SubmissionReportingYear &lt; '2011'">
+                      <tr>
+
+						  <td width="5%" align="center">
+							<p style="font-size: 8pt">8.11</p>
+						  </td>
+						  <td colspan="2">
+
+							<p style="font-size: 8pt">If you wish to submit
+													  additional optional
+													  information on source
+													  reduction, recycling, or
+													  pollution control activities,
+													  check "Yes."</p>
+						  </td>
+						  <td colspan="2" style="font-size: 8pt">
+							<p style="font-size: 8pt">
+							  Yes [
+
+							  <xsl:choose>
+								<xsl:when test="TRI:SubmissionAdditionalDataIndicator = 'true'">
+								  <span class="answerText">X</span>
+								</xsl:when>
+							  </xsl:choose>
+							  ]
+
+							</p>
+						  </td>
+						</tr>
+                    </xsl:if>
+                  </table>
+                </td>
+              </tr>
+            </table>
+          </center>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0"
+                 style="font-size: 8pt" border="0">
+            <tr>
+              <td width="50%">
+                <p style="font-size: 8pt">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+                  		EPA Form 9350-1 (Rev. <xsl:value-of select="$RevisionDateFormR"/>) - Previous editions are obsolete.
+                  	</xsl:if>
+                </p>
+              </td>
+              <td align="right">
+                <p style="font-size: 8pt">
+                	*For Dioxin and Dioxin-like Compounds, report in grams/year<br/>
+                	<xsl:if test="TRI:SubmissionReportingYear &gt; '2013'">
+                		** Includes quantities released to the environment or transferred off-site as a result of remedial actions, catastrophic events, or other one-time events not associated with production processes
+                	</xsl:if>
+                </p>
+              </td>
+            </tr>
+          </table>
+          <p style="page-break-before: always">&#160;</p>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="1"
+                 style="font-size: 8pt" border="0">
+            <tr>
+             <!--   <td width="90%">
+                <a name="PG-6_{$formID}"></a>
+                <p style="font-size: 8pt">
+                  <a href="#PG-1_{$formID}">1</a>
+                  <a href="#PG-2_{$formID}">2</a>
+                  <a href="#PG-3_{$formID}">3</a>
+                  <a href="#PG-4_{$formID}">4</a>
+                  <a href="#PG-5_{$formID}">5</a>
+                  <a href="#PG-6_{$formID}">Additional Info</a>
+                  <xsl:if test="$ScheduleOneNA = 'false'">
+                      <a href="#S1_PG-1_{$formID}">Schedule 1</a>
+                  </xsl:if>
+                </p>
+              </td>-->
+            </tr>
+          </table>
+          <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%"
+                 style="font-size: 8pt">
+            <tr>
+              <td colspan="2">
+                <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="1" cellspacing="0" cellpadding="1" frame="void">
+                  <tr>
+                    <td>
+                        TRI Facility ID Number
+                        <hr />
+                        <span class="answerText">
+                          <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                        &#160;</span>
+                      <hr />
+                      Toxic Chemical, Category, or Generic Name
+                      <hr />
+                      <span class="answerText">
+                        <xsl:choose>
+                          <xsl:when test="TRI:ChemicalIdentification/TRI:ChemicalNameText='NA'">
+                            <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalMixtureNameText"/>
+                          </xsl:when>
+                          <xsl:otherwise>
+                            <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalNameText"/>
+                          </xsl:otherwise>
+                        </xsl:choose>
+                      &#160;</span>
+                    </td>
+                  </tr>
+                </table>
+              </td>
+            </tr>
+          </table>
+          <br/>
+          <table border="1" width="99%" style="font-size: 8pt" cellspacing="0" cellpadding="1">
+            <tr>
+              <td align="left" style="font-size: 8pt">
+                <p style="font-size: 8pt">
+                  <b>Additional optional information on source reduction,
+                     recycling, or pollution control activities.</b>
+                </p>
+              </td>
+            </tr>
+            <tr>
+              <td align="left" style="font-size: 8pt">
+                <span class="answerText">
+                  <xsl:value-of select="TRI:OptionalInformationText"/>
+                  &#160;
+                </span>
+              </td>
+            </tr>
+          </table>
+          <br/>
+          <xsl:choose>
+          	<xsl:when test="TRI:SubmissionReportingYear &gt; '2013'">
+          		<table summary="table used for layout purposes" border="1" width="99%" style="font-size: 8pt" cellspacing="0" cellpadding="1">
+		            <tr>
+		              <td colspan="2" align="left" style="font-size: 8pt">
+		                <p style="font-size: 8pt">
+		                  <b>Section 8.11: If you wish to submit additional optional information on source reduction, recycling, or pollution control activities, provide it here.</b>
+		                </p>
+		              </td>
+		            </tr>
+		            <tr>
+			           <td style="width: 20%;">
+			            <p style="font-size: 8pt">
+			             <b>Topic</b>
+			            </p>
+			           </td>
+			           <td>
+			            <p style="font-size: 8pt">
+			             <b>Comment</b>
+			            </p>
+			           </td>
+	        		</tr>
+		            <xsl:for-each select="TRI:TRIComment">
+		            	<xsl:if test="TRI:TRICommentSection = '8.11'">
+			            	<tr>
+			            		<td style="width: 20%;">
+			            			<p style="font-size: 8pt">
+			            				<xsl:value-of select="TRI:TRICommentTypeDescription"/>
+			            			</p>
+			            		</td>
+			            		<td>
+			            			<p style="font-size: 8pt">
+			            				<xsl:value-of select="TRI:TRICommentText"/>
+			            			</p>
+			            		</td>
+			            	</tr>
+		            	</xsl:if>
+		            </xsl:for-each>
+		          </table>
+		          <br/>
+		          <table summary="table used for layout purposes" border="1" width="99%" style="font-size: 8pt" cellspacing="0" cellpadding="1">
+		            <tr>
+		              <td colspan="2" align="left" style="font-size: 8pt">
+		                <p style="font-size: 8pt">
+		                  <b>Section 9.1: If you wish to submit any miscellaneous, additional, or optional information regarding your Form R submission, provide it here.</b>
+		                </p>
+		              </td>
+		            </tr>
+		            <tr>
+			           <td style="width: 20%;">
+			            <p style="font-size: 8pt">
+			             <b>Topic</b>
+			            </p>
+			           </td>
+			           <td>
+			            <p style="font-size: 8pt">
+			             <b>Comment</b>
+			            </p>
+			           </td>
+	        		</tr>
+		            <xsl:for-each select="TRI:TRIComment">
+		            	<xsl:if test="TRI:TRICommentSection = '9.1'">
+			            	<xsl:if test="TRI:TRICommentText !=''">
+			            	<tr>
+			            		<td style="width: 20%;">
+			            			<p style="font-size: 8pt">
+			            				<xsl:value-of select="TRI:TRICommentTypeDescription"/>
+			            			</p>
+			            		</td>
+			            		<td>
+			            			<p style="font-size: 8pt">
+			            				<xsl:value-of select="TRI:TRICommentText"/>
+			            			</p>
+			            		</td>
+			            	</tr>
+		            	</xsl:if>
+		            	</xsl:if>
+		            </xsl:for-each>
+		          </table>
+          	</xsl:when>
+	        <xsl:when test="TRI:SubmissionReportingYear &gt; '2010'">
+		        <table summary="table used for layout purposes" border="1" width="99%" style="font-size: 8pt" cellspacing="0" cellpadding="1">
+		          <tr>
+		            <td align="left" style="font-size: 8pt">
+		              <p style="font-size: 8pt">
+		                <b>Miscellaneous, additional, or optional information regarding the Form R submission</b>
+		              </p>
+		            </td>
+		          </tr>
+		          <tr>
+		            <td align="left" style="font-size: 8pt">
+		              <span class="answerText">
+		                <xsl:value-of select="TRI:MiscellaneousInformationText"/>
+		              &#160;</span>
+		            </td>
+		          </tr>
+		        </table>
+		    </xsl:when>
+	      </xsl:choose>
+
+          <p style="page-break-before: always"></p>
+
+          <xsl:if test="$ScheduleOneNA = 'false'">
+              <!-- Schedule 1 Page One -->
+
+              <xsl:call-template name="ScheduleOnePageOne">
+                <xsl:with-param name="baseStreamID">0</xsl:with-param>
+                <xsl:with-param name="formID"><xsl:value-of select="$formID" /></xsl:with-param>
+                <xsl:with-param name="OMBNumberSchedule1"><xsl:value-of select="$OMBNumberSchedule1" /></xsl:with-param>
+                <xsl:with-param name="ApprovalDateSchedule1"><xsl:value-of select="$ApprovalDateSchedule1" /></xsl:with-param>
+              </xsl:call-template>
+
+              <!-- Additional Page One(s) if necessary -->
+              <xsl:for-each select="TRI:OnsiteReleaseQuantity/TRI:WaterStream">
+                <xsl:if test="TRI:WaterSequenceNumber > 2 and TRI:WaterSequenceNumber mod 3 = 0">
+                  <xsl:variable name="baseStreamID" select="TRI:WaterSequenceNumber" />
+                  <xsl:for-each select="../..">
+                    <xsl:call-template name="ScheduleOnePageOne">
+                      <xsl:with-param name="baseStreamID"><xsl:value-of select="$baseStreamID" /></xsl:with-param>
+                      <xsl:with-param name="formID"><xsl:value-of select="$formID" /></xsl:with-param>
+                      <xsl:with-param name="OMBNumberSchedule1"><xsl:value-of select="$OMBNumberSchedule1" /></xsl:with-param>
+                      <xsl:with-param name="ApprovalDateSchedule1"><xsl:value-of select="$ApprovalDateSchedule1" /></xsl:with-param>
+                    </xsl:call-template>
+                  </xsl:for-each>
+                </xsl:if>
+              </xsl:for-each>
+
+          <!-- Schedule 1 Page Two -->
+          <div class="landscapeArea">
+          <tr>
+	              <td align="center" width="100%">
+	                <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+	                  *** Do not send to EPA: This is the final copy of your form.***
+	                &#160;</span>
+	              </td>
+           </tr>
+            <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 8pt" border="0">
+              <tr>
+                <td width="30%">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	                  Form Approved OMB Number:<span class="smallAnswer"><xsl:value-of select="$OMBNumberSchedule1" />&#160;</span><br />
+	                  Approval Expires: <span class="smallAnswer"><xsl:value-of select="$ApprovalDateSchedule1" />&#160;</span>
+	                </xsl:if>
+                </td>
+                <td width="10%">
+                  <p style="font-size: 8pt"><b>Page 2 of 4</b></p>
+                </td>
+              </tr>
+            </table>
+
+          <center>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt;">
+
+              <tr>
+                <td colspan="26" align="center">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="0" cellspacing="0" cellpadding="0" frame="void">
+                    <tr>
+                      <td style="font-size: 10pt"><b> EPA </b></td>
+                      <td align="center" style="font-size: 14pt"><b>FORM R Schedule 1</b></td>
+                      <td><p style="font-size: 8pt">TRI Facility ID Number:</p></td>
+                    </tr>
+                    <tr>
+                      <td>
+                        <p style="font-size: 8pt">United States<br />Environmental Protection<br />Agency</p>
+                      </td>
+                      <td align="center">
+                        <p style="font-size: 14pt"><b>PART II.  CHEMICAL-SPECIFIC INFORMATION (continued)</b></p>
+                      </td>
+                      <td class="answerText"><xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/></td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+
+              <tr>
+                <td align="left" colspan="26" style="font-size: 8pt">
+                  <p style="font-size: 9pt"><b>Section 5. Quantity Of Dioxin And Dioxin-Like Compounds Entering Each Environmental Medium On-site (continued)</b></p>
+                </td>
+              </tr>
+
+              <tr>
+                <td colspan="2" rowspan="3" style="background-color: gray">&#160;</td>
+                <td align="center" colspan="6" style="font-size: 8pt">
+                  <p style="font-size: 8pt"><b>5.4</b>&#160;&#160; Underground Injection</p>
+                </td>
+                <td align="center" colspan="18" style="font-size: 8pt">
+                  <p style="font-size: 8pt"><b>5.5</b>&#160;&#160; Disposal to Land On-site</p>
+                </td>
+              </tr>
+
+              <tr>
+                <td style="font-size: 8pt" align="center"><b>5.4.1</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator[../../TRI:EnvironmentalMediumCode = 'UNINJ I'] = 'true'">
+                  X
+                  </xsl:if>&#160;
+                </td>
+
+                <td style="font-size: 8pt" align="center"><b>5.4.2</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator[../../TRI:EnvironmentalMediumCode = 'UNINJ IIV'] = 'true'">
+                  X
+                  </xsl:if>&#160;
+                </td>
+
+                <td style="font-size: 8pt" align="center"><b>5.5.1A</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator[../../TRI:EnvironmentalMediumCode = 'RCRA C'] = 'true'">
+                  X
+                  </xsl:if>&#160;
+                </td>
+
+                <td style="font-size: 8pt" align="center"><b>5.5.1B</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator[../../TRI:EnvironmentalMediumCode = 'OTH LANDF'] = 'true'">
+                  X
+                  </xsl:if>&#160;
+                </td>
+
+                <td style="font-size: 8pt" align="center"><b>5.5.2</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator[../../TRI:EnvironmentalMediumCode = 'LAND TREA'] = 'true'">
+                  X
+                  </xsl:if>&#160;
+                </td>
+
+                <td style="font-size: 8pt" align="center"><b>5.5.3A</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator[../../TRI:EnvironmentalMediumCode = 'SI 5.5.3A'] = 'true'">
+                  X
+                  </xsl:if>&#160;
+                </td>
+
+                <td style="font-size: 8pt" align="center"><b>5.5.3B</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator[../../TRI:EnvironmentalMediumCode = 'SI 5.5.3B'] = 'true'">
+                  X
+                  </xsl:if>&#160;
+                </td>
+
+                <td style="font-size: 8pt" align="center"><b>5.5.4</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator[../../TRI:EnvironmentalMediumCode = 'OTH DISP'] = 'true'">
+                  X
+                  </xsl:if>&#160;
+                </td>
+
+              </tr>
+
+              <tr>
+                <td colspan="3" style="font-size: 8pt" align="center">
+                	<xsl:choose>
+                		<xsl:when test="TRI:SubmissionReportingYear &lt; '2014'">
+                			Underground Injection on-site to Class I Wells
+                		</xsl:when>
+                		<xsl:otherwise>
+                			Class I Underground Injection Wells
+                		</xsl:otherwise>
+                	</xsl:choose>
+                </td>
+                <td colspan="3" style="font-size: 8pt" align="center">
+                	<xsl:choose>
+                		<xsl:when test="TRI:SubmissionReportingYear &lt; '2014'">
+                			Underground Injection on-site to Class II-V Wells
+                		</xsl:when>
+                		<xsl:otherwise>
+                			Class II-V Underground Injection Wells
+                		</xsl:otherwise>
+                	</xsl:choose>
+
+                </td>
+                <td colspan="3" style="font-size: 8pt" align="center">
+                  RCRA Subtitle C landfills
+                </td>
+                <td colspan="3" style="font-size: 8pt" align="center">
+                  Other landfills
+                </td>
+                <td colspan="3" style="font-size: 8pt" align="center">
+                  Land treatment/application farming
+                </td>
+                <td colspan="3" style="font-size: 8pt" align="center">
+                  RCRA Subtitle C surface impoundment
+                </td>
+                <td colspan="3" style="font-size: 8pt" align="center">
+                  Other surface impoundment
+                </td>
+                <td colspan="3" style="font-size: 8pt" align="center">
+                  Other disposal
+                </td>
+              </tr>
+
+              <xsl:call-template name="ScheduleOnePageTwoRow" />
+
+            </table>
+          </center>
+
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 7pt" border="0">
+            <tr>
+              <td width="60%">
+                <p style="font-size: 8pt">
+                  EPA Form 9350-3
+                </p>
+              </td>
+              <td width="30%">
+                <p style="font-size: 8pt">Printed using TRI-MEweb</p>
+              </td>
+            </tr>
+          </table>
+          </div>
+
+          <!-- Schedule 1 Page Three -->
+          <xsl:variable name="potwTEQ" select="TRI:POTWWasteQuantity/TRI:ToxicEquivalencyIdentification" />
+
+            <div style="width: 1010px;" class="landscapeArea">
+            <tr>
+	              <td align="center" width="100%">
+	                <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+	                  *** Do not send to EPA: This is the final copy of your form.***
+	                &#160;</span>
+	              </td>
+            </tr>
+            <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 8pt" border="0">
+              <tr>
+                <td width="30%">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	                  Form Approved OMB Number:<span class="smallAnswer"><xsl:value-of select="$OMBNumberSchedule1" />&#160;</span><br />
+    	              Approval Expires: <span class="smallAnswer"><xsl:value-of select="$ApprovalDateSchedule1" />&#160;</span>
+    	            </xsl:if>
+                </td>
+                <td width="10%">
+                  <p style="font-size: 8pt"><b>Page 3 of 4</b></p>
+                </td>
+              </tr>
+            </table>
+
+          <center>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt;">
+              <tr>
+                <td colspan="18" align="center">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="0" cellspacing="0" cellpadding="0" frame="void">
+                    <tr>
+                      <td style="font-size: 8pt">
+                        <p style="font-size: 10pt"><b> EPA </b></p>
+                      </td>
+                      <td align="center" style="font-size: 10pt">
+                        <p style="font-size: 14pt"><b>FORM R Schedule 1</b></p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">TRI Facility ID Number:</p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td>
+                        <p style="font-size: 8pt">United States<br />Environmental Protection<br />Agency</p>
+                      </td>
+                      <td align="center">
+                        <p style="font-size: 14pt"><b>PART II.  CHEMICAL-SPECIFIC INFORMATION (continued)</b></p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                            <span class="answerText">
+                              <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                            &#160;</span>
+                        </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+
+              <tr>
+                <td align="left" colspan="18" style="font-size: 8pt">
+                  <p style="font-size: 9pt"><b>SECTION 6. TRANSFERS OF DIOXIN AND DIOXIN-LIKE COMPOUNDS IN WASTES TO OFF-SITE LOCATIONS</b></p>
+                </td>
+              </tr>
+              <tr>
+                 <xsl:choose>
+				  <xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+					 <td align="left" colspan="18" style="font-size: 8pt" width="50%">
+					  <p style="font-size: 9pt"><b>6.1 DISCHARGES TO PUBLICLY-OWNED TREATMENT WORKS (POTWs)</b></p>
+					</td>
+				  </xsl:when>
+				  <xsl:otherwise>
+					<td align="left" colspan="9" style="font-size: 8pt" width="50%">
+					  <p style="font-size: 9pt"><b>6.1 DISCHARGES TO PUBLICLY-OWNED TREATMENT WORKS (POTWs)</b></p>
+					</td>
+					<td align="left" colspan="9" style="font-size: 8pt" width="50%">
+					  <p style="font-size: 8pt">
+						NA [
+						  <xsl:if test="TRI:POTWWasteQuantity/TRI:WasteQuantityNAIndicator = 'true' or not(TRI:POTWWasteQuantity)">
+							<span class="answerText">X</span>
+						  </xsl:if>
+						]
+					  </p>
+					</td>
+				  </xsl:otherwise>
+				</xsl:choose>
+              </tr>
+              <xsl:for-each select="TRI:POTWWasteQuantity">
+              <xsl:choose>
+				<xsl:when test="../TRI:SubmissionReportingYear &lt; '2011'">
+				  <tr>
+					  <td colspan="18" align="center" style="font-size: 8pt"><b>6.1.A.3 Mass (grams) of each compound in the category (1-17)
+					  </b>
+					</td>
+				  </tr>
+				   <tr>
+					  <td style="font-size: 8pt">1</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency1Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">2</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency2Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">3</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency3Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">4</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency4Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">5</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency5Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">6</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency6Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">7</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency7Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">8</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency8Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">9</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency9Value" />&#160;</td>
+					</tr>
+					<tr>
+					  <td style="font-size: 8pt">10</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency10Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">11</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency11Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">12</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency12Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">13</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency13Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">14</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency14Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">15</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency15Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">16</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency16Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">17</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency17Value" />&#160;</td>
+
+					  <td colspan="2" style="background-color:gray">&#160;</td>
+				  </tr>
+				</xsl:when>
+				<xsl:otherwise>
+				  <tr>
+					  <td colspan="2" align="left" style="font-size: 9pt"><b>6.1.<xsl:value-of select="TRI:POTWSequenceNumber" />
+					  </b></td>
+					  <td colspan="16" align="left" style="font-size: 8pt"><b>C. Mass (grams) of each compound in the category (1-17)
+					  </b></td>
+				  </tr>
+				  <tr>
+					  <td align="center" colspan="2" style="font-size: 8pt">
+						  <b><xsl:value-of select="TRI:POTWSequenceNumber" />.</b>
+					  </td>
+					  <td style="font-size: 8pt">1</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency1Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">2</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency2Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">3</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency3Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">4</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency4Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">5</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency5Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">6</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency6Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">7</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency7Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">8</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency8Value" />&#160;</td>
+					</tr>
+					<tr>
+					  <td style="font-size: 8pt">9</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency9Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">10</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency10Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">11</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency11Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">12</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency12Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">13</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency13Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">14</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency14Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">15</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency15Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">16</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency16Value" />&#160;</td>
+
+					  <td style="font-size: 8pt">17</td>
+					  <td align="center" class="teqAnswer"><xsl:value-of select="TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency17Value" />&#160;</td>
+				  </tr>
+		        </xsl:otherwise>
+                </xsl:choose>
+
+          	</xsl:for-each>
+              <tr>
+                <xsl:choose>
+				  <xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+				    <td align="left" colspan="18" style="font-size: 8pt">
+					  <p style="font-size: 9pt"><b>6.2  TRANSFERS TO OTHER OFF-SITE LOCATIONS</b></p>
+					</td>
+				  </xsl:when>
+				  <xsl:otherwise>
+				    <td align="left" colspan="9" style="font-size: 8pt">
+					  <p style="font-size: 9pt"><b>6.2  TRANSFERS TO OTHER OFF-SITE LOCATIONS</b></p>
+					</td>
+					<td align="left" colspan="9" style="font-size: 8pt;">
+						<p style="font-size: 8pt">
+					   NA [
+
+						  <xsl:if test="not(TRI:TransferLocation)">
+
+								<span class="answerText">X</span>
+
+						  </xsl:if>
+
+						 ]
+					 </p>
+					</td>
+				  </xsl:otherwise>
+				</xsl:choose>
+              </tr>
+
+
+              <!-- Loop through transfers; if not potw write header and call template for transfer TEQ quantities -->
+              <xsl:for-each select="TRI:TransferLocation">
+                <xsl:if test="TRI:POTWIndicator = 'false'">
+                  <tr>
+                    <td colspan="2" align="left" style="font-size: 8pt">
+                      <p style="font-size: 9pt">
+                        <xsl:choose>
+                        <xsl:when test="../TRI:TransferLocation[1]/TRI:POTWIndicator = 'true'">
+                          <b>6.2.<xsl:value-of select="count(preceding-sibling::TRI:TransferLocation)-1"/></b>
+                        </xsl:when>
+                        <xsl:otherwise>
+                          <b>6.2.<xsl:value-of select="count(preceding-sibling::TRI:TransferLocation)-1"/></b>
+                        </xsl:otherwise>
+                        </xsl:choose>
+                      </p>
+                    </td>
+                    <td colspan="16" align="left" style="font-size: 8pt">
+                      <p style="font-size: 8pt"><b>D. Mass (grams) of each compound in the category (1-17)</b></p>
+                    </td>
+                  </tr>
+
+                  <!-- Loop through TEQ values -->
+                  <xsl:for-each select="TRI:TransferQuantity">
+                    <xsl:call-template name="ScheduleOnePageThreeRow" />
+                  </xsl:for-each>
+
+                </xsl:if>
+              </xsl:for-each>
+
+              <!-- Put in 2 blank section 6.2 TEQ sections if there is no data -->
+              <xsl:if test="count(TRI:TransferLocation) = 0 or (count(TRI:TransferLocation) = 1 and TRI:TransferLocation[1]/TRI:POTWIndicator = 'true')">
+                  <xsl:call-template name="ScheduleOnePageThreeRowBlank"><xsl:with-param name="i">1</xsl:with-param></xsl:call-template>
+                  <xsl:call-template name="ScheduleOnePageThreeRowBlank"><xsl:with-param name="i">2</xsl:with-param></xsl:call-template>
+              </xsl:if>
+
+              <tr>
+                <td align="left" colspan="18" style="font-size: 8pt">
+                  <!--p style="font-size: 8pt">
+                    If additional pages of Section 6.2 are attached, indicate the total number of pages in this box&#160;&#160;
+                    <span style="border: 1px solid black; padding: 2px; text-align:center; width: 25px;">
+                      &#160;
+                    &#160;</span>
+                    <br />
+                    and indicate the Section 6.2 page number in this box&#160;&#160;
+                    <span style="border: 1px solid black; padding: 2px; text-align:center; width: 25px;">
+                      &#160;
+                    &#160;</span>&#160;
+                    (example: 1,2,3, etc.)
+                  </p-->
+                  &#160;
+                </td>
+              </tr>
+
+            </table>
+          </center>
+
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 7pt" border="0">
+            <tr>
+              <td width="60%">
+                <p style="font-size: 8pt">
+                  EPA Form 9350-3
+                </p>
+              </td>
+              <td width="30%">
+                <p style="font-size: 8pt">Printed using TRI-MEweb</p>
+              </td>
+            </tr>
+          </table>
+          </div>
+
+          <!-- Schedule 1 Page Four -->
+
+         <div width="1010px;" class="landscapeArea">
+         	<tr>
+	              <td align="center" width="100%">
+	                <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+	                  *** Do not send to EPA: This is the final copy of your form.***
+	                &#160;</span>
+	              </td>
+            </tr>
+            <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 8pt" border="0">
+              <tr>
+                <td width="30%">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+                  		Form Approved OMB Number:<span class="smallAnswer"><xsl:value-of select="$OMBNumberSchedule1" />&#160;</span><br />
+                  		Approval Expires: <span class="smallAnswer"><xsl:value-of select="$ApprovalDateSchedule1" />&#160;</span>
+                  	</xsl:if>
+                </td>
+                <td width="10%">
+                  <p style="font-size: 8pt"><b>Page 4 of 4</b></p>
+                </td>
+              </tr>
+            </table>
+
+          <center>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt;">
+              <tr>
+                <td colspan="13" align="center">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="0" cellspacing="0" cellpadding="0" frame="void">
+                    <tr>
+                      <td style="font-size: 8pt">
+                        <p style="font-size: 10pt"><b> EPA </b></p>
+                      </td>
+                      <td align="center" style="font-size: 10pt">
+                        <p style="font-size: 14pt"><b>FORM R Schedule 1</b></p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">TRI Facility ID Number:</p>
+                      </td>
+                    </tr>
+                    <tr>
+                      <td>
+                        <p style="font-size: 8pt">United States<br />Environmental Protection<br />Agency</p>
+                      </td>
+                      <td align="center">
+                        <p style="font-size: 14pt"><b>PART II.  CHEMICAL-SPECIFIC INFORMATION (continued)</b></p>
+                      </td>
+                      <td>
+                        <p style="font-size: 8pt">
+                            <span class="answerText">
+                              <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                            &#160;</span>
+                        </p>
+                      </td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+
+              <tr>
+                <td align="left" colspan="13" style="font-size: 8pt">
+                  <p style="font-size: 9pt"><b>SECTION 8. SOURCE REDUCTION AND WASTE MANAGEMENT FOR DIOXIN AND DIOXIN-LIKE COMPOUNDS (current year only)</b></p>
+                </td>
+              </tr>
+
+
+              <tr>
+                <td colspan="2" rowspan="2" style="background-color:gray">&#160;</td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.1a</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.1b</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.1c</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.1d</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.2</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.3</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.4</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.5</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.6</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.7</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">8.8</p>
+                </td>
+              </tr>
+
+              <tr>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Total on-site disposal to Class 1 Underground Injection Wells, RCRA Subtitle C landfills, and other landfills</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Total other on-site disposal or other releases</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Total off-site disposal to Class 1 Underground Injection Wells, RCRA Subtitle C landfills, and other landfills</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Total other off-site disposal or other releases</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Quantity used for energy recovery on-site</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Quantity used for energy recovery off-site</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Quantity recycled on-site</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Quantity recycled off-site</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Quantity treated on-site</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Quantity treated off-site</p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Quantity released to the environment as a result of remedial actions, catastrophic events, or one-time events not associated with production processes</p>
+                </td>
+              </tr>
+
+              <xsl:call-template name="ScheduleOnePageFourRow" />
+
+            </table>
+          </center>
+
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 7pt" border="0">
+            <tr>
+              <td width="60%">
+                <p style="font-size: 8pt">
+                  EPA Form 9350-3
+                </p>
+              </td>
+              <td width="30%">
+                <p style="font-size: 8pt">Printed using TRI-MEweb</p>
+              </td>
+            </tr>
+          </table>
+          </div>
+          </xsl:if>
+
+      </xsl:when>
+      <xsl:otherwise>
+          <!-- Begin Form A : Form A data will be grouped together by revision codes, withdrawal codes, and public and technical contact infomration.
+                So, the following test chooses only to enter the form a section if the form a data encountered has not been encountered yet.
+          -->
+
+          <xsl:if test="count(preceding::TRI:Report[TRI:ReportType/TRI:ReportTypeCode = current()/TRI:ReportType/TRI:ReportTypeCode
+                                                         and concat(TRI:TechnicalContactNameText/sc:IndividualFullName, 'xx') = concat(current()/TRI:TechnicalContactNameText/sc:IndividualFullName, 'xx')
+                                                         and concat(TRI:TechnicalContactPhoneText, 'xx') = concat(current()/TRI:TechnicalContactPhoneText, 'xx')
+                                                         and concat(TRI:TechnicalContactEmailAddressText, 'xx') = concat(current()/TRI:TechnicalContactEmailAddressText, 'xx')
+                                                         and concat(TRI:PublicContactNameText/sc:IndividualFullName, 'xx') = concat(current()/TRI:PublicContactNameText/sc:IndividualFullName, 'xx')
+                                                         and concat(TRI:PublicContactPhoneText, 'xx') = concat(current()/TRI:PublicContactPhoneText, 'xx')
+                                                         and concat(TRI:PublicContactEmailAddressText, 'xx') = concat(current()/TRI:PublicContactEmailAddressText, 'xx')
+                                                         and sc:RevisionIndicator = current()/sc:RevisionIndicator
+                                                         and concat(TRI:ChemicalReportRevisionCode[1], 'xx') = concat(current()/TRI:ChemicalReportRevisionCode[1], 'xx')
+                                                         and concat(TRI:ChemicalReportRevisionCode[2], 'xx') = concat(current()/TRI:ChemicalReportRevisionCode[2], 'xx')
+                                                         and concat(TRI:ChemicalReportWithdrawalCode[1], 'xx') = concat(current()/TRI:ChemicalReportWithdrawalCode[1], 'xx')
+                                                         and concat(TRI:ChemicalReportWithdrawalCode[2], 'xx') = concat(current()/TRI:ChemicalReportWithdrawalCode[2], 'xx')
+                                                         and ../TRI:Facility = current()/../TRI:Facility
+                                                         ]) = 0">
+          <xsl:if test="count(preceding::TRI:Report) &gt; 0">
+            <p style="page-break-before: always">&#160;</p>
+          </xsl:if>
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" border="0">
+            <tr>
+             <td align="center" width="100%">
+              <span style="font-size: 12pt; color: red; font-weight: bold;" class="noPrint">
+               *** File Copy Only: Do Not Submit Paper Form to EPA ***
+              &#160;</span>
+             </td>
+            </tr>
+
+            <xsl:if test="SubmissionStatusText">
+             <tr>
+              <td>
+               <span class="fieldLabel" style="color:red">
+                Form Status:
+                <xsl:value-of select="SubmissionStatusText"/>
+               &#160;</span>
+              </td>
+             </tr>
+            </xsl:if>
+            <xsl:if test="ValidationStatusText">
+             <tr>
+              <td>
+               <span class="fieldLabel" style="color:red">
+                Validation Status:
+                <xsl:value-of select="ValidationStatusText"/>
+               &#160;</span>
+              </td>
+             </tr>
+            </xsl:if>
+
+           </table>
+           <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 8pt" border="0">
+            <tr>
+             <td width="30%">
+             	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	              <p style="font-size: 8pt">
+    	          Form Approved OMB Number:
+        	      <span class="smallAnswer">
+        	       <xsl:value-of select="$OMBNumberFormA"/>
+        	      &#160;</span>
+        	      </p>
+        	    </xsl:if>
+             </td>
+             <td width="10%">
+              <br/>
+             </td>
+            </tr>
+            <tr>
+             <td width="60%">
+              <p style="font-size: 8pt">
+              	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	               <i>(IMPORTANT: Read instructions before completing form; type or use fill-and-print form)</i>
+	            </xsl:if>
+              </p>
+             </td>
+             <td width="30%">
+             	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	              <p style="font-size: 8pt">
+    	          Approval Expires:
+    	          <span class="smallAnswer">
+    	           <xsl:value-of select="$ApprovalDateFormA"/>
+    	          &#160;</span>
+    	          </p>
+    	        </xsl:if>
+             </td>
+             <td width="10%">
+              <br/>
+             </td>
+            </tr>
+           </table>
+           <center>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-family: 'Arial'; font-size: 8pt">
+             <tr>
+              <td colspan="2" align="center">
+               <table summary="table used for layout purposes" width="100%" style="font-size: 10pt" cellspacing="0" cellpadding="1">
+                <tr>
+                 <td width="20%">
+                  <p style="font-size: 9pt">
+                   <span style="font-weight:bold">
+                    United States
+                    <br/>
+                    Environmental Protection Agency
+                   &#160;</span>
+                  </p>
+                 </td>
+                 <td nowrap="nowrap" align="center">
+                  <p style="font-size: 10pt">
+                   <span style="font-weight:bold">
+                    TOXICS CHEMICAL RELEASE INVENTORY
+                    <br/>
+                    FORM A
+                   &#160;</span>
+                  </p>
+                 </td>
+                </tr>
+               </table>
+              </td>
+              <td style="font-size: 8pt">
+                TRI Facility ID Number
+                <hr />
+                <span class="answerText">
+                 <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>&#160;</span>
+              </td>
+             </tr>
+             <tr>
+              <td colspan="3">
+               <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt" frame="void">
+                <tr>
+                 <td align="center" width="15%">
+                  <p style="font-size: 8pt">WHERE TO SEND COMPLETED FORMS: </p>
+                 </td>
+                 <td nowrap="nowrap">
+                  <p style="font-size: 8pt">
+                   1. TRI Data Processing Center
+                   <br />
+                   P.O. Box 10163
+                   <br />
+                   Fairfax, VA 22038
+                   <br />
+                   <span style="font-size: 8pt; color: red; font-weight: bold;">
+                   *** File Copy Only: Do Not Submit Paper Form to EPA ***
+                   &#160;</span>
+                  </p>
+                 </td>
+                 <td nowrap="nowrap">
+                  <p style="font-size: 8pt">
+                   2. APPROPRIATE STATE OFFICE
+                   <br/>
+                   (See instructions in Appendix F)
+                  </p>
+                 </td>
+                </tr>
+                <tr>
+                 <td colspan="3"></td>
+                </tr>
+               </table>
+               <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" frame="void">
+                <tr>
+                 <td width="33%">
+                  <p style="font-size: 9pt">This section only applies if you are revising or withdrawing a previously submitted form, otherwise leave blank:</p>
+                 </td>
+                 <td align="center" width="33%">
+                  <p style="font-size: 9pt">
+                   Revision (Enter up to two code(s))
+                   <br/>
+                   <br/>
+                   [
+                   <span class="answerText">
+                    <xsl:value-of select="TRI:ChemicalReportRevisionCode[1]"/>
+                   &#160;</span>
+                   ] [
+                   <span class="answerText">
+                    <xsl:value-of select="TRI:ChemicalReportRevisionCode[2]"/>
+                   &#160;</span>
+                   ]
+                  </p>
+                 </td>
+                 <td align="center" width="34%">
+                  <p style="font-size: 9pt">
+                   Withdrawal (Enter up to two code(s))
+                   <br/>
+                   <br/>
+                   [
+                   <span class="answerText">
+                    <xsl:value-of select="TRI:ChemicalReportWithdrawalCode[1]"/>
+                   &#160;</span>
+                   ] [
+                   <span class="answerText">
+                    <xsl:value-of select="TRI:ChemicalReportWithdrawalCode[2]"/>
+                   &#160;</span>
+                   ]
+                  </p>
+                 </td>
+                </tr>
+               </table>
+              </td>
+             </tr>
+             <tr>
+              <td align="left" colspan="3" style="font-size: 8pt">
+               <p style="font-size: 8pt">Important: See Instructions to determine when "Not Applicable (NA)" boxes should be checked.</p>
+              </td>
+             </tr>
+             <tr>
+              <td align="center" colspan="3">
+               <p style="font-size: 8pt">Part I. FACILITY IDENTIFICATION INFORMATION </p>
+              </td>
+             </tr>
+             <tr>
+              <td align="left" colspan="3" style="font-size: 8pt">
+                SECTION 1. REPORTING YEAR :
+                <u><span class="answerText"><xsl:value-of select="TRI:SubmissionReportingYear"/></span></u>
+                <br />
+              </td>
+             </tr>
+             <tr>
+              <td align="left" colspan="3">
+               <p style="font-size: 8pt">SECTION 2. TRADE SECRET INFORMATION </p>
+              </td>
+             </tr>
+             <tr>
+              <td align="left" style="font-size: 8pt">
+               <dl>
+                <dt>
+                 2.1 Are you claiming the toxic chemical identified on page 2 trade secret?
+                </dt>
+                <dd>
+                  [
+                  <xsl:choose>
+                   <xsl:when test="TRI:ChemicalTradeSecretIndicator = 'true'">
+                    <span class="answerText">X</span>
+                   </xsl:when>
+                  </xsl:choose>
+                  ] Yes (Answer question 2.2; attach substantiation forms)
+                </dd>
+                <dd>
+                  [
+                  <xsl:choose>
+                   <xsl:when test="TRI:ChemicalTradeSecretIndicator = 'false'">
+                    <span class="answerText">X</span>
+                   </xsl:when>
+                  </xsl:choose>
+                  ] NO (Do not answer 2.2; go to Section 3)
+                </dd>
+               </dl>
+              </td>
+              <td align="left">
+               <dl>
+                <dt>
+                 2.2 Is this copy
+                </dt>
+                <dd>
+                 <p style="font-size: 8pt">[ ] Sanitized [ ] Unsanitized</p>
+                </dd>
+                <dd>
+                 <p style="font-size: 8pt">(Answer only if "Yes" in 2.1)</p>
+                </dd>
+               </dl>
+              </td>
+              <td>
+               <br/>
+              </td>
+             </tr>
+             <tr>
+              <td align="left" colspan="3">
+               <p style="font-size: 8pt">SECTION 3. CERTIFICATION (Important: Read and sign after completing all form sections.)</p>
+              </td>
+             </tr>
+             <tr>
+              <td align="left" colspan="3">
+               <p style="font-size: 8pt">
+                <xsl:choose>
+                 <xsl:when test="TRI:SubmissionReportingYear = '2006'">
+                      Pursuant to 40 CFR 372.27(a)(1), "I hereby certify that to the best of my knowledge and belief for the
+                      toxic chemical(s) listed in this statement, for this reporting year, the annual reportable amount for each
+                      chemical, as defined in 40 CFR 372.27(a)(1), did not exceed 5,000 pounds, which included no more than 2,000
+                      pounds of total disposal or other releases to the environment, and that the chemical was manufactured,
+                      or processed, or otherwise used in an amount not exceeding 1 million pounds during this reporting
+                      year;" and/or Pursuant to 40 CFR 372.27(a)(2), "I hereby certify that to the best of my knowledge and
+                      belief for the toxic chemical(s) of special concern listed in this statement, there were zero disposals or
+                      other releases to the environment (including disposals or other releases that resulted from catastrophic
+                      events) for this reporting year, the "Annual Reportable Amount of a Chemical of Special Concern"
+                      for each such chemical, as defined in 40 CFR 372.27(a)(2), did not exceed 500 pounds for this
+                      reporting year, and that the chemical was manufactured, or processed, or otherwise used in an
+                      amount not exceeding 1 million pounds during this reporting year."
+                 </xsl:when>
+				 <xsl:when test="TRI:SubmissionReportingYear = '2007'">
+                      Pursuant to 40 CFR 372.27(a)(1), "I hereby certify that to the best of my knowledge and belief for the
+                      toxic chemical(s) listed in this statement, for this reporting year, the annual reportable amount for each
+                      chemical, as defined in 40 CFR 372.27(a)(1), did not exceed 5,000 pounds, which included no more than 2,000
+                      pounds of total disposal or other releases to the environment, and that the chemical was manufactured,
+                      or processed, or otherwise used in an amount not exceeding 1 million pounds during this reporting
+                      year;" and/or Pursuant to 40 CFR 372.27(a)(2), "I hereby certify that to the best of my knowledge and
+                      belief for the toxic chemical(s) of special concern listed in this statement, there were zero disposals or
+                      other releases to the environment (including disposals or other releases that resulted from catastrophic
+                      events) for this reporting year, the "Annual Reportable Amount of a Chemical of Special Concern"
+                      for each such chemical, as defined in 40 CFR 372.27(a)(2), did not exceed 500 pounds for this
+                      reporting year, and that the chemical was manufactured, or processed, or otherwise used in an
+                      amount not exceeding 1 million pounds during this reporting year."
+                 </xsl:when>
+                 <xsl:otherwise>
+				 I hereby certify that to the best of my knowledge and belief, for each toxic chemical listed in the statement,
+				 the annual reportable amount as defined in 40 CFR 372.27 (a), did not exceed 500 pounds for this reporting year
+				 and the chemical was manufactured, processed, or otherwise used in an amount not exceeding 1 million pounds during
+				 this reporting year.
+				 </xsl:otherwise>
+                </xsl:choose>
+               </p>
+               <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt" frame="above">
+                <tr>
+                 <td>
+                  <p style="font-size: 8pt">Name and official title of owner/operator or senior management official:</p>
+                 </td>
+                 <td>
+                  <p style="font-size: 8pt">Signature:</p>
+                 </td>
+                 <td>
+                  <p style="font-size: 8pt">Date Signed: </p>
+                 </td>
+                </tr>
+                <tr>
+                      <td>
+  						<p>
+      						<span class="answerText"><xsl:value-of select="TRI:CertifierName"/>&#160;&#160;&#160;</span>
+      						<span class="answerText"><xsl:value-of select="TRI:CertifierTitleText"/></span>
+  						</p>
+					  </td>
+					  <td>
+    					<p>
+      						<span style="font-size: 9pt; color: red; font-weight: bold;">Reference Copy: Copy of Record Resides in CDX</span>
+    					</p>
+					  </td>
+					  <td>
+     					<span class="answerText">
+					    	<xsl:if test="TRI:CertificationSignedDate != '' and TRI:CertificationSignedDate != '1900-01-01'">
+	                    		<xsl:value-of select="TRI:CertificationSignedDate"/>
+	                   		</xsl:if>
+     					</span>
+					  </td>
+                    </tr>
+               </table>
+               </td>
+             </tr>
+             <tr>
+              <td align="left" colspan="3">
+               <p style="font-size: 8pt">SECTION 4. FACILITY IDENTIFICATION </p>
+              </td>
+             </tr>
+             <tr>
+              <td colspan="3">
+               <table summary="table used for layout purposes" width="100%" cellpadding="1" cellspacing="0" border="1" frame="void" style="font-size: 8pt">
+                <tr>
+                 <td width="5%">4.1</td>
+                 <td colspan="4" width="45%">&#160;</td>
+                 <td colspan="2" width="20%">TRI Facility ID Number</td>
+                 <td colspan="2" width="30%">
+                  <p>
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+                   &#160;</span>
+                  </p>
+                 </td>
+                </tr>
+ 				<xsl:choose>
+                      <xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+	                    <tr>
+	                      <td colspan="5">
+	                        <p style="font-size: 7pt">
+	                          <u style="font-size: 7pt">Facility or Establishment Name</u>
+	                          <br/>
+	                          <span class="answerText">
+	                            <xsl:value-of select="../TRI:Facility/sc:FacilitySiteName"/>
+	                          </span>
+	                        </p>
+	                      </td>
+	                      <td colspan="4">
+	                        <p style="font-size: 7pt">
+	                          <u style="font-size: 7pt">Facility or Establishment Name or Mailing Address(if different from street address)</u>
+	                          <br/>
+	                          <span class="answerText">
+	                            <xsl:value-of select="../TRI:Facility/TRI:MailingFacilitySiteName"/>
+	                          </span>
+	                        </p>
+	                      </td>
+	                    </tr>
+                      </xsl:when>
+                      <xsl:otherwise>
+                        <tr>
+		                  <td colspan="9">
+		                   <p>
+		                    <u style="font-size: 7pt">Facility or Establishment Name</u>
+		                   </p>
+		                   <p>
+		                    <span class="answerText">
+		                     <xsl:value-of select="../TRI:Facility/sc:FacilitySiteName"/>
+		                    &#160;</span>
+		                   </p>
+		                  </td>
+		                </tr>
+                      </xsl:otherwise>
+                </xsl:choose>
+                <tr>
+                 <td colspan="5">
+                  <p>
+                   <u style="font-size: 7pt">Street</u>
+                  </p>
+                  <p>
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:LocationAddressText"/>
+                   &#160;</span>
+                  </p>
+                 </td>
+                 <td colspan="4">
+                  <p>
+                   <u style="font-size: 7pt">Mailing Address (if different from physical street address)</u>
+                  </p>
+                  <p>
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:MailingAddressText"/>
+                   &#160;</span>
+                  </p>
+                 </td>
+                </tr>
+                <tr>
+                 <td colspan="5">
+                  <p>
+                  <xsl:choose>
+                   <xsl:when test="TRI:SubmissionReportingYear >= '2012' ">
+                      <u style="font-size: 7pt">City/County/Tribe/State/ZIP Code</u>
+                      <br/>
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:LocalityName"/>
+                   &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:CountyIdentity/sc:CountyName"/>
+                   &#160;</span>
+                    /
+                   <span class="answerText">
+                     BIA Code: <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:TribalIdentity/sc:TribalCode"/>
+                     &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:StateIdentity/sc:StateName"/>
+                   &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:AddressPostalCode"/>
+                   &#160;</span>
+                   </xsl:when>
+
+                   <xsl:otherwise>
+                     <u style="font-size: 7pt">City/County/State/ZIP Code</u>
+                      <br/>
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:LocalityName"/>
+                   &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:CountyIdentity/sc:CountyName"/>
+                   &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:StateIdentity/sc:StateName"/>
+                   &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/sc:LocationAddress/sc:AddressPostalCode"/>
+                   &#160;</span>
+                   </xsl:otherwise>
+                   </xsl:choose>
+                  </p>
+                 </td>
+                 <td colspan="3">
+                  <p>
+                   <u style="font-size: 7pt">City/State/ZIP Code</u>
+                   <br/>
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:MailingAddressCityName"/>
+                   &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:StateIdentity/sc:StateName"/>
+                   &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:AddressPostalCode"/>
+                   &#160;</span>
+                  </p>
+                 </td>
+                 <td colspan="1" width="15%">
+                  <p>
+                   <u style="font-size: 7pt">Country (Non-US)</u>
+                   <br/>
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/sc:CountryIdentity/sc:CountryName"/>
+                   &#160;</span>
+                   /
+                   <span class="answerText">
+                    <xsl:value-of select="../TRI:Facility/TRI:MailingAddress/TRI:ProvinceNameText"/>
+                   &#160;</span>
+                  </p>
+                 </td>
+                </tr>
+                <tr>
+                 <td width="5%">
+                  <p style="font-size: 8pt">4.2</p>
+                 </td>
+                 <td colspan="4">
+                  <p style="font-size: 8pt">
+                   This report contains information for : (
+                   <u>Important:</u>
+                   check c or d if applicable)
+                  </p>
+                 </td>
+                 <td colspan="2">
+                  c. [
+                  <xsl:choose>
+                   <xsl:when test="TRI:SubmissionFederalFacilityIndicator = 'Y'">
+                    <span class="answerText">X</span>
+                   </xsl:when>
+                  </xsl:choose>
+                  ] A Federal facility
+                 </td>
+                 <td colspan="2">
+                  d. [
+                  <xsl:choose>
+                   <xsl:when test="TRI:SubmissionGOCOFacilityIndicator = 'true'">
+                    <span class="answerText">X</span>
+                   </xsl:when>
+                  </xsl:choose>
+                  ] GOCO
+                 </td>
+                </tr>
+                <tr>
+                 <td width="5%">
+                  <p style="font-size: 8pt">4.3</p>
+                 </td>
+                 <td colspan="2" nowrap="nowrap" align="center">
+                  <p style="font-size: 8pt">Technical Contact name</p>
+                 </td>
+                 <td colspan="2">
+                  <span class="answerText">
+                   <xsl:value-of select="TRI:TechnicalContactNameText/sc:IndividualFullName"/>
+                  &#160;</span>
+                 </td>
+                 <td colspan="2" nowrap="nowrap">
+                  <p>
+                   <u style="font-size: 7pt">Email Address</u>
+                   <br/>
+                   <span class="answerText">
+                    <xsl:value-of select="TRI:TechnicalContactEmailAddressText"/>
+                   &#160;</span>
+                  </p>
+                 </td>
+                 <td colspan="2" nowrap="nowrap">
+                  <p>
+                   <xsl:choose>
+						<xsl:when test="TRI:SubmissionReportingYear &gt; '2013' ">
+							<u style="font-size: 7pt">Telephone Number (include area code and ext.)</u>
+						</xsl:when>
+        				<xsl:otherwise>
+							<u style="font-size: 7pt">Telephone Number (include area code)</u>
+        				</xsl:otherwise>
+					</xsl:choose>
+                   <br/>
+                   <span class="answerText">
+                    <xsl:value-of select="substring(TRI:TechnicalContactPhoneText,1, 3)"/>&#45;<xsl:value-of select="substring(TRI:TechnicalContactPhoneText,4, 3)"/>&#45;<xsl:value-of select="substring(TRI:TechnicalContactPhoneText,7)"/>
+                   &#160;</span>
+                   <xsl:if test="TRI:SubmissionReportingYear &gt; '2013' ">
+                          	 <span class="answerText">
+                            	<xsl:if test="string-length(TRI:TechnicalContactPhoneExtText) &gt; 0 ">
+									&#045; &#160;<xsl:value-of select="TRI:TechnicalContactPhoneExtText"/>
+								</xsl:if>
+                          	&#160;</span>
+                    </xsl:if>
+                  </p>
+                 </td>
+                </tr>
+                <xsl:choose>
+                 <xsl:when test="TRI:SubmissionReportingYear >= '2007' or TRI:SubmissionReportingYear &lt;= '2004'">
+                  <tr>
+                   <td width="5%" style="font-size: 8pt">
+                    <p style="font-size: 8pt">4.4</p>
+                   </td>
+                   <td colspan="2" nowrap="nowrap" align="center">
+                    <p style="font-size: 8pt">Public Contact name </p>
+                   </td>
+                   <td colspan="2">
+                    <span class="answerText">
+                     <xsl:value-of select="TRI:PublicContactNameText"/>
+                    &#160;</span>
+                   </td>
+                   <td colspan="2" nowrap="nowrap">
+                    <p style="font-size: 8pt">
+                     <u style="font-size: 7pt">Email Address</u>
+                     <br/>
+                     <span class="answerText">
+                      <xsl:value-of select="TRI:PublicContactEmailAddressText"/>
+                     &#160;</span>
+                    </p>
+                   </td>
+                   <td colspan="2" nowrap="nowrap">
+                    <p style="font-size: 8pt">
+                   <xsl:choose>
+						<xsl:when test="TRI:SubmissionReportingYear &gt; '2013' ">
+							<u style="font-size: 7pt">Telephone Number (include area code and ext.)</u>
+						</xsl:when>
+        				<xsl:otherwise>
+							<u style="font-size: 7pt">Telephone Number (include area code)</u>
+        				</xsl:otherwise>
+					</xsl:choose>
+                     <br/>
+                     <span class="answerText">
+                     <xsl:if test="string-length(TRI:PublicContactPhoneText)  &gt; 0">
+                      <xsl:value-of select="substring(TRI:PublicContactPhoneText,1, 3)"/>&#45;<xsl:value-of select="substring(TRI:PublicContactPhoneText,4, 3)"/>&#45;<xsl:value-of select="substring(TRI:PublicContactPhoneText,7)"/>
+                      </xsl:if>
+                     &#160;</span>
+                     <xsl:if test="TRI:SubmissionReportingYear &gt; '2013' ">
+                          		 <span class="answerText">
+                            		<xsl:if test="string-length(TRI:PublicContactPhoneExtText) &gt; 0 ">
+										&#045; &#160;<xsl:value-of select="TRI:PublicContactPhoneExtText"/>
+									</xsl:if>
+                          		&#160;</span>
+                     </xsl:if>
+
+                    </p>
+                   </td>
+                  </tr>
+                 </xsl:when>
+                 <xsl:otherwise>
+                  <tr>
+                   <td width="5%">
+                    <p style="font-size: 8pt">4.4</p>
+                   </td>
+                   <td colspan="8">
+                    <p style="font-size: 8pt">Intentionally left blank</p>
+                   </td>
+                  </tr>
+                 </xsl:otherwise>
+                </xsl:choose>
+                <xsl:choose>
+                 <xsl:when test="TRI:SubmissionReportingYear &lt;= '2005'">
+                  <tr>
+                   <td width="5%" style="font-size: 8pt">
+                    <p style="font-size: 8pt">4.5</p>
+                   </td>
+                   <td colspan="2" nowrap="nowrap" width="35%" align="center">
+                    <p style="font-size: 8pt">SIC Code(s) (4 digits)</p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     a.
+                     <xsl:for-each select="../TRI:Facility/TRI:FacilitySIC">
+                      <xsl:choose>
+                       <xsl:when test="sc:SICPrimaryIndicator = 'Primary'">
+                        <span class="answerText">
+                         <xsl:value-of select="sc:SICCode"/>
+                         (Primary)
+                        &#160;</span>
+                       </xsl:when>
+                      </xsl:choose>
+                     </xsl:for-each>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     b.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 1">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[2]/sc:SICCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     c.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 2">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[3]/sc:SICCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     d.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 3">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[4]/sc:SICCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     e.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 4">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[5]/sc:SICCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     f.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilitySIC) > 5">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilitySIC[6]/sc:SICCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                  </tr>
+                 </xsl:when>
+                 <xsl:otherwise>
+                  <tr>
+                   <td width="5%" style="font-size: 8pt">
+                    <p style="font-size: 8pt">4.5</p>
+                   </td>
+                   <td colspan="2" nowrap="nowrap" width="35%" align="center">
+                    <p style="font-size: 8pt">NAICS Code(s) (6 digits)</p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     a.
+                     <xsl:for-each select="../TRI:Facility/TRI:FacilityNAICS">
+                      <xsl:choose>
+                       <xsl:when test="sc:NAICSPrimaryIndicator = 'Primary'">
+                        <span class="answerText">
+                         <xsl:value-of select="sc:NAICSCode"/>
+                         (Primary)
+                        &#160;</span>
+                       </xsl:when>
+                      </xsl:choose>
+                     </xsl:for-each>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     b.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 1">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[2]/sc:NAICSCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     c.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 2">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[3]/sc:NAICSCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     d.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 3">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[4]/sc:NAICSCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     e.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 4">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[5]/sc:NAICSCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                   <td colspan="1" width="10%">
+                    <p style="font-size: 8pt">
+                     f.
+                     <xsl:choose>
+                      <xsl:when test="count(../TRI:Facility/TRI:FacilityNAICS) > 5">
+                       <span class="answerText">
+                        <xsl:value-of select="../TRI:Facility/TRI:FacilityNAICS[6]/sc:NAICSCode"/>
+                       &#160;</span>
+                      </xsl:when>
+                     </xsl:choose>
+                    </p>
+                   </td>
+                  </tr>
+                 </xsl:otherwise>
+                </xsl:choose>
+                <tr>
+                 <td colspan="9">
+                  <table summary="table used for layout purposes" width="100%" cellpadding="1" cellspacing="0" border="1" frame="void" style="font-size: 8pt" rules="all">
+                   <tr>
+                    <td width="5%" style="font-size: 8pt">
+                     <p style="font-size: 8pt">4.7</p>
+                    </td>
+                    <td nowrap="nowrap">
+                     <p style="font-size: 8pt">
+                      Dun and Bradstreet
+                      <br/>
+                      Number(s) (9 digits)
+                     </p>
+                    </td>
+                   </tr>
+                   <tr>
+                    <td colspan="2">
+                     <p style="font-size: 8pt">
+                      a.
+                      <span class="answerText">
+                       <xsl:value-of select="../TRI:Facility/TRI:FacilityDunBradstreetCode[1]"/>
+                      &#160;</span>
+                     </p>
+                    </td>
+                   </tr>
+                   <tr>
+                    <td colspan="2">
+                     <p style="font-size: 8pt">
+                      b.
+                      <span class="answerText">
+                       <xsl:value-of select="../TRI:Facility/TRI:FacilityDunBradstreetCode[2]"/>
+                      &#160;</span>
+                     </p>
+                    </td>
+                   </tr>
+                  </table>
+                 </td>
+                </tr>
+                <tr>
+                 <td align="left" colspan="9">
+                  <p style="font-size: 8pt">SECTION 5. PARENT COMPANY INFORMATION</p>
+                 </td>
+                </tr>
+                <tr>
+                 <td width="5%" style="font-size: 8pt">
+                  <p style="font-size: 8pt">5.1</p>
+                 </td>
+                 <td colspan="2" align="center">
+                  <p style="font-size: 8pt">
+				  <xsl:choose>
+					<xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+					  Name of Parent Company
+					</xsl:when>
+					<xsl:otherwise>
+					  Name of U.S. Parent Company (for TRI Reporting purposes)
+					</xsl:otherwise>
+			       </xsl:choose>
+                  </p>
+                 </td>
+                 <xsl:choose>
+						  <xsl:when test="TRI:SubmissionReportingYear &gt; '2010'">
+						  <td colspan="5">
+                        <span class="answerText">
+                        <xsl:if test="../TRI:Facility/TRI:ParentCompanyNameText != 'NA'">
+                    		<xsl:value-of select="../TRI:Facility/TRI:ParentCompanyNameText"/>
+                   		</xsl:if>
+                        &#160;</span>
+                        <br/>
+                      </td>
+					  <td colspan="1">
+                        <p style="font-size: 8pt">
+						    No U.S. Parent Company (for TRI Reporting purposes) [
+					    <xsl:choose>
+                            <xsl:when test="../TRI:Facility/TRI:ParentCompanyNameNAIndicator = 'true'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ]
+                        </p>
+                      </td>
+						  </xsl:when>
+						  <xsl:otherwise>
+					                       <td colspan="1">
+                        <p style="font-size: 8pt">
+						    NA [
+
+					    <xsl:choose>
+                            <xsl:when test="../TRI:Facility/TRI:ParentCompanyNameNAIndicator = 'true'">
+                              <span class="answerText">X</span>
+                            </xsl:when>
+                          </xsl:choose>
+                          ]
+                        </p>
+                      </td>
+                      <td colspan="5">
+                        <span class="answerText">
+                          <xsl:value-of select="../TRI:Facility/TRI:ParentCompanyNameText"/>
+                        &#160;</span>
+                        <br/>
+                      </td>
+					  	  </xsl:otherwise>
+					  </xsl:choose>
+                </tr>
+                <tr>
+                 <td width="5%" style="font-size: 8pt">
+                  <p style="font-size: 8pt">5.2</p>
+                 </td>
+                 <td colspan="2" align="left">
+                  <p style="font-size: 8pt">Parent Company's Dun &amp; Bradstreet Number </p>
+                 </td>
+                 <td colspan="1">
+                  <p style="font-size: 8pt">
+                   NA [
+                   <xsl:choose>
+                    <xsl:when test="../TRI:Facility/TRI:ParentDunBradstreetCode = 'NA'">
+                     <span class="answerText">X</span>
+                    </xsl:when>
+                   </xsl:choose>
+                   ]
+                  </p>
+                 </td>
+                 <td colspan="5">
+                  <xsl:choose>
+                   <xsl:when test="../TRI:Facility/TRI:ParentDunBradstreetCode != 'NA'">
+                    <span class="answerText">
+                     <xsl:value-of select="../TRI:Facility/TRI:ParentDunBradstreetCode"/>
+                    &#160;</span>
+                   </xsl:when>
+                  </xsl:choose>
+                  <br/>
+                 </td>
+                </tr>
+               </table>
+              </td>
+             </tr>
+            </table>
+           </center>
+           <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="1" style="font-size: 8pt" border="0">
+            <tr>
+             <td width="60%">
+              <p style="font-size: 8pt">
+              	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+               		EPA Form 9350-2 (Rev. <xsl:value-of select="$RevisionDateFormA"/>) - Previous editions are obsolete.
+               	</xsl:if>
+              </p>
+             </td>
+             <td width="30%">
+              <p style="font-size: 8pt">Printed using TRI-MEweb</p>
+             </td>
+            </tr>
+           </table>
+
+           <!-- Start Form A Page Two -->
+          <xsl:for-each select="//TRI:Report[TRI:ReportType/TRI:ReportTypeCode = current()/TRI:ReportType/TRI:ReportTypeCode
+                                                         and concat(TRI:TechnicalContactNameText/sc:IndividualFullName, 'xx') = concat(current()/TRI:TechnicalContactNameText/sc:IndividualFullName, 'xx')
+                                                         and concat(TRI:TechnicalContactPhoneText, 'xx') = concat(current()/TRI:TechnicalContactPhoneText, 'xx')
+                                                         and concat(TRI:TechnicalContactEmailAddressText, 'xx') = concat(current()/TRI:TechnicalContactEmailAddressText, 'xx')
+                                                         and concat(TRI:PublicContactNameText/sc:IndividualFullName, 'xx') = concat(current()/TRI:PublicContactNameText/sc:IndividualFullName, 'xx')
+                                                         and concat(TRI:PublicContactPhoneText, 'xx') = concat(current()/TRI:PublicContactPhoneText, 'xx')
+                                                         and concat(TRI:PublicContactEmailAddressText, 'xx') = concat(current()/TRI:PublicContactEmailAddressText, 'xx')
+                                                         and sc:RevisionIndicator = current()/sc:RevisionIndicator
+                                                         and concat(TRI:ChemicalReportRevisionCode[1], 'xx') = concat(current()/TRI:ChemicalReportRevisionCode[1], 'xx')
+                                                         and concat(TRI:ChemicalReportRevisionCode[2], 'xx') = concat(current()/TRI:ChemicalReportRevisionCode[2], 'xx')
+                                                         and concat(TRI:ChemicalReportWithdrawalCode[1], 'xx') = concat(current()/TRI:ChemicalReportWithdrawalCode[1], 'xx')
+                                                         and concat(TRI:ChemicalReportWithdrawalCode[2], 'xx') = concat(current()/TRI:ChemicalReportWithdrawalCode[2], 'xx')
+                                                         and ../TRI:Facility = current()/../TRI:Facility
+                                                         ]">
+            <xsl:choose>
+            <xsl:when test="(position() - 1) mod 4 = 0">
+           <p style="page-break-before: always">&#160;</p>
+           <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 7pt" border="0">
+            <tr>
+             <td width="60%">
+              <p style="font-size: 8pt">
+               <xsl:call-template name="FormAPage2Links">
+                  <xsl:with-param name="reportID"><xsl:value-of select="$formID"/></xsl:with-param>
+                  <xsl:with-param name="lastPosition"><xsl:value-of select="last()"/></xsl:with-param>
+                  <xsl:with-param name="currentPosition">4</xsl:with-param>
+               </xsl:call-template>
+               	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	               IMPORTANT: Read instructions before completing form; type or use fill-and-print form
+	            </xsl:if>
+              </p>
+             </td>
+             <td width="10%">
+
+             </td>
+            </tr>
+           </table>
+
+           <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt">
+            <tr>
+             <td colspan="2">
+              <table summary="table used for layout purposes" width="100%" style="font-size: 10pt" cellspacing="0" cellpadding="1">
+               <tr>
+                <td width="80%" align="center" style="font-size: 9pt">
+                  <span style="font-weight:bold">EPA FORM A</span>
+                  <br/>
+                  <span style="font-weight:bold">PART II. CHEMICAL IDENTIFICATION</span>
+                  <br/>
+                  <p style="font-size: 8pt">
+                   <xsl:choose>
+                    <xsl:when test="TRI:SubmissionReportingYear = '2005'">
+                        Do not use this form for reporting PBT chemicals including Dioxin and Dioxin-like Compounds*
+                    </xsl:when>
+                    <xsl:otherwise>
+                        Do not use this form for reporting Dioxin and Dioxin-like Compounds*</xsl:otherwise>
+                   </xsl:choose>
+                  </p>
+                </td>
+               </tr>
+              </table>
+             </td>
+             <td>TRI Facility ID Number
+               <hr />
+               <span class="answerText">
+                <xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/>
+               &#160;</span>
+             </td>
+            </tr>
+           </table>
+           </xsl:when>
+           </xsl:choose>
+
+           <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt">
+            <tr>
+             <td colspan="2">
+              <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0" cellpadding="1">
+               <tr>
+                <td align="left" width="75%">
+                 <p style="font-size: 7pt">SECTION 1. TOXIC CHEMICAL IDENTITY</p>
+                </td>
+                <td align="right">
+                 <p style="font-size: 7pt">Report <span class="smallAnswer"><xsl:value-of  select="position()"/></span> of <span class="smallAnswer"><xsl:value-of  select="last()"/></span></p>
+                </td>
+               </tr>
+              </table>
+             </td>
+            </tr>
+              <xsl:for-each select="TRI:ChemicalIdentification">
+               <tr>
+                <td align="center" width="5%">
+                 <p style="font-size: 7pt">1.1</p>
+                </td>
+                <td width="95%" style="font-size: 7pt">
+                  CAS Number (Important: Enter only one number as it appears on the
+                  Section 313 list. Enter category code if reporting a chemical
+                  category.)
+                  <hr/>
+                  <span style="color: blue;text-indent: 5em;font-weight:bold">
+                   <xsl:value-of select="sc:CASNumber"/>
+                  &#160;</span>
+                </td>
+               </tr>
+               <tr>
+                <td align="center" width="5%">
+                 <p style="font-family: arial;font-size: 7pt">1.2</p>
+                </td>
+                <td style="font-size: 7pt">
+                  Toxic Chemical or Chemical Category Name (Important: Enter only one
+                  name exactly as it appears on the Section 313 list.)
+                  <hr/>
+                  <span style="color: blue;font-size: 7pt;text-indent: 5em;font-weight:bold">
+                   <xsl:value-of select="TRI:ChemicalNameText"/>
+                  &#160;</span>
+                </td>
+               </tr>
+              </xsl:for-each>
+              <tr>
+               <td align="center" width="5%">
+                <p style=" font-family: arial;font-size: 7pt">1.3</p>
+               </td>
+               <td style="font-size: 7pt">
+                 Generic Chemical Name (Important: Complete only if Part I, Section
+                 2.1 is checked "Yes". Generic Name must be structurally descriptive).
+                 <hr/>
+                 <span style="color: blue;font-size: 7pt;text-indent: 5em;font-weight:bold">NA</span>
+               </td>
+              </tr>
+              <tr>
+               <td colspan="2">
+                <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" cellspacing="0"
+                       cellpadding="1">
+                 <tr>
+                  <td align="left" colspan="2">
+                   <p style="font-family: arial;font-size: 8pt">
+                      SECTION 2. MIXTURE COMPONENT IDENTITY (Important: DO NOT complete this section if you completed Section 1.)
+                   </p>
+                  </td>
+                 </tr>
+                </table>
+               </td>
+              </tr>
+              <tr>
+               <td align="center" width="5%">
+                <p style="font-family: arial;font-size: 7pt">2.1</p>
+               </td>
+               <td style="font-size: 8pt">
+                 Generic Chemical Name Provided by Supplier (Important: Maximum of 70
+                 characters, including numbers, spaces, and punctuation.)
+                 <hr/>
+                 <b style="color: blue;font-size: 9pt; font-family:arial">
+                  <xsl:value-of select="TRI:ChemicalIdentification/TRI:ChemicalMixtureNameText"/>
+                 </b>
+                 <br/>
+               </td>
+              </tr>
+             </table>
+             <br />
+        <xsl:choose>
+        <xsl:when test="((position() mod 4 = 0) or (position() = last()))">
+
+               <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 7pt" border="0">
+                <tr>
+                 <td colspan="2" align="center">
+                  <p style="font-family: arial;font-size: 7pt">
+                   <xsl:choose>
+                    <xsl:when test="TRI:SubmissionReportingYear = '2005'">
+                        *See the TRI Reporting Forms and Instructions Manual for the list of PBT
+                         Chemicals(including Dioxin and Dioxin-like Compounds)
+                    </xsl:when>
+                    <xsl:otherwise>*See the TRI Reporting Forms and Instructions
+                                   Manual for the TRI-listed Dioxin and Dioxin-like
+                                   Compounds</xsl:otherwise>
+                   </xsl:choose>
+                  </p>
+                 </td>
+                </tr>
+                <tr>
+                 <td width="60%">
+                  <p style="font-family: arial;font-size: 7pt">
+                  	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+                   		EPA Form 9350-2 (Rev. <xsl:value-of select="$RevisionDateFormA"/>) - Previous editions are obsolete.
+                   	</xsl:if>
+                  </p>
+                 </td>
+                 <td width="40%" align="right" style="font-size: 7pt">
+                  <p style="font-family: arial;font-size: 7pt">&#160;</p>
+                 </td>
+                </tr>
+               </table>
+            </xsl:when>
+          </xsl:choose>
+           <!-- End Form A Page Two -->
+           </xsl:for-each>
+        </xsl:if>
+      </xsl:otherwise>
+      </xsl:choose>
+      </xsl:for-each>
+      </body>
+    </html>
+  </xsl:template>
+
+  <xsl:template name="ScheduleOnePageOne">
+    <xsl:param name="baseStreamID" />
+    <xsl:param name="formID" />
+
+    <xsl:param name="OMBNumberSchedule1" />
+    <xsl:param name="ApprovalDateSchedule1" />
+
+    <xsl:param name="fugitiveRelease" select="TRI:OnsiteReleaseQuantity[TRI:EnvironmentalMediumCode = 'AIR FUG' and $baseStreamID = 0]" />
+    <xsl:param name="stackRelease" select="TRI:OnsiteReleaseQuantity[TRI:EnvironmentalMediumCode = 'AIR STACK' and $baseStreamID = 0]" />
+    <xsl:param name="firstStreamRelease" select="TRI:OnsiteReleaseQuantity[TRI:WaterStream/TRI:WaterSequenceNumber = $baseStreamID + 1]" />
+    <xsl:param name="secondStreamRelease" select="TRI:OnsiteReleaseQuantity[TRI:WaterStream/TRI:WaterSequenceNumber = $baseStreamID + 2]" />
+    <xsl:param name="thirdStreamRelease" select="TRI:OnsiteReleaseQuantity[TRI:WaterStream/TRI:WaterSequenceNumber = $baseStreamID + 3]" />
+
+    <div class="landscapeArea">
+        <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 8pt" border="0">
+              <tr>
+                <td width="30%">
+                	<xsl:if test="TRI:SubmissionReportingYear &lt; '2014' ">
+	                  Form Approved OMB Number:<span class="smallAnswer"><xsl:value-of select="$OMBNumberSchedule1" />&#160;</span><br />
+    	              Approval Expires: <span class="smallAnswer"><xsl:value-of select="$ApprovalDateSchedule1" />&#160;</span>
+    	            </xsl:if>
+                </td>
+                <td width="10%">
+                  <p style="font-size: 8pt"><b>Page 1 of 4</b></p>
+                </td>
+              </tr>
+            </table>
+
+          <center>
+            <table summary="table used for layout purposes" border="1" cellspacing="0" cellpadding="1" width="100%" style="font-size: 8pt;">
+
+              <tr>
+                <td colspan="13" align="center">
+                  <table summary="table used for layout purposes" width="100%" style="font-size: 8pt" border="0" cellspacing="0" cellpadding="0" frame="void">
+                    <tr>
+                      <td style="font-size: 10pt"><b> EPA </b></td>
+                      <td align="center" style="font-size: 14pt"><b>FORM R Schedule 1</b></td>
+                      <td><p style="font-size: 8pt">TRI Facility ID Number:</p></td>
+                    </tr>
+                    <tr>
+                      <td><p style="font-size: 8pt">United States<br />Environmental Protection<br />Agency</p></td>
+                      <td align="center"><p style="font-size: 14pt"><b>PART II.  CHEMICAL-SPECIFIC INFORMATION (continued)</b></p></td>
+                      <td class="answerText"><xsl:value-of select="../TRI:Facility/TRI:FacilityIdentifier"/></td>
+                    </tr>
+                  </table>
+                </td>
+              </tr>
+
+              <tr>
+                <td align="left" colspan="13" style="font-size: 8pt">
+                  <p style="font-size: 9pt"><b>Section 5. Quantity Of Dioxin And Dioxin-Like Compounds Entering Each Environmental Medium On-site</b></p>
+                </td>
+              </tr>
+
+              <tr>
+                <td colspan="2" rowspan="2" style="background-color: gray">&#160;</td>
+                <td align="center" style="font-size: 8pt"><b>5.1</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="$fugitiveRelease/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+                    X
+                  </xsl:if>&#160;
+                </td>
+
+                <td align="center" style="font-size: 8pt"><b>5.2</b></td>
+                <td align="center" style="font-size: 8pt">NA</td>
+                <td align="center" class="smallAnswer">
+                  <xsl:if test="$stackRelease/TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+                    X
+                  </xsl:if>&#160;
+                </td>
+
+                <td align="center" colspan="5" style="font-size: 8pt">
+                  <b>5.3</b>&#160;&#160;&#160;Discharges to receiving streams or water
+                  bodies&#160;&#160;&#160;&#160;&#160;&#160;
+				  <xsl:choose>
+					<xsl:when test="TRI:SubmissionReportingYear &lt; '2011'">
+					  &#160;
+					</xsl:when>
+					<xsl:otherwise>
+					  NA&#160;&#160;&#160;
+                  [&#160;<xsl:for-each select="TRI:OnsiteReleaseQuantity">
+					  <xsl:choose>
+					    <xsl:when test="TRI:EnvironmentalMediumCode = 'WATER'">
+					      <xsl:choose>
+					        <xsl:when test="TRI:OnsiteWasteQuantity/TRI:WasteQuantityNAIndicator = 'true'">
+					          <span class="smallAnswer">X</span>
+					        </xsl:when>
+					      </xsl:choose>
+					    </xsl:when>
+					  </xsl:choose>
+					</xsl:for-each>&#160;]
+					</xsl:otherwise>
+				  </xsl:choose>
+                </td>
+              </tr>
+              <tr>
+                <td align="center" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Fugitive or non-point air emissions</p>
+                </td>
+
+                <td align="center" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">Stack or point air emissions</p>
+                </td>
+
+                <td align="center" colspan="3" style="font-size: 8pt">
+                  <p style="font-size: 8pt">5.3.<xsl:value-of select="$baseStreamID + 1" />&#160;
+                    <xsl:value-of select="$firstStreamRelease/TRI:WaterStream/TRI:StreamName" />
+                  </p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">5.3.<xsl:value-of select="$baseStreamID + 2" />&#160;
+                    <xsl:value-of select="$secondStreamRelease/TRI:WaterStream/TRI:StreamName" />
+                  </p>
+                </td>
+                <td align="center" style="font-size: 8pt">
+                  <p style="font-size: 8pt">5.3.<xsl:value-of select="$baseStreamID + 3" />&#160;
+                    <xsl:value-of select="$thirdStreamRelease/TRI:WaterStream/TRI:StreamName" />
+                  </p>
+                </td>
+              </tr>
+
+            <xsl:call-template name="ScheduleOnePageOneRow">
+              <xsl:with-param name="baseStreamID"><xsl:value-of select="$baseStreamID" /></xsl:with-param>
+            </xsl:call-template>
+
+              <tr>
+                <td align="left" colspan="13" style="font-size: 8pt">
+                  <p style="font-size: 8pt">
+                    If additional pages of Section 6.1 or 6.2 are attached, indicate the total number of pages in this box&#160;&#160;
+                    <span style="border: 1px solid black; padding: 2px; text-align:center; width: 25px;">
+                      <xsl:if test="count(TRI:OnsiteReleaseQuantity/TRI:WaterStream) &gt; 3">
+                          <span class="answerText"><xsl:value-of select="(floor(count(TRI:OnsiteReleaseQuantity/TRI:WaterStream) div 3)) + 1" />&#160;</span>
+                      </xsl:if>&#160;
+                    &#160;</span>
+                    <br />
+                    and indicate the Section 6.1 or 6.2 page number in this box&#160;&#160;
+                    <span style="border: 1px solid black; padding: 2px; text-align:center; width: 25px;">
+                      <xsl:if test="count(TRI:OnsiteReleaseQuantity/TRI:WaterStream) &gt; 3">
+                          <span class="answerText"><xsl:value-of select="($baseStreamID div 3) + 1" />&#160;</span>
+                      </xsl:if>&#160;
+                    &#160;</span>&#160;
+                    (Example: 1,2,3, etc.)
+                  </p>
+                </td>
+              </tr>
+
+            </table>
+          </center>
+
+          <table summary="table used for layout purposes" width="100%" cellspacing="0" cellpadding="0" style="font-size: 7pt" border="0">
+            <tr>
+              <td width="60%">
+                <p style="font-size: 8pt">
+                  EPA Form 9350-3
+                </p>
+              </td>
+              <td width="30%">
+                <p style="font-size: 8pt">Printed using TRI-MEweb</p>
+              </td>
+            </tr>
+          </table>
+          </div>
+    </xsl:template>
+
+    <xsl:template name="ScheduleOnePageOneRow">
+        <xsl:param name="baseStreamID" />
+        <xsl:param name="i">1</xsl:param>
+        <xsl:param name="teqNodeName"><xsl:value-of select="concat('TRI:ToxicEquivalency',$i,'Value')" /></xsl:param>
+        <xsl:param name="fugitiveTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'AIR FUG' and $baseStreamID = 0]" />
+        <xsl:param name="stackTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'AIR STACK' and $baseStreamID = 0]" />
+        <xsl:param name="firstStreamTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:WaterStream/TRI:WaterSequenceNumber = $baseStreamID + 1]" />
+        <xsl:param name="secondStreamTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:WaterStream/TRI:WaterSequenceNumber = $baseStreamID + 2]" />
+        <xsl:param name="thirdStreamTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:WaterStream/TRI:WaterSequenceNumber = $baseStreamID + 3]" />
+
+        <xsl:if test="$i &lt; 18">
+        <tr>
+          <xsl:if test="$i = 1">
+            <td align="center" rowspan="17" style="font-size: 8pt">
+              <p style="font-size: 8pt"><b>D. Mass<br />(grams)<br />of<br />each<br />compound<br />in<br />the<br />category<br />(1-17)</b></p>
+            </td>
+          </xsl:if>
+
+            <td align="center" style="font-size: 8pt">
+              <xsl:value-of select="$i" />
+            </td>
+            <td align="center" colspan="3" class="teqAnswer">
+                <xsl:value-of select="$fugitiveTEQ/*[name() = $teqNodeName]" /><br />
+            </td>
+            <td align="center" colspan="3" class="teqAnswer">
+                <xsl:value-of select="$stackTEQ/*[name() = $teqNodeName]" /><br />
+            </td>
+            <td align="center" colspan="3" class="teqAnswer">
+                <xsl:value-of select="$firstStreamTEQ/*[name() = $teqNodeName]" /><br />
+            </td>
+            <td align="center" class="teqAnswer">
+                <xsl:value-of select="$secondStreamTEQ/*[name() = $teqNodeName]" /><br />
+            </td>
+            <td align="center" class="teqAnswer">
+                <xsl:value-of select="$thirdStreamTEQ/*[name() = $teqNodeName]" /><br />
+            </td>
+          </tr>
+
+          <xsl:call-template name="ScheduleOnePageOneRow">
+              <xsl:with-param name="i"><xsl:value-of select="$i + 1" /></xsl:with-param>
+              <xsl:with-param name="baseStreamID"><xsl:value-of select="$baseStreamID" /></xsl:with-param>
+          </xsl:call-template>
+        </xsl:if>
+    </xsl:template>
+
+    <xsl:template name="ScheduleOnePageTwoRow">
+        <xsl:param name="i">1</xsl:param>
+        <xsl:param name="teqNodeName"><xsl:value-of select="concat('TRI:ToxicEquivalency',$i,'Value')" /></xsl:param>
+        <xsl:param name="uicClass1TEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'UNINJ I']" />
+        <xsl:param name="uicClass25TEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'UNINJ IIV']" />
+        <xsl:param name="rcraLandfillTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'RCRA C']" />
+        <xsl:param name="otherLandfillTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'OTH LANDF']" />
+        <xsl:param name="farmingTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'LAND TREA']" />
+        <xsl:param name="rcraSITEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'SI 5.5.3A']" />
+        <xsl:param name="otherSITEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'SI 5.5.3B']" />
+        <xsl:param name="otherTEQ" select="TRI:OnsiteReleaseQuantity/TRI:OnsiteWasteQuantity/TRI:ToxicEquivalencyIdentification[../../TRI:EnvironmentalMediumCode = 'OTH DISP']" />
+
+        <xsl:if test="$i &lt; 18">
+            <tr>
+              <xsl:if test="$i = 1">
+              <td align="center" rowspan="17" style="font-size: 8pt">
+                <b>C. Mass<br />(grams)<br />of<br />each<br />compound<br />in<br />the<br />category<br />(1-17)</b>
+              </td>
+              </xsl:if>
+              <td align="center" style="font-size: 8pt">
+                <xsl:value-of select="$i" />
+              </td>
+              <td colspan="3" align="center" class="teqAnswer">
+                <xsl:value-of select="$uicClass1TEQ/*[name() = $teqNodeName]" /><br />
+              </td>
+              <td colspan="3" align="center" class="teqAnswer">
+                <xsl:value-of select="$uicClass25TEQ/*[name() = $teqNodeName]" /><br />
+              </td>
+              <td colspan="3" align="center" class="teqAnswer">
+                <xsl:value-of select="$rcraLandfillTEQ/*[name() = $teqNodeName]" /><br />
+              </td>
+              <td colspan="3" align="center" class="teqAnswer">
+                <xsl:value-of select="$otherLandfillTEQ/*[name() = $teqNodeName]" /><br />
+              </td>
+              <td colspan="3" align="center" class="teqAnswer">
+                <xsl:value-of select="$farmingTEQ/*[name() = $teqNodeName]" /><br />
+              </td>
+              <td colspan="3" align="center" class="teqAnswer">
+                <xsl:value-of select="$rcraSITEQ/*[name() = $teqNodeName]" /><br />
+              </td>
+              <td colspan="3" align="center" class="teqAnswer">
+                <xsl:value-of select="$otherSITEQ/*[name() = $teqNodeName]" /><br />
+              </td>
+              <td colspan="3" align="center" class="teqAnswer">
+                <xsl:value-of select="$otherTEQ/*[name() = $teqNodeName]" /><br />
+              </td>
+            </tr>
+
+            <xsl:call-template name="ScheduleOnePageTwoRow">
+              <xsl:with-param name="i"><xsl:value-of select="$i + 1" /></xsl:with-param>
+            </xsl:call-template>
+        </xsl:if>
+    </xsl:template>
+
+    <xsl:template name="ScheduleOnePageThreeRowBlank">
+        <xsl:param name="i">1</xsl:param>
+
+        <tr>
+          <td colspan="2" align="left" style="font-size: 9pt"><b>6.2_<xsl:value-of select="$i" /></b></td>
+          <td colspan="16" align="left" style="font-size: 8pt"><b>. Mass (grams) of each compound in the Category (1-17)</b></td>
+        </tr>
+
+        <xsl:call-template name="ScheduleOnePageThreeDetailBlank"><xsl:with-param name="j">1</xsl:with-param></xsl:call-template>
+        <xsl:call-template name="ScheduleOnePageThreeDetailBlank"><xsl:with-param name="j">2</xsl:with-param></xsl:call-template>
+        <xsl:call-template name="ScheduleOnePageThreeDetailBlank"><xsl:with-param name="j">3</xsl:with-param></xsl:call-template>
+        <xsl:call-template name="ScheduleOnePageThreeDetailBlank"><xsl:with-param name="j">4</xsl:with-param></xsl:call-template>
+    </xsl:template>
+
+    <xsl:template name="ScheduleOnePageThreeDetailBlank">
+        <xsl:param name="j">1</xsl:param>
+
+        <tr>
+          <td align="center" colspan="2" style="font-size: 8pt">
+              <b><xsl:value-of select="$j" />.</b>
+          </td>
+          <td style="font-size: 8pt">1</td><td>&#160;</td>
+          <td style="font-size: 8pt">2</td><td>&#160;</td>
+          <td style="font-size: 8pt">3</td><td>&#160;</td>
+          <td style="font-size: 8pt">4</td><td>&#160;</td>
+          <td style="font-size: 8pt">5</td><td>&#160;</td>
+          <td style="font-size: 8pt">6</td><td>&#160;</td>
+          <td style="font-size: 8pt">7</td><td>&#160;</td>
+          <td style="font-size: 8pt">8</td><td>&#160;</td>
+        </tr>
+        <tr>
+          <td style="font-size: 8pt">9</td><td>&#160;</td>
+          <td style="font-size: 8pt">10</td><td>&#160;</td>
+          <td style="font-size: 8pt">11</td><td>&#160;</td>
+          <td style="font-size: 8pt">12</td><td>&#160;</td>
+          <td style="font-size: 8pt">13</td><td>&#160;</td>
+          <td style="font-size: 8pt">14</td><td>&#160;</td>
+          <td style="font-size: 8pt">15</td><td>&#160;</td>
+          <td style="font-size: 8pt">16</td><td>&#160;</td>
+          <td style="font-size: 8pt">17</td><td>&#160;</td>
+        </tr>
+    </xsl:template>
+
+    <xsl:template name="ScheduleOnePageThreeRow">
+        <tr>
+          <td align="center" colspan="2" style="font-size: 8pt">
+              <b><xsl:value-of select="TRI:TransferSequenceNumber + 1" />.</b>
+          </td>
+          <td style="font-size: 8pt">1</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency1Value" />&#160;</td>
+
+          <td style="font-size: 8pt">2</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency2Value" />&#160;</td>
+
+          <td style="font-size: 8pt">3</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency3Value" />&#160;</td>
+
+          <td style="font-size: 8pt">4</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency4Value" />&#160;</td>
+
+          <td style="font-size: 8pt">5</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency5Value" />&#160;</td>
+
+          <td style="font-size: 8pt">6</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency6Value" />&#160;</td>
+
+          <td style="font-size: 8pt">7</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency7Value" />&#160;</td>
+
+          <td style="font-size: 8pt">8</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency8Value" />&#160;</td>
+        </tr>
+
+        <tr>
+          <td style="font-size: 8pt">9</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency9Value" />&#160;</td>
+
+          <td style="font-size: 8pt">10</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency10Value" />&#160;</td>
+
+          <td style="font-size: 8pt">11</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency11Value" />&#160;</td>
+
+          <td style="font-size: 8pt">12</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency12Value" />&#160;</td>
+
+          <td style="font-size: 8pt">13</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency13Value" />&#160;</td>
+
+          <td style="font-size: 8pt">14</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency14Value" />&#160;</td>
+
+          <td style="font-size: 8pt">15</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency15Value" />&#160;</td>
+
+          <td style="font-size: 8pt">16</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency16Value" />&#160;</td>
+
+          <td style="font-size: 8pt">17</td>
+          <td align="center" class="teqAnswer"><xsl:value-of select="TRI:TransferWasteQuantity/TRI:ToxicEquivalencyIdentification/TRI:ToxicEquivalency17Value" />&#160;</td>
+        </tr>
+    </xsl:template>
+
+    <xsl:template name="ScheduleOnePageFourRow">
+      <xsl:param name="i">1</xsl:param>
+      <xsl:param name="teqNodeName"><xsl:value-of select="concat('TRI:ToxicEquivalency',$i,'Value')" /></xsl:param>
+
+      <xsl:if test="$i &lt; 18">
+        <tr>
+          <xsl:if test="$i = 1">
+          <td rowspan="17" align="center" style="font-size: 8pt">
+            <b>F. Mass<br />(grams)<br />of<br />each<br />compound<br />in<br />the<br />category<br />(1-17)</b>
+          </td>
+          </xsl:if>
+
+          <td align="center" style="font-size: 8pt"><xsl:value-of select="$i" /></td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OnsiteUICDisposalQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OnsiteOtherDisposalQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OffsiteUICDisposalQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OffsiteOtherDisposalQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OnsiteEnergyRecoveryQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OffsiteEnergyRecoveryQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OnsiteRecycledQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OffsiteRecycledQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OnsiteTreatedQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:OffsiteTreatedQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+          <td align="center" class="teqAnswer">
+            <xsl:value-of select="TRI:SourceReductionQuantity/TRI:ToxicEquivalencyIdentification/*[name() = $teqNodeName]" /><br />
+          </td>
+        </tr>
+
+        <xsl:call-template name="ScheduleOnePageFourRow">
+          <xsl:with-param name="i"><xsl:value-of select="$i + 1" /></xsl:with-param>
+        </xsl:call-template>
+
+      </xsl:if>
+    </xsl:template>
+
+    <xsl:template name="FormAPage2Links">
+      <xsl:param name="lastPosition">0</xsl:param>
+      <xsl:param name="currentPosition">0</xsl:param>
+      <xsl:param name="reportID">0</xsl:param>
+      <xsl:if test="$currentPosition &lt;= $lastPosition and $lastPosition &gt; 4">
+          <xsl:call-template name="FormAPage2Links">
+            <xsl:with-param name="lastPosition"><xsl:value-of select="$lastPosition"/></xsl:with-param>
+            <xsl:with-param name="currentPosition"><xsl:value-of select="$currentPosition + 1"/></xsl:with-param>
+            <xsl:with-param name="reportID"><xsl:value-of select="$reportID"/></xsl:with-param>
+          </xsl:call-template>
+      </xsl:if>
+    </xsl:template>
+</xsl:stylesheet>
diff --git a/jdk/test/javax/xml/jaxp/transform/8169112/TransformerTest.java b/jdk/test/javax/xml/jaxp/transform/8169112/TransformerTest.java
new file mode 100644
index 0000000..6b913e5
--- /dev/null
+++ b/jdk/test/javax/xml/jaxp/transform/8169112/TransformerTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8169112
+ * @summary Test compilation of large xsl file with outlining.
+ * @run testng/othervm TransformerTest
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileNotFoundException;
+
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+import org.testng.annotations.Test;
+
+public class TransformerTest {
+
+     /**
+     * @bug 8169112
+     * @summary Test compilation of large xsl file with outlining.
+     *
+     * This test merely compiles a large xsl file and tests if its bytecode
+     * passes verification by invoking the transform() method for
+     * dummy content. The test succeeds if no Exception is thrown
+     */
+    @Test
+    public final void testBug8169112() throws FileNotFoundException,
+        TransformerException
+    {
+        TransformerFactory tf = TransformerFactory.newInstance();
+        String xslFile = getClass().getResource("Bug8169112.xsl").toString();
+        Transformer t = tf.newTransformer(new StreamSource(xslFile));
+        String xmlIn = "<?xml version=\"1.0\"?><DOCROOT/>";
+        ByteArrayInputStream bis = new ByteArrayInputStream(xmlIn.getBytes());
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        t.transform(new StreamSource(bis), new StreamResult(bos));
+    }
+}
diff --git a/jdk/test/javax/xml/ws/publish/WSTest.java b/jdk/test/javax/xml/ws/publish/WSTest.java
new file mode 100644
index 0000000..539f2d4
--- /dev/null
+++ b/jdk/test/javax/xml/ws/publish/WSTest.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8146086
+ * @summary Publishing two webservices on same port fails with "java.net.BindException: Address already in use"
+ * @run main/othervm WSTest
+ */
+import javax.jws.WebMethod;
+import javax.jws.WebService;
+import javax.xml.ws.Endpoint;
+import java.net.ServerSocket;
+
+public class WSTest {
+
+    @WebService(targetNamespace = "test")
+    public static class Method1 {
+        @WebMethod
+        public String getMethod1Value() {
+            return "from Method1";
+        }
+    }
+
+    @WebService(targetNamespace = "test")
+    public static class Method2 {
+        @WebMethod
+        public String getMethod2Value() {
+            return "from Method2";
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        // find a free port
+        ServerSocket ss = new ServerSocket(0);
+        int port = ss.getLocalPort();
+        ss.close();
+
+        Endpoint endPoint1 = null;
+        Endpoint endPoint2 = null;
+        try {
+            endPoint1 = Endpoint.publish("http://0.0.0.0:" + port + "/method1",
+                    new Method1());
+            endPoint2 = Endpoint.publish("http://0.0.0.0:" + port + "/method2",
+                    new Method2());
+
+            System.out.println("Sleep 3 secs...");
+
+            Thread.sleep(3000);
+        } finally {
+            stop(endPoint2);
+            stop(endPoint1);
+        }
+    }
+
+    private static void stop(Endpoint endPoint) {
+        if (endPoint == null) return;
+
+        try {
+            endPoint.stop();
+        } catch (Throwable ignored) {
+        }
+    }
+
+}
diff --git a/jdk/test/sun/net/ftp/TestFtpClientNameListWithNull.java b/jdk/test/sun/net/ftp/TestFtpClientNameListWithNull.java
new file mode 100644
index 0000000..7a142f6
--- /dev/null
+++ b/jdk/test/sun/net/ftp/TestFtpClientNameListWithNull.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8022580
+ * @summary "null" should be treated as "current directory" in nameList()
+ * method of FtpClient
+ * @modules java.base/sun.net.ftp
+ * @run main TestFtpClientNameListWithNull
+*/
+
+
+import sun.net.ftp.FtpClient;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketException;
+
+
+public class TestFtpClientNameListWithNull {
+
+    private static volatile boolean commandHasArgs;
+
+    public static void main(String[] args) throws Exception {
+        try (FtpServer server = new FtpServer();
+             FtpClient client = FtpClient.create()) {
+            (new Thread(server)).start();
+            int port = server.getPort();
+            client.connect(new InetSocketAddress("localhost", port));
+            client.nameList(null);
+        } finally {
+            if (commandHasArgs) {
+                throw new RuntimeException("Test failed. NLST shouldn't have " +
+                        "args if nameList parameter is null");
+            }
+        }
+    }
+
+    private static class FtpServer implements AutoCloseable, Runnable {
+        private final ServerSocket serverSocket;
+
+        FtpServer() throws IOException {
+            serverSocket = new ServerSocket(0);
+        }
+
+        public void handleClient(Socket client) throws IOException {
+            boolean done = false;
+            String str;
+
+            client.setSoTimeout(2000);
+            BufferedReader in = new BufferedReader(new InputStreamReader(client.
+                    getInputStream()));
+            PrintWriter out = new PrintWriter(client.getOutputStream(), true);
+            out.println("220 FTP serverSocket is ready.");
+            while (!done) {
+                try {
+                    str = in.readLine();
+                } catch (SocketException e) {
+                    done = true;
+                    continue;
+                }
+                String cmd = str.substring(0, str.indexOf(" ") > 0 ?
+                        str.indexOf(" ") : str.length());
+                String args = (cmd.equals(str)) ?
+                        "" : str.substring(str.indexOf(" "));
+                switch (cmd) {
+                    case "QUIT":
+                        out.println("221 Goodbye.");
+                        out.flush();
+                        done = true;
+                        break;
+                    case "EPSV":
+                        if ("all".equalsIgnoreCase(args)) {
+                            out.println("200 EPSV ALL command successful.");
+                            continue;
+                        }
+                        out.println("229 Entering Extended Passive Mode " +
+                                "(|||" + getPort() + "|)");
+                        break;
+                    case "NLST":
+                        if (args.trim().length() != 0) {
+                            commandHasArgs = true;
+                        }
+                        out.println("200 Command okay.");
+                        break;
+                    default:
+                        out.println("500 unsupported command: " + str);
+                }
+            }
+        }
+
+        public int getPort() {
+            if (serverSocket != null) {
+                return serverSocket.getLocalPort();
+            }
+            return 0;
+        }
+
+        public void close() throws IOException {
+            if (serverSocket != null && !serverSocket.isClosed()) {
+                serverSocket.close();
+            }
+        }
+
+        @Override
+        public void run() {
+            try {
+                try (Socket client = serverSocket.accept()) {
+                    handleClient(client);
+                }
+            } catch (IOException e) {
+                throw new RuntimeException("Problem in test execution", e);
+            }
+        }
+    }
+}
diff --git a/jdk/test/sun/net/www/protocol/jar/JarURLConnectionUseCaches.java b/jdk/test/sun/net/www/protocol/jar/JarURLConnectionUseCaches.java
new file mode 100644
index 0000000..433a72c
--- /dev/null
+++ b/jdk/test/sun/net/www/protocol/jar/JarURLConnectionUseCaches.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 6947916
+ * @summary  JarURLConnection does not handle useCaches correctly
+ * @run main/othervm JarURLConnectionUseCaches
+ */
+
+import java.io.*;
+import java.net.JarURLConnection;
+import java.net.URL;
+import java.util.jar.*;
+
+public class JarURLConnectionUseCaches {
+    public static void main( String[] args ) throws IOException {
+        JarOutputStream out = new JarOutputStream(
+                new FileOutputStream("usecache.jar"));
+        out.putNextEntry(new JarEntry("test.txt"));
+        out.write("Test txt file".getBytes());
+        out.closeEntry();
+        out.close();
+
+        URL url = new URL("jar:"
+            + new File(".").toURI().toString()
+            + "/usecache.jar!/test.txt");
+
+        JarURLConnection c1 = (JarURLConnection)url.openConnection();
+        c1.setDefaultUseCaches( false );
+        c1.setUseCaches( true );
+        c1.connect();
+
+        JarURLConnection c2 = (JarURLConnection)url.openConnection();
+        c2.setDefaultUseCaches( false );
+        c2.setUseCaches( true );
+        c2.connect();
+
+        c1.getInputStream().close();
+        c2.getInputStream().read();
+        c2.getInputStream().close();
+    }
+}
diff --git a/jdk/test/sun/security/krb5/auto/CommMatcher.java b/jdk/test/sun/security/krb5/auto/CommMatcher.java
new file mode 100644
index 0000000..1cfe25a
--- /dev/null
+++ b/jdk/test/sun/security/krb5/auto/CommMatcher.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Matches the krb5 debug output:
+ * >>> KDCCommunication: kdc=host UDP:11555, timeout=100,Attempt =1, #bytes=138
+ *
+ * Example:
+ *   CommMatcher cm = new CommMatcher();
+ *   cm.addPort(12345).addPort(23456);
+ *   for (String line : debugOutput) {
+ *       if (cm.match(line)) {
+ *           println("KDC: %c, %s, Timeout: %d\n",
+ *              cm.kdc(), cm.protocol(), cm.timeout());
+ *       }
+ *   }
+ */
+public class CommMatcher {
+
+    static final Pattern re = Pattern.compile(
+            ">>> KDCCommunication: kdc=\\S+ (TCP|UDP):(\\d+), " +
+                    "timeout=(\\d+),Attempt\\s*=(\\d+)");
+
+    List<Integer> kdcPorts = new ArrayList<>();
+    Matcher matcher;
+
+    /**
+     * Add KDC ports one by one. The 1st KDC will be 'a' in {@link #kdc()},
+     * 2nd is 'b', etc, etc.
+     */
+    public CommMatcher addPort(int port) {
+        if (port > 0) {
+            kdcPorts.add(port);
+        } else {
+            kdcPorts.clear();
+        }
+        return this;
+    }
+
+    public boolean match(String line) {
+        matcher = re.matcher(line);
+        return matcher.find();
+    }
+
+    public String protocol() {
+        return matcher.group(1);
+    }
+
+    public char kdc() {
+        int port = Integer.parseInt(matcher.group(2));
+        return (char)(kdcPorts.indexOf(port) + 'a');
+    }
+
+    public int timeout() {
+        return BadKdc.toSymbolicSec(Integer.parseInt(matcher.group(3)));
+    }
+
+    public int attempt() {
+        return Integer.parseInt(matcher.group(4));
+    }
+}
diff --git a/jdk/test/sun/security/krb5/auto/MaxRetries.java b/jdk/test/sun/security/krb5/auto/MaxRetries.java
index 880c023..2de3817 100644
--- a/jdk/test/sun/security/krb5/auto/MaxRetries.java
+++ b/jdk/test/sun/security/krb5/auto/MaxRetries.java
@@ -29,49 +29,94 @@
  * @summary support max_retries in krb5.conf
  */
 
+import javax.security.auth.login.LoginException;
 import java.io.*;
 import java.net.DatagramSocket;
 import java.security.Security;
 
 public class MaxRetries {
+
+    static int idlePort = -1;
+    static CommMatcher cm = new CommMatcher();
+
     public static void main(String[] args)
             throws Exception {
 
         System.setProperty("sun.security.krb5.debug", "true");
-        new OneKDC(null).writeJAASConf();
+        OneKDC kdc = new OneKDC(null).writeJAASConf();
 
-        // An idle UDP socket to revent PortUnreachableException
-        DatagramSocket ds = new DatagramSocket(33333);
+        // An idle UDP socket to prevent PortUnreachableException
+        DatagramSocket ds = new DatagramSocket();
+        idlePort = ds.getLocalPort();
+
+        cm.addPort(idlePort);
+        cm.addPort(kdc.getPort());
 
         System.setProperty("java.security.krb5.conf", "alternative-krb5.conf");
 
-        // For tryLast
         Security.setProperty("krb5.kdc.bad.policy", "trylast");
+
+        // We always make the real timeout to be 1 second
+        BadKdc.setRatio(0.25f);
         rewriteMaxRetries(4);
-        test1(4000, 6);         // 1 1 1 1 2 2
-        test1(4000, 2);         // 2 2
 
+        // Explanation: In this case, max_retries=4 and timeout=4s.
+        // For AS-REQ without preauth, we will see 4 4s timeout on kdc#1
+        // ("a4" repeat 4 times), and one 4s timeout on kdc#2 ("b4"). For
+        // AS-REQ with preauth, one 4s timeout on kdc#2 (second "b4").
+        // we tolerate 4 real timeout on kdc#2, so make it "(b4){2,6}".
+        test1("a4a4a4a4b4b4", "a4a4a4a4(b4){2,6}");
+        test1("b4b4", "(b4){2,6}");
+
+        BadKdc.setRatio(1f);
         rewriteMaxRetries(1);
-        test1(1000, 3);         // 1 2 2
-        test1(1000, 2);         // 2 2
+        // Explanation: Since max_retries=1 only, we could fail in 1st or 2nd
+        // AS-REQ to kdc#2.
+        String actual = test1("a1b1b1", "(a1b1b1|a1b1x|a1b1b1x)");
+        if (actual.endsWith("x")) {
+            // If 1st attempt fails, all bads are back available
+            test1("a1b1b1", "(a1b1b1|a1b1x|a1b1b1x)");
+        } else {
+            test1("b1b1", "(b1b1|b1x|b1b1x)");
+        }
 
+        BadKdc.setRatio(0.2f);
         rewriteMaxRetries(-1);
-        test1(5000, 4);         // 1 1 2 2
-        test1(5000, 2);         // 2 2
+        test1("a5a5a5b5b5", "a5a5a5(b5){2,4}");
+        test1("b5b5", "(b5){2,4}");
 
-        // For tryLess
-        Security.setProperty("krb5.kdc.bad.policy", "tryless:1," + BadKdc.toReal(5000));
+        BadKdc.setRatio(0.25f);
+        Security.setProperty("krb5.kdc.bad.policy",
+                "tryless:1,1000");
         rewriteMaxRetries(4);
-        test1(4000, 7);         // 1 1 1 1 2 1 2
-        test1(4000, 4);         // 1 2 1 2
+        test1("a4a4a4a4b4a4b4", "a4a4a4a4(b4){1,3}a4(b4){1,3}");
+        test1("a4b4a4b4", "a4(b4){1,3}a4(b4){1,3}");
 
+        BadKdc.setRatio(1f);
         rewriteMaxRetries(1);
-        test1(1000, 4);         // 1 2 1 2
-        test1(1000, 4);         // 1 2 1 2
+        actual = test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
+        if (actual.endsWith("x")) {
+            test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
+        } else {
+            test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
+        }
 
+        BadKdc.setRatio(.2f);
         rewriteMaxRetries(-1);
-        test1(5000, 5);         // 1 1 2 1 2
-        test1(5000, 4);         // 1 2 1 2
+        test1("a5a5a5b5a5b5", "a5a5a5(b5){1,2}a5(b5){1,2}");
+        test1("a5b5a5b5", "a5(b5){1,2}a5(b5){1,2}");
+
+        BadKdc.setRatio(1f);
+        rewriteMaxRetries(2);
+        if (BadKdc.toReal(2000) > 1000) {
+            // Explanation: if timeout is longer than 1s in tryLess,
+            // we will see "a1" at 2nd kdc#1 access
+            test1("a2a2b2a1b2", "a2a2(b2){1,2}a1(b2){1,2}");
+        } else {
+            test1("a2a2b2a2b2", "a2a2(b2){1,2}a2(b2){1,2}");
+        }
+
+        BadKdc.setRatio(1f);
 
         rewriteUdpPrefLimit(-1, -1);    // default, no limit
         test2("UDP");
@@ -90,32 +135,52 @@
 
     /**
      * One round of test for max_retries and timeout.
-     * @param timeout the expected timeout
-     * @param count the expected total try
+     *
+     * @param exact the expected exact match, where no timeout
+     *              happens for real KDCs
+     * @param relaxed the expected relaxed match, where some timeout
+     *                could happen for real KDCs
+     * @return the actual result
      */
-    private static void test1(int timeout, int count) throws Exception {
-        String timeoutTag = "timeout=" + BadKdc.toReal(timeout);
+    private static String test1(String exact, String relaxed) throws Exception {
         ByteArrayOutputStream bo = new ByteArrayOutputStream();
         PrintStream oldout = System.out;
         System.setOut(new PrintStream(bo));
-        Context c = Context.fromJAAS("client");
+        boolean failed = false;
+        long start = System.nanoTime();
+        try {
+            Context c = Context.fromJAAS("client");
+        } catch (LoginException e) {
+            failed = true;
+        }
         System.setOut(oldout);
 
         String[] lines = new String(bo.toByteArray()).split("\n");
-        System.out.println("----------------- TEST (" + timeout + "," +
-                count + ") -----------------");
+        System.out.println("----------------- TEST (" + exact
+                + ") -----------------");
+
+        // Result, a series of timeout + kdc#
+        StringBuilder sb = new StringBuilder();
         for (String line: lines) {
-            if (line.startsWith(">>> KDCCommunication")) {
+            if (cm.match(line)) {
                 System.out.println(line);
-                if (line.indexOf(timeoutTag) < 0) {
-                    throw new Exception("Wrong timeout value" + timeoutTag);
-                }
-                count--;
+                sb.append(cm.kdc()).append(cm.timeout());
             }
         }
-        if (count != 0) {
-            throw new Exception("Retry count is " + count + " less");
+        if (failed) {
+            sb.append("x");
         }
+        System.out.println("Time: " + (System.nanoTime() - start) / 1000000000d);
+        String actual = sb.toString();
+        System.out.println("Actual: " + actual);
+        if (actual.equals(exact)) {
+            System.out.println("Exact match: " + exact);
+        } else if (actual.matches(relaxed)) {
+            System.out.println("!!!! Tolerant match: " + relaxed);
+        } else {
+            throw new Exception("Match neither " + exact + " nor " + relaxed);
+        }
+        return actual;
     }
 
     /**
@@ -133,11 +198,11 @@
         String[] lines = new String(bo.toByteArray()).split("\n");
         System.out.println("----------------- TEST -----------------");
         for (String line: lines) {
-            if (line.startsWith(">>> KDCCommunication")) {
+            if (cm.match(line)) {
                 System.out.println(line);
                 count--;
-                if (line.indexOf(proto) < 0) {
-                    throw new Exception("Wrong timeout value");
+                if (!cm.protocol().equals(proto)) {
+                    throw new Exception("Wrong protocol value");
                 }
             }
         }
@@ -160,6 +225,7 @@
             }
             if (s.startsWith("[realms]")) {
                 // Reconfig global setting
+                fw.write("kdc_timeout = 5000\n");
                 if (global != -1) {
                     fw.write("udp_preference_limit = " + global + "\n");
                 }
@@ -178,7 +244,8 @@
 
     /**
      * Set max_retries and timeout value for realm. The global value is always
-     * 2 and 5000.
+     * 3 and 5000.
+     *
      * @param value max_retries and timeout/1000 for a realm, -1 means none.
      */
     private static void rewriteMaxRetries(int value) throws Exception {
@@ -191,7 +258,7 @@
             }
             if (s.startsWith("[realms]")) {
                 // Reconfig global setting
-                fw.write("max_retries = 2\n");
+                fw.write("max_retries = 3\n");
                 fw.write("kdc_timeout = " + BadKdc.toReal(5000) + "\n");
             } else if (s.trim().startsWith("kdc = ")) {
                 if (value != -1) {
@@ -200,7 +267,7 @@
                     fw.write("    kdc_timeout = " + BadKdc.toReal(value*1000) + "\n");
                 }
                 // Add a bad KDC as the first candidate
-                fw.write("    kdc = localhost:33333\n");
+                fw.write("    kdc = localhost:" + idlePort + "\n");
             }
             fw.write(s + "\n");
         }
diff --git a/jdk/test/sun/security/krb5/auto/OneKDC.java b/jdk/test/sun/security/krb5/auto/OneKDC.java
index 2d3fc54..7526628 100644
--- a/jdk/test/sun/security/krb5/auto/OneKDC.java
+++ b/jdk/test/sun/security/krb5/auto/OneKDC.java
@@ -95,7 +95,7 @@
      * entries with names using existing OneKDC principals.
      * @throws java.lang.Exception if anything goes wrong
      */
-    public void writeJAASConf() throws IOException {
+    public OneKDC writeJAASConf() throws IOException {
         System.setProperty("java.security.auth.login.config", JAAS_CONF);
         File f = new File(JAAS_CONF);
         FileOutputStream fos = new FileOutputStream(f);
@@ -123,6 +123,7 @@
                 "    isInitiator=false;\n};\n"
                 ).getBytes());
         fos.close();
+        return this;
     }
 
     /**
diff --git a/jdk/test/sun/security/krb5/canonicalize/Test.java b/jdk/test/sun/security/krb5/canonicalize/Test.java
index 9340163..3bd0bac 100644
--- a/jdk/test/sun/security/krb5/canonicalize/Test.java
+++ b/jdk/test/sun/security/krb5/canonicalize/Test.java
@@ -22,7 +22,7 @@
  */
 /*
  * @test
- * @bug 6682516
+ * @bug 6682516 8149521
  * @summary SPNEGO_HTTP_AUTH/WWW_KRB and SPNEGO_HTTP_AUTH/WWW_SPNEGO failed on all non-windows platforms
  * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Djava.security.krb5.conf=krb5.conf Test
  */
@@ -43,9 +43,11 @@
         check("c1", "c1.this.domain");
         check("c1.this", "c1.this.domain");
         check("c1.this.domain", "c1.this.domain");
+        check("c1.this.domain.", "c1.this.domain");
 
         // canonicalized name goes IP, reject
         check("c2", "c2");
+        check("c2.", "c2");
 
         // canonicalized name goes strange, reject
         check("c3", "c3");
diff --git a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java
index b812ba5..b10431b 100644
--- a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java
@@ -30,12 +30,13 @@
 
 /*
  * @test
- * @bug 7113275
+ * @bug 7113275 8164846
  * @summary compatibility issue with MD2 trust anchor and old X509TrustManager
- * @run main/othervm TrustTrustedCert PKIX TLSv1.1
- * @run main/othervm TrustTrustedCert SunX509 TLSv1.1
- * @run main/othervm TrustTrustedCert PKIX TLSv1.2
- * @run main/othervm TrustTrustedCert SunX509 TLSv1.2
+ * @run main/othervm TrustTrustedCert PKIX TLSv1.1 true
+ * @run main/othervm TrustTrustedCert PKIX TLSv1.1 false
+ * @run main/othervm TrustTrustedCert SunX509 TLSv1.1 false
+ * @run main/othervm TrustTrustedCert PKIX TLSv1.2 false
+ * @run main/othervm TrustTrustedCert SunX509 TLSv1.2 false
  */
 
 import java.net.*;
@@ -181,23 +182,32 @@
             Thread.sleep(50);
         }
 
-        SSLContext context = generateSSLContext();
-        SSLSocketFactory sslsf = context.getSocketFactory();
+        SSLSocket sslSocket = null;
+        try {
+            SSLContext context = generateSSLContext();
+            SSLSocketFactory sslsf = context.getSocketFactory();
 
-        SSLSocket sslSocket =
-            (SSLSocket)sslsf.createSocket("localhost", serverPort);
+            sslSocket = (SSLSocket)sslsf.createSocket("localhost", serverPort);
 
-        // enable the specified TLS protocol
-        sslSocket.setEnabledProtocols(new String[] {tlsProtocol});
+            // enable the specified TLS protocol
+            sslSocket.setEnabledProtocols(new String[] {tlsProtocol});
 
-        InputStream sslIS = sslSocket.getInputStream();
-        OutputStream sslOS = sslSocket.getOutputStream();
-
-        sslOS.write('B');
-        sslOS.flush();
-        sslIS.read();
-
-        sslSocket.close();
+            InputStream sslIS = sslSocket.getInputStream();
+            OutputStream sslOS = sslSocket.getOutputStream();
+            sslOS.write('B');
+            sslOS.flush();
+            sslIS.read();
+        } catch (SSLHandshakeException e) {
+            // focus in on the CertPathValidatorException
+            Throwable t = e.getCause().getCause();
+            if ((t == null) || (expectFail &&
+                !t.toString().contains("MD5withRSA"))) {
+                throw new RuntimeException(
+                    "Expected to see MD5withRSA in exception output " + t);
+            }
+        } finally {
+            if (sslSocket != null) sslSocket.close();
+        }
     }
 
     /*
@@ -206,10 +216,13 @@
      */
     private static String tmAlgorithm;        // trust manager
     private static String tlsProtocol;        // trust manager
+    // set this flag to test context of CertificateException
+    private static boolean expectFail;
 
     private static void parseArguments(String[] args) {
         tmAlgorithm = args[0];
         tlsProtocol = args[1];
+        expectFail = Boolean.parseBoolean(args[2]);
     }
 
     private static SSLContext generateSSLContext() throws Exception {
@@ -232,7 +245,7 @@
 
         // generate the private key.
         PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
-                                Base64.getMimeDecoder().decode(targetPrivateKey));
+                            Base64.getMimeDecoder().decode(targetPrivateKey));
         KeyFactory kf = KeyFactory.getInstance("RSA");
         RSAPrivateKey priKey =
                 (RSAPrivateKey)kf.generatePrivate(priKeySpec);
@@ -338,9 +351,19 @@
     volatile Exception clientException = null;
 
     public static void main(String[] args) throws Exception {
-        // MD5 is used in this test case, don't disable MD5 algorithm.
-        Security.setProperty("jdk.certpath.disabledAlgorithms",
+        /*
+         * Get the customized arguments.
+         */
+        parseArguments(args);
+
+        /*
+         * MD5 is used in this test case, don't disable MD5 algorithm.
+         * if expectFail is set, we're testing exception message
+         */
+        if (!expectFail) {
+            Security.setProperty("jdk.certpath.disabledAlgorithms",
                 "MD2, RSA keySize < 1024");
+        }
         Security.setProperty("jdk.tls.disabledAlgorithms",
                 "SSLv3, RC4, DH keySize < 768");
 
@@ -348,11 +371,6 @@
             System.setProperty("javax.net.debug", "all");
 
         /*
-         * Get the customized arguments.
-         */
-        parseArguments(args);
-
-        /*
          * Start the tests.
          */
         new TrustTrustedCert();
@@ -376,7 +394,8 @@
                 startServer(false);
             }
         } catch (Exception e) {
-            // swallow for now.  Show later
+            System.out.println("Unexpected exception: ");
+            e.printStackTrace();
         }
 
         /*
@@ -440,7 +459,11 @@
                          */
                         System.err.println("Server died...");
                         serverReady = true;
-                        serverException = e;
+                        if (!expectFail) {
+                            // only record if we weren't expecting.
+                            // client side will record exception
+                            serverException = e;
+                        }
                     }
                 }
             };
@@ -449,7 +472,11 @@
             try {
                 doServerSide();
             } catch (Exception e) {
-                serverException = e;
+                // only record if we weren't expecting.
+                // client side will record exception
+                if (!expectFail) {
+                    serverException = e;
+                }
             } finally {
                 serverReady = true;
             }
diff --git a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NotifyHandshakeTest.java b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NotifyHandshakeTest.java
index 1cd8a53..4e42bd1 100644
--- a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NotifyHandshakeTest.java
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NotifyHandshakeTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2005, 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
@@ -88,6 +88,7 @@
          */
         SSLServerSocket sslss =
             (SSLServerSocket)sslssf.createServerSocket(serverPort);
+        sslss.setSoTimeout(30000);  // 30 seconds
         serverPort = sslss.getLocalPort();
         Server server = new Server(sslss);
         server.start();
diff --git a/jdk/test/sun/security/ssl/etc/README b/jdk/test/sun/security/ssl/etc/README
new file mode 100644
index 0000000..0ac6a84
--- /dev/null
+++ b/jdk/test/sun/security/ssl/etc/README
@@ -0,0 +1,94 @@
+Keystores used for the JSSE regression test suite.
+
+keystore
+truststore
+==========
+
+These are the primary two keystores and contain entries for testing most
+of the JSSE regression test files.  There are three entries, one RSA-based,
+one DSA-based and one EC-based.  If they expire, simply recreate them
+using keytool and most of the test cases should work.
+
+The password on both files is:
+
+    passphrase
+
+There are no individual key entry passwords at this time.
+
+
+keystore entries
+================
+
+Alias name: dummy
+-----------------
+Creation date: May 16, 2016
+Entry type: PrivateKeyEntry
+Certificate chain length: 1
+Certificate[1]:
+Owner: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US
+Issuer: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US
+Serial number: 57399b87
+Valid from: Mon May 16 10:06:38 UTC 2016 until: Sat May 16 10:06:38 UTC 2026
+Signature algorithm name: SHA256withRSA
+Version: 1
+
+This can be generated using hacked (update the keytool source code so that
+it can be used for version 1 X.509 certificate) keytool command:
+% keytool -genkeypair -alias dummy -keyalg RSA -keysize 2048 \
+  -sigalg SHA256withRSA \
+  -dname "CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US" \
+  -validity 3652 -keypass passphrase -keystore keystore -storepass passphrase
+
+
+Alias name: dummyecdsa
+----------------------
+Creation date: May 16, 2016
+Entry type: PrivateKeyEntry
+Certificate chain length: 1
+Certificate[1]:
+Owner: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US
+Issuer: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US
+Serial number: 57399c1d
+Valid from: Mon May 16 10:09:01 UTC 2016 until: Sat May 16 10:09:01 UTC 2026
+Signature algorithm name: SHA256withECDSA
+Version: 1
+
+This can be generated using hacked (update the keytool source code so that
+it can be used for version 1 X.509 certificate) keytool command:
+% keytool -genkeypair -alias dummy -keyalg EC -keysize 256 \
+  -sigalg SHA256withECDSA \
+  -dname "CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US" \
+  -validity 3652 -keypass passphrase -keystore keystore -storepass passphrase
+
+Alias name: dummydsa
+--------------------
+Creation date: Mar 11, 2007
+Entry type: PrivateKeyEntry
+Certificate chain length: 1
+Certificate[1]:
+Owner: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US
+Issuer: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US
+Serial number: 45f3a314
+Valid from: Sun Mar 11 06:35:00 UTC 2007 until: Wed Mar 08 06:35:00 UTC 2017
+Certificate fingerprints:
+Signature algorithm name: SHA1withDSA
+Version: 1
+
+This can be generated using hacked (update the keytool source code so that
+it can be used for version 1 X.509 certificate) keytool command:
+% keytool -genkeypair -alias dummy -keyalg DSA -keysize 1024 \
+  -sigalg SHA1withDSA \
+  -dname "CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US" \
+  -validity 3652 -keypass passphrase -keystore keystore -storepass passphrase
+
+
+truststore entries
+==================
+This key store contains only trusted certificate entries.  The same
+certificates are used in both keystore and truststore.
+
+
+unknown_keystore
+================
+A keystore you can use when you don't want things to be verified.
+Use this with keystore/truststore, and you'll never get a match.
diff --git a/jdk/test/sun/security/ssl/etc/keystore b/jdk/test/sun/security/ssl/etc/keystore
index 2eb1993..4062e17 100644
--- a/jdk/test/sun/security/ssl/etc/keystore
+++ b/jdk/test/sun/security/ssl/etc/keystore
Binary files differ
diff --git a/jdk/test/sun/security/ssl/etc/truststore b/jdk/test/sun/security/ssl/etc/truststore
index 65a140d..12da39e 100644
--- a/jdk/test/sun/security/ssl/etc/truststore
+++ b/jdk/test/sun/security/ssl/etc/truststore
Binary files differ
diff --git a/jdk/test/sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java b/jdk/test/sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java
index 812732e..5e08f76 100644
--- a/jdk/test/sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java
+++ b/jdk/test/sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java
@@ -26,8 +26,7 @@
  * @bug 4496785
  * @summary Verify that all ciphersuites work in all configurations
  * @author Andreas Sterbenz
- * @run main/othervm/timeout=300 -Djdk.tls.namedGroups="secp256r1,secp192r1"
- *      ClientJSSEServerJSSE
+ * @run main/othervm/timeout=300 ClientJSSEServerJSSE
  */
 
 import java.security.Security;
diff --git a/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxy.java b/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxy.java
index 3908db8..9fb21a2 100644
--- a/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxy.java
+++ b/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxy.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
@@ -98,6 +98,7 @@
             ServerSocketFactory ssf =
                 PostThruProxy.getServerSocketFactory(useSSL);
             ServerSocket ss = ssf.createServerSocket(serverPort);
+            ss.setSoTimeout(30000);  // 30 seconds
             serverPort = ss.getLocalPort();
             new TestServer(ss);
         } catch (Exception e) {
diff --git a/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxyWithAuth.java b/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxyWithAuth.java
index d3e7dda..ccd8360 100644
--- a/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxyWithAuth.java
+++ b/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxyWithAuth.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
@@ -100,6 +100,7 @@
             ServerSocketFactory ssf =
                 PostThruProxyWithAuth.getServerSocketFactory(useSSL);
             ServerSocket ss = ssf.createServerSocket(serverPort);
+            ss.setSoTimeout(30000);  // 30 seconds
             serverPort = ss.getLocalPort();
             new TestServer(ss);
         } catch (Exception e) {
diff --git a/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java b/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java
index c86affc..811ffd9 100644
--- a/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java
+++ b/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java
@@ -114,6 +114,9 @@
             // specify -tsadigestalg option because
             // TSA server uses SHA-1 digest algorithm
              OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+                    "-J-Dhttp.proxyHost=",
+                    "-J-Dhttp.proxyPort=",
+                    "-J-Djava.net.useSystemProxies=",
                     "-verbose",
                     "-keystore", KEYSTORE,
                     "-storepass", PASSWORD,
diff --git a/jdk/test/sun/security/tools/jarsigner/warnings/Test.java b/jdk/test/sun/security/tools/jarsigner/warnings/Test.java
index 43ced17..999789a 100644
--- a/jdk/test/sun/security/tools/jarsigner/warnings/Test.java
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/Test.java
@@ -197,21 +197,4 @@
         cmd.addAll(Arrays.asList(args));
         return ProcessTools.executeCommand(cmd.toArray(new String[cmd.size()]));
     }
-
-    protected OutputAnalyzer keytool(String... cmd) throws Throwable {
-        return tool(KEYTOOL, cmd);
-    }
-
-    protected OutputAnalyzer jarsigner(String... cmd) throws Throwable {
-        return tool(JARSIGNER, cmd);
-    }
-
-    private OutputAnalyzer tool(String tool, String... args) throws Throwable {
-        List<String> cmd = new ArrayList<>();
-        cmd.add(tool);
-        cmd.add("-J-Duser.language=en");
-        cmd.add("-J-Duser.country=US");
-        cmd.addAll(Arrays.asList(args));
-        return ProcessTools.executeCommand(cmd.toArray(new String[cmd.size()]));
-    }
 }
diff --git a/jdk/test/sun/text/resources/LocaleData b/jdk/test/sun/text/resources/LocaleData
index a80c129..f4c26f6 100644
--- a/jdk/test/sun/text/resources/LocaleData
+++ b/jdk/test/sun/text/resources/LocaleData
@@ -6406,8 +6406,8 @@
 CurrencyNames//bif=Burundian Franc
 CurrencyNames//bob=Bolivian Boliviano
 CurrencyNames//btn=Bhutanese Ngultrum
-CurrencyNames//byb=Belarusian New Ruble (1994-1999)
-CurrencyNames//byr=Belarusian Ruble
+CurrencyNames//byb=Belarusian Ruble (1994-1999)
+CurrencyNames//byr=Belarusian Ruble (2000-2016)
 CurrencyNames//cdf=Congolese Franc
 CurrencyNames//clf=Chilean Unit of Account (UF)
 CurrencyNames//cny=Chinese Yuan
@@ -6439,7 +6439,6 @@
 CurrencyNames//mro=Mauritanian Ouguiya
 CurrencyNames//mur=Mauritian Rupee
 CurrencyNames//mvr=Maldivian Rufiyaa
-CurrencyNames//mwk=Malawian Kwacha
 CurrencyNames//mxv=Mexican Investment Unit
 CurrencyNames//mzm=Mozambican Metical (1980-2006)
 CurrencyNames//mzn=Mozambican Metical
@@ -6447,7 +6446,6 @@
 CurrencyNames//nio=Nicaraguan C\u00f3rdoba
 CurrencyNames//nlg=Dutch Guilder
 CurrencyNames//omr=Omani Rial
-CurrencyNames//pen=Peruvian Nuevo Sol
 CurrencyNames//pgk=Papua New Guinean Kina
 CurrencyNames//pkr=Pakistani Rupee
 CurrencyNames//pyg=Paraguayan Guarani
@@ -8287,3 +8285,14 @@
 
 # bug #8075173
 FormatData/de/standalone.MonthAbbreviations/2=M\u00e4r
+
+# bug #8129361
+CurrencyNames//hrk=Kuna
+
+# bug #8164784
+CurrencyNames//mwk=Malawian Malawi Kwacha
+CurrencyNames//pen=Peruvian Sol
+
+# bug #8145952
+CurrencyNames//byn=Belarusian Ruble
+CurrencyNames/be_BY/BYN=\u0420\u0443\u0431
diff --git a/jdk/test/sun/text/resources/LocaleDataTest.java b/jdk/test/sun/text/resources/LocaleDataTest.java
index 44f94e7..94e92b9 100644
--- a/jdk/test/sun/text/resources/LocaleDataTest.java
+++ b/jdk/test/sun/text/resources/LocaleDataTest.java
@@ -36,7 +36,8 @@
  *      6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 7101495
  *      7003124 7085757 7028073 7171028 7189611 8000983 7195759 8004489 8006509
  *      7114053 7074882 7040556 8013836 8021121 6192407 6931564 8027695 7090826
- *      8017142 8037343 8055222 8042126 8074791 8075173 8080774
+ *      8017142 8037343 8055222 8042126 8074791 8075173 8080774 8129361
+ *      8145952 8164784
  * @summary Verify locale data
  *
  */
diff --git a/jdk/test/tools/pack200/Pack200Test.java b/jdk/test/tools/pack200/Pack200Test.java
index b4226f2..1ee453e 100644
--- a/jdk/test/tools/pack200/Pack200Test.java
+++ b/jdk/test/tools/pack200/Pack200Test.java
@@ -31,6 +31,7 @@
  /*
   * @test
   * @bug 6521334 6712743 8007902
+  * @requires (sun.arch.data.model == "64" & os.maxMemory >= 4g)
   * @summary check for memory leaks, test general packer/unpacker functionality\
   *          using native and java unpackers
   * @compile -XDignore.symbol.file Utils.java Pack200Test.java
diff --git a/langtools/.hgtags b/langtools/.hgtags
index 1ade7ba..9ea9e07 100644
--- a/langtools/.hgtags
+++ b/langtools/.hgtags
@@ -720,3 +720,25 @@
 e0ed0609963aca47e766901d7ec57ab97b649567 jdk8u151-b05
 ff824edbfa4dc81b6f2b5c33e4027806fd149304 jdk8u151-b06
 305472b39e966569e99a8b149543e3cd9160419c jdk8u151-b07
+bb3202444c4b86a63aaf68490f09ecf4bb1eff5f jdk8u151-b08
+9a9ce479b92f1b4d9d436fb857d70c3d2b59a20c jdk8u122-b00
+85d9e434701cc7112aaf965b0f5ee4b31ab2a445 jdk8u122-b01
+2baeb96fa198f75e9bd50a5f5ef4a19be6cfbc4e jdk8u122-b02
+a5da608d17bdc073fd3a4f2e1d4fe7d526567d09 jdk8u122-b03
+a5da608d17bdc073fd3a4f2e1d4fe7d526567d09 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+18bfe5da1f56c6932cce6378f617904db68bedcd jdk8u122-b03
+5ce29dae0e3e11bbecbc2173479ccf0a06b7d556 jdk8u122-b04
+9229942f9ee2ad7c5b8d57cddcb9011aac6bac23 jdk8u132-b00
+03e31cfcd499360c2db8eeccacc77ee040e71bac jdk8u152-b00
+f47b61665c6fefb5eba2504d5e312004d59f0483 jdk8u152-b01
+a283fc8f44acc956fbc4192d546216c4638e7146 jdk8u152-b02
+2783ff53e49dec0e7939b54aeb302605725e1017 jdk8u152-b03
+71e344b8e2c237dd7ef7c5f4276030e2880a6e07 jdk8u152-b04
+38bb14529d829cc290439a712b9821cd0e272f7e jdk8u152-b05
+243671be7d4e0a4f71c0f88add12695ac86295cb jdk8u152-b06
+a2cc6d348025da4b72c7b18edcc5fc9e046803da jdk8u152-b07
+19eec1de09c1fef1392593284eb9d2c5becd6663 jdk8u152-b08
+ca6375d1a8b2ba3c086746a2bca65015a1a12146 jdk8u152-b09
+abdab2b0bfdbda42030083e99e903bd663cafda3 jdk8u152-b10
diff --git a/langtools/ASSEMBLY_EXCEPTION b/langtools/ASSEMBLY_EXCEPTION
index 8b7ac1d..065b8d9 100644
--- a/langtools/ASSEMBLY_EXCEPTION
+++ b/langtools/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Sun at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Sun gives you permission to link this
-    OpenJDK Code with certain code licensed by Sun as indicated at
+    As a special exception, Oracle gives you permission to link this
+    OpenJDK Code with certain code licensed by Oracle as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Sun.
+    governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Sun
-could not provide under GPL2 (or that Sun has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java
index f4e4aab..5f0b6b8 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java
@@ -27,6 +27,7 @@
 
 import java.util.*;
 
+import com.sun.tools.javac.tree.TreeInfo.PosKind;
 import com.sun.tools.javac.util.*;
 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
 import com.sun.tools.javac.util.List;
@@ -1531,12 +1532,16 @@
                                   catchallpc, 0);
                     startseg = env.info.gaps.next().intValue();
                 }
-                code.statBegin(TreeInfo.finalizerPos(env.tree));
+                code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
                 code.markStatBegin();
 
                 Item excVar = makeTemp(syms.throwableType);
                 excVar.store();
                 genFinalizer(env);
+                code.resolvePending();
+                code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
+                code.markStatBegin();
+
                 excVar.load();
                 registerCatch(body.pos(), startseg,
                               env.info.gaps.next().intValue(),
@@ -1550,7 +1555,7 @@
                     code.resolve(env.info.cont);
 
                     // Mark statement line number
-                    code.statBegin(TreeInfo.finalizerPos(env.tree));
+                    code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
                     code.markStatBegin();
 
                     // Save return address.
diff --git a/langtools/src/share/classes/com/sun/tools/javac/tree/TreeInfo.java b/langtools/src/share/classes/com/sun/tools/javac/tree/TreeInfo.java
index 66a61b1..0ae0a92 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/TreeInfo.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/TreeInfo.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -35,6 +35,7 @@
 import com.sun.tools.javac.tree.JCTree.*;
 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
 import com.sun.tools.javac.util.*;
+
 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
 import static com.sun.tools.javac.code.Flags.*;
 import static com.sun.tools.javac.code.TypeTag.BOT;
@@ -611,13 +612,21 @@
         };
     }
 
+    public enum PosKind {
+        START_POS() { int  toPos(JCTree tree) { return TreeInfo.getStartPos(tree); } },
+        FIRST_STAT_POS() { int  toPos(JCTree tree) { return firstStatPos(tree); } },
+        END_POS() { int  toPos(JCTree tree) { return endPos(tree); } };
+
+        abstract int toPos(JCTree tree);
+    }
+
     /** The position of the finalizer of given try/synchronized statement.
      */
-    public static int finalizerPos(JCTree tree) {
+    public static int finalizerPos(JCTree tree, PosKind posKind) {
         if (tree.hasTag(TRY)) {
             JCTry t = (JCTry) tree;
             Assert.checkNonNull(t.finalizer);
-            return firstStatPos(t.finalizer);
+            return posKind.toPos(t.finalizer);
         } else if (tree.hasTag(SYNCHRONIZED)) {
             return endPos(((JCSynchronized) tree).body);
         } else {
diff --git a/langtools/test/tools/javac/T7008643/InlinedFinallyConfuseDebuggersTest.java b/langtools/test/tools/javac/T7008643/InlinedFinallyConfuseDebuggersTest.java
index 8557f99..0b63e9b 100644
--- a/langtools/test/tools/javac/T7008643/InlinedFinallyConfuseDebuggersTest.java
+++ b/langtools/test/tools/javac/T7008643/InlinedFinallyConfuseDebuggersTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -64,6 +64,7 @@
         {9,           21},      //System.out.println("finally");
         {10,          29},
         {9,           32},      //System.out.println("finally");
+        {10,          41},      //}
         {11,          43},
     };
 
diff --git a/langtools/test/tools/javac/T8180660/MissingLNTEntryForFinalizerTest.java b/langtools/test/tools/javac/T8180660/MissingLNTEntryForFinalizerTest.java
new file mode 100644
index 0000000..f0fd104
--- /dev/null
+++ b/langtools/test/tools/javac/T8180660/MissingLNTEntryForFinalizerTest.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2017, 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 8180141
+ * @summary Missing entry in LineNumberTable for break statement that jumps out of try-finally
+ * @compile -g MissingLNTEntryForFinalizerTest.java
+ * @run main MissingLNTEntryForFinalizerTest
+ */
+
+import java.io.File;
+import java.net.URI;
+
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+
+import com.sun.tools.classfile.*;
+import com.sun.tools.javac.comp.Attr;
+import com.sun.tools.javac.comp.AttrContext;
+import com.sun.tools.javac.comp.Env;
+import com.sun.tools.javac.file.JavacFileManager;
+import com.sun.tools.javac.main.JavaCompiler;
+import com.sun.tools.javac.tree.JCTree;
+import com.sun.tools.javac.tree.JCTree.*;
+import com.sun.tools.javac.util.Context;
+import com.sun.tools.javac.util.List;
+
+import static com.sun.tools.javac.util.List.of;
+import static com.sun.tools.javac.tree.JCTree.Tag.*;
+
+public class MissingLNTEntryForFinalizerTest {
+    protected ReusableJavaCompiler tool;
+    Context context;
+
+    MissingLNTEntryForFinalizerTest() {
+        context = new Context();
+        JavacFileManager.preRegister(context);
+        MyAttr.preRegister(context);
+        tool = new ReusableJavaCompiler(context);
+    }
+
+    public static void main(String... args) throws Throwable {
+        new MissingLNTEntryForFinalizerTest().test();
+    }
+
+    void test() throws Throwable {
+        JavaSource source = new JavaSource("1");
+        tool.clear();
+        List<JavaFileObject> inputs = of(source);
+        try {
+            tool.compile(inputs);
+        } catch (Throwable ex) {
+            throw new AssertionError(ex);
+        }
+        File testClasses = new File(".");
+        File file = new File(testClasses, "Test1.class");
+        ClassFile classFile = ClassFile.read(file);
+        for (Method m : classFile.methods) {
+            if (classFile.constant_pool.getUTF8Value(m.name_index).equals("foo")) {
+                Code_attribute code = (Code_attribute)m.attributes.get(Attribute.Code);
+                LineNumberTable_attribute lnt = (LineNumberTable_attribute)code.attributes.get(Attribute.LineNumberTable);
+                checkLNT(lnt, MyAttr.lineNumber);
+            }
+        }
+    }
+
+    void checkLNT(LineNumberTable_attribute lnt, int lineToCheckFor) {
+        for (LineNumberTable_attribute.Entry e: lnt.line_number_table) {
+            if (e.line_number == lineToCheckFor) {
+                return;
+            }
+        }
+        throw new AssertionError("seek line number not found in the LNT for method foo()");
+    }
+
+    class JavaSource extends SimpleJavaFileObject {
+        String id;
+        String template =
+                "import java.util.*;\n" +
+                "class Test#Id {\n" +
+                "    void foo() {\n" +
+                "        List<String> l = null;\n" +
+                "        String first = null;\n" +
+                "        try {\n" +
+                "            first = l.get(0);\n" +
+                "        } finally {\n" +
+                "            if (first != null) {\n" +
+                "                System.out.println(\"finalizer\");\n" +
+                "            }\n" +
+                "        }\n" +
+                "    }\n" +
+                "}";
+
+        JavaSource(String id) {
+            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
+            this.id = id;
+        }
+
+        @Override
+        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+            return template.replace("#Id", id);
+        }
+    }
+
+    /* this class has been set up to do not depend on a fixed line number, this Attr subclass will
+     * look for 'break' or 'continue' statements in order to find the actual line number they occupy.
+     * This way the test can find if that line number appears in the LNT generated for a given class.
+     */
+    static class MyAttr extends Attr {
+        static int lineNumber;
+
+        static void preRegister(Context context) {
+            context.put(attrKey, (com.sun.tools.javac.util.Context.Factory<Attr>) c -> new MyAttr(c));
+        }
+
+        MyAttr(Context context) {
+            super(context);
+        }
+
+        @Override
+        public com.sun.tools.javac.code.Type attribStat(JCTree tree, Env<AttrContext> env) {
+            com.sun.tools.javac.code.Type result = super.attribStat(tree, env);
+            if (tree.hasTag(TRY)) {
+                JCTry tryTree = (JCTry)tree;
+                lineNumber = env.toplevel.lineMap.getLineNumber(tryTree.finalizer.endpos);
+            }
+            return result;
+        }
+    }
+
+    static class ReusableJavaCompiler extends JavaCompiler {
+        ReusableJavaCompiler(Context context) {
+            super(context);
+        }
+
+        protected void checkReusable() {
+            // do nothing
+        }
+
+        @Override
+        public void close() {
+            //do nothing
+        }
+
+        void clear() {
+            //do nothing
+        }
+    }
+}
diff --git a/langtools/test/tools/javac/linenumbers/FinallyLineNumberTest.java b/langtools/test/tools/javac/linenumbers/FinallyLineNumberTest.java
index 892d365..51946f6 100644
--- a/langtools/test/tools/javac/linenumbers/FinallyLineNumberTest.java
+++ b/langtools/test/tools/javac/linenumbers/FinallyLineNumberTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -36,7 +36,6 @@
 import com.sun.tools.classfile.LineNumberTable_attribute;
 import com.sun.tools.classfile.LineNumberTable_attribute.Entry;
 
-import java.io.File;
 import java.io.IOException;
 
 public class FinallyLineNumberTest {
@@ -46,13 +45,13 @@
         if (lines == null) {
             throw new Exception("finally line number table could not be loaded");
         }
-        if (lines.length != 4) {
+        if (lines.length != 5) {
             // Help debug
             System.err.println("LineTable error, got lines:");
             for (Entry e : lines) {
                 System.err.println(e.line_number);
             }
-            throw new Exception("finally line number table incorrect: length=" + lines.length + " expected length=4");
+            throw new Exception("finally line number table incorrect: length=" + lines.length + " expected length=5");
         }
 
         // return null line, for the load null operation
@@ -71,11 +70,17 @@
             throw new Exception("finally line number table incorrect: got=" + current + " expected=" + first);
         }
 
-        // finally line, for when exception is thrown
+        // for when exception is thrown
         current = lines[3].line_number;
         if (current != first + 2) {
             throw new Exception("finally line number table incorrect: got=" + current + " expected=" + (first + 2));
         }
+
+        // the '}' closing the finally block
+        current = lines[4].line_number;
+        if (current != first + 3) {
+            throw new Exception("finally line number table incorrect: got=" + current + " expected=" + (first + 3));
+        }
     }
 
     static Entry[] findEntries() throws IOException, ConstantPoolException {
diff --git a/make/common/NativeCompilation.gmk b/make/common/NativeCompilation.gmk
index 494ebef..670f911 100644
--- a/make/common/NativeCompilation.gmk
+++ b/make/common/NativeCompilation.gmk
@@ -297,17 +297,21 @@
     $$(shell $(RM) -f $$($1_SUPERFLUOUS_OBJS))
   endif
 
-  # Pickup extra OPENJDK_TARGET_OS_API and/or OPENJDK_TARGET_OS dependent variables for CFLAGS.
-  $1_EXTRA_CFLAGS:=$$($1_CFLAGS_$(OPENJDK_TARGET_OS_API)) $$($1_CFLAGS_$(OPENJDK_TARGET_OS))
+  # Pickup extra OPENJDK_TARGET_OS_API, OPENJDK_TARGET_OS, and/or OPENJDK_TARGET_OS plus
+  # OPENJDK_TARGET_CPU pair dependent variables for CFLAGS.
+  $1_EXTRA_CFLAGS:=$$($1_CFLAGS_$(OPENJDK_TARGET_OS_API)) $$($1_CFLAGS_$(OPENJDK_TARGET_OS)) \
+      $$($1_CFLAGS_$(OPENJDK_TARGET_OS)_$(OPENJDK_TARGET_CPU))
   ifneq ($(DEBUG_LEVEL),release)
     # Pickup extra debug dependent variables for CFLAGS
     $1_EXTRA_CFLAGS+=$$($1_CFLAGS_debug)
     $1_EXTRA_CFLAGS+=$$($1_CFLAGS_$(OPENJDK_TARGET_OS_API)_debug)
     $1_EXTRA_CFLAGS+=$$($1_CFLAGS_$(OPENJDK_TARGET_OS)_debug)
+    $1_EXTRA_CFLAGS+=$$($1_CFLAGS_$(OPENJDK_TARGET_OS)_$(OPENJDK_TARGET_CPU)_debug)
   else
     $1_EXTRA_CFLAGS+=$$($1_CFLAGS_release)
     $1_EXTRA_CFLAGS+=$$($1_CFLAGS_$(OPENJDK_TARGET_OS_API)_release)
     $1_EXTRA_CFLAGS+=$$($1_CFLAGS_$(OPENJDK_TARGET_OS)_release)
+    $1_EXTRA_CFLAGS+=$$($1_CFLAGS_$(OPENJDK_TARGET_OS)_$(OPENJDK_TARGET_CPU)_release)
   endif
 
   # Pickup extra OPENJDK_TARGET_OS_API and/or OPENJDK_TARGET_OS dependent variables for CXXFLAGS.
diff --git a/nashorn/.hgtags b/nashorn/.hgtags
index a001c87..30636f7 100644
--- a/nashorn/.hgtags
+++ b/nashorn/.hgtags
@@ -699,3 +699,25 @@
 178207e92304e6717c1b2e80c56424efe4e69204 jdk8u151-b05
 b9ed966e2b873528553e27a791298205e1bc7cb5 jdk8u151-b06
 0e94fe02e7596493459317fe13a782c1a4daa1be jdk8u151-b07
+1f3aa2166cc45a091656795e0f022f2a049c6cae jdk8u151-b08
+18eb73eb84c5395b3efcafa43ce224565eca02b3 jdk8u122-b00
+9e615ea961fe5732813ed7b273606e7337ea2234 jdk8u122-b01
+2f0b11882cb7ddb10e35682ab9e8343919a71c54 jdk8u122-b02
+df2a2824284f97c5edb9b9c2e6d18bb4ff838199 jdk8u122-b03
+df2a2824284f97c5edb9b9c2e6d18bb4ff838199 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+12650d23a8fd1b27a0d28c6a276fdecf01805294 jdk8u122-b03
+3c3b4e793e7c6255a840844db077ef466940035c jdk8u122-b04
+30dc0c72f3d0aff34b6d421208b18f384d05d761 jdk8u132-b00
+91d33aea2714e63796eeab0e63e38c9d2568c00c jdk8u152-b00
+50dac2fd8689dbb820d887ce3919708d5d042891 jdk8u152-b01
+01bbd310156db7a75a46a7320d1f49beff844472 jdk8u152-b02
+2a01d94fea9a86b4038a93622f62b0986083f67e jdk8u152-b03
+9dce75561a92f096d822ebb7eb76810f191fe522 jdk8u152-b04
+cdb7d9454d254e95c73d6dc77077ab2c198e2ad6 jdk8u152-b05
+2be667f12b54fc5b57b147f60851ee63ff02e5fa jdk8u152-b06
+a44dcdfa00bee9261012f10bd3f06bea1fec4340 jdk8u152-b07
+d0a8151a276c362a6e17068d9aa8ed583309d46e jdk8u152-b08
+37e94d764d7b98e3676e54f2ad346d721fdde113 jdk8u152-b09
+b4f39fda3c39d41a33c9996555ddfd3200895756 jdk8u152-b10
diff --git a/nashorn/ASSEMBLY_EXCEPTION b/nashorn/ASSEMBLY_EXCEPTION
index 8b7ac1d..065b8d9 100644
--- a/nashorn/ASSEMBLY_EXCEPTION
+++ b/nashorn/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Sun at openjdk.java.net and
-openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
-GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
+openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
+General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Sun gives you permission to link this
-    OpenJDK Code with certain code licensed by Sun as indicated at
+    As a special exception, Oracle gives you permission to link this
+    OpenJDK Code with certain code licensed by Oracle as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Sun.
+    governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
-build an executable that includes those portions of necessary code that Sun
-could not provide under GPL2 (or that Sun has provided under GPL2 with the
-Classpath exception).  If you modify or add to the OpenJDK code, that new
-GPL2 code may still be combined with Designated Exception Modules if the
-new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
+to build an executable that includes those portions of necessary code that
+Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
+with the Classpath exception).  If you modify or add to the OpenJDK code,
+that new GPL2 code may still be combined with Designated Exception Modules
+if the new code is made subject to this exception by its copyright holder.
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
index 9e1148f..6b9b731 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
@@ -2454,11 +2454,6 @@
                     }
 
                     @Override
-                    public boolean enterObjectNode(final ObjectNode objectNode) {
-                        return false;
-                    }
-
-                    @Override
                     public boolean enterDefault(final Node node) {
                         if (contains) {
                             return false;
@@ -2526,7 +2521,8 @@
             oc = new FieldObjectCreator<Expression>(this, tuples) {
                 @Override
                 protected void loadValue(final Expression node, final Type type) {
-                    loadExpressionAsType(node, type);
+                    // Use generic type in order to avoid conversion between object types
+                    loadExpressionAsType(node, Type.generic(type));
                 }};
         }
 
@@ -2542,10 +2538,7 @@
         //handler
         if (restOfProperty) {
             final ContinuationInfo ci = getContinuationInfo();
-            // Can be set at most once for a single rest-of method
-            assert ci.getObjectLiteralMap() == null;
-            ci.setObjectLiteralMap(oc.getMap());
-            ci.setObjectLiteralStackDepth(method.getStackSize());
+            ci.setObjectLiteralMap(method.getStackSize(), oc.getMap());
         }
 
         method.dup();
@@ -4023,7 +4016,7 @@
                     void loadStack() {
                         assert assignNode.getWidestOperandType() == Type.INT;
                         if (isRhsZero(binaryNode)) {
-                            loadExpressionAsType(binaryNode.lhs(), Type.INT);
+                            loadExpression(binaryNode.lhs(), TypeBounds.INT, true);
                         } else {
                             loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), TypeBounds.INT, true, false);
                             method.shr();
@@ -5259,10 +5252,8 @@
         private Type[] stackTypes;
         // If non-null, this node should perform the requisite type conversion
         private Type returnValueType;
-        // If we are in the middle of an object literal initialization, we need to update the map
-        private PropertyMap objectLiteralMap;
-        // Object literal stack depth for object literal - not necessarily top if property is a tree
-        private int objectLiteralStackDepth = -1;
+        // If we are in the middle of an object literal initialization, we need to update the property maps
+        private Map<Integer, PropertyMap> objectLiteralMaps;
         // The line number at the continuation point
         private int lineNumber;
         // The active catch label, in case the continuation point is in a try/catch block
@@ -5314,20 +5305,15 @@
             this.returnValueType = returnValueType;
         }
 
-        int getObjectLiteralStackDepth() {
-            return objectLiteralStackDepth;
+        void setObjectLiteralMap(final int objectLiteralStackDepth, final PropertyMap objectLiteralMap) {
+            if (objectLiteralMaps == null) {
+                objectLiteralMaps = new HashMap<>();
+            }
+            objectLiteralMaps.put(objectLiteralStackDepth, objectLiteralMap);
         }
 
-        void setObjectLiteralStackDepth(final int objectLiteralStackDepth) {
-            this.objectLiteralStackDepth = objectLiteralStackDepth;
-        }
-
-        PropertyMap getObjectLiteralMap() {
-            return objectLiteralMap;
-        }
-
-        void setObjectLiteralMap(final PropertyMap objectLiteralMap) {
-            this.objectLiteralMap = objectLiteralMap;
+        PropertyMap getObjectLiteralMap(final int stackDepth) {
+            return objectLiteralMaps == null ? null : objectLiteralMaps.get(stackDepth);
         }
 
         @Override
@@ -5417,10 +5403,9 @@
         final int[]   stackStoreSpec = ci.getStackStoreSpec();
         final Type[]  stackTypes     = ci.getStackTypes();
         final boolean isStackEmpty   = stackStoreSpec.length == 0;
-        boolean replacedObjectLiteralMap = false;
+        int replacedObjectLiteralMaps = 0;
         if(!isStackEmpty) {
             // Load arguments on the stack
-            final int objectLiteralStackDepth = ci.getObjectLiteralStackDepth();
             for(int i = 0; i < stackStoreSpec.length; ++i) {
                 final int slot = stackStoreSpec[i];
                 method.load(lvarTypes.get(slot), slot);
@@ -5428,18 +5413,18 @@
                 // stack: s0=object literal being initialized
                 // change map of s0 so that the property we are initializing when we failed
                 // is now ci.returnValueType
-                if (i == objectLiteralStackDepth) {
+                final PropertyMap map = ci.getObjectLiteralMap(i);
+                if (map != null) {
                     method.dup();
-                    assert ci.getObjectLiteralMap() != null;
                     assert ScriptObject.class.isAssignableFrom(method.peekType().getTypeClass()) : method.peekType().getTypeClass() + " is not a script object";
-                    loadConstant(ci.getObjectLiteralMap());
+                    loadConstant(map);
                     method.invoke(ScriptObject.SET_MAP);
-                    replacedObjectLiteralMap = true;
+                    replacedObjectLiteralMaps++;
                 }
             }
         }
-        // Must have emitted the code for replacing the map of an object literal if we have a set object literal stack depth
-        assert ci.getObjectLiteralStackDepth() == -1 || replacedObjectLiteralMap;
+        // Must have emitted the code for replacing all object literal maps
+        assert ci.objectLiteralMaps == null || ci.objectLiteralMaps.size() == replacedObjectLiteralMaps;
         // Load RewriteException back.
         method.load(rewriteExceptionType, lvarCount);
         // Get rid of the stored reference
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java b/nashorn/src/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java
index 310a087..63bafa7 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java
@@ -33,6 +33,7 @@
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Deque;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.IdentityHashMap;
 import java.util.Iterator;
@@ -122,9 +123,9 @@
         private final List<JumpOrigin> origins = new LinkedList<>();
         private Map<Symbol, LvarType> types = Collections.emptyMap();
 
-        void addOrigin(final JoinPredecessor originNode, final Map<Symbol, LvarType> originTypes) {
+        void addOrigin(final JoinPredecessor originNode, final Map<Symbol, LvarType> originTypes, final LocalVariableTypesCalculator calc) {
             origins.add(new JumpOrigin(originNode, originTypes));
-            this.types = getUnionTypes(this.types, originTypes);
+            this.types = calc.getUnionTypes(this.types, originTypes);
         }
     }
     private enum LvarType {
@@ -185,12 +186,15 @@
     }
 
     @SuppressWarnings("unchecked")
-    private static IdentityHashMap<Symbol, LvarType> cloneMap(final Map<Symbol, LvarType> map) {
-        return (IdentityHashMap<Symbol, LvarType>)((IdentityHashMap<?,?>)map).clone();
+    private static HashMap<Symbol, LvarType> cloneMap(final Map<Symbol, LvarType> map) {
+        return (HashMap<Symbol, LvarType>)((HashMap<?,?>)map).clone();
     }
 
     private LocalVariableConversion createConversion(final Symbol symbol, final LvarType branchLvarType,
             final Map<Symbol, LvarType> joinLvarTypes, final LocalVariableConversion next) {
+        if (invalidatedSymbols.contains(symbol)) {
+            return next;
+        }
         final LvarType targetType = joinLvarTypes.get(symbol);
         assert targetType != null;
         if(targetType == branchLvarType) {
@@ -208,7 +212,7 @@
         return new LocalVariableConversion(symbol, branchLvarType.type, targetType.type, next);
     }
 
-    private static Map<Symbol, LvarType> getUnionTypes(final Map<Symbol, LvarType> types1, final Map<Symbol, LvarType> types2) {
+    private Map<Symbol, LvarType> getUnionTypes(final Map<Symbol, LvarType> types1, final Map<Symbol, LvarType> types2) {
         if(types1 == types2 || types1.isEmpty()) {
             return types2;
         } else if(types2.isEmpty()) {
@@ -261,6 +265,11 @@
             final LvarType type2 = types2.get(symbol);
             union.put(symbol, widestLvarType(type1,  type2));
         }
+        // If the two sets of symbols differ, there's a good chance that some of
+        // symbols only appearing in one of the sets are lexically invalidated,
+        // so we remove them from further consideration.
+        // This is not strictly necessary, just a working set size optimization.
+        union.keySet().removeAll(invalidatedSymbols);
         return union;
     }
 
@@ -359,8 +368,6 @@
         if(t1.ordinal() < LvarType.INT.ordinal() || t2.ordinal() < LvarType.INT.ordinal()) {
             return LvarType.OBJECT;
         }
-        // NOTE: we allow "widening" of long to double even though it can lose precision. ECMAScript doesn't have an
-        // Int64 type anyway, so this loss of precision is actually more conformant to the specification...
         return LvarType.values()[Math.max(t1.ordinal(), t2.ordinal())];
     }
     private final Compiler compiler;
@@ -368,7 +375,10 @@
     // Local variable type mapping at the currently evaluated point. No map instance is ever modified; setLvarType() always
     // allocates a new map. Immutability of maps allows for cheap snapshots by just keeping the reference to the current
     // value.
-    private Map<Symbol, LvarType> localVariableTypes = new IdentityHashMap<>();
+    private Map<Symbol, LvarType> localVariableTypes = Collections.emptyMap();
+    // Set of symbols whose lexical scope has already ended.
+    private final Set<Symbol> invalidatedSymbols = new HashSet<>();
+
     // Stack for evaluated expression types.
     private final Deque<LvarType> typeStack = new ArrayDeque<>();
 
@@ -464,9 +474,19 @@
 
     @Override
     public boolean enterBlock(final Block block) {
+        boolean cloned = false;
         for(final Symbol symbol: block.getSymbols()) {
-            if(symbol.isBytecodeLocal() && getLocalVariableTypeOrNull(symbol) == null) {
-                setType(symbol, LvarType.UNDEFINED);
+            if(symbol.isBytecodeLocal()) {
+                if (getLocalVariableTypeOrNull(symbol) == null) {
+                    if (!cloned) {
+                        cloneOrNewLocalVariableTypes();
+                        cloned = true;
+                    }
+                    localVariableTypes.put(symbol, LvarType.UNDEFINED);
+                }
+                // In case we're repeating analysis of a lexical scope (e.g. it's in a loop),
+                // make sure all symbols lexically scoped by the block become valid again.
+                invalidatedSymbols.remove(symbol);
             }
         }
         return true;
@@ -1046,15 +1066,11 @@
             // throw an exception.
             reachable = true;
             catchBody.accept(this);
-            final Symbol exceptionSymbol = exception.getSymbol();
             if(reachable) {
-                localVariableTypes = cloneMap(localVariableTypes);
-                localVariableTypes.remove(exceptionSymbol);
                 jumpToLabel(catchBody, endLabel);
                 canExit = true;
             }
-            localVariableTypes = cloneMap(afterConditionTypes);
-            localVariableTypes.remove(exceptionSymbol);
+            localVariableTypes = afterConditionTypes;
         }
         // NOTE: if we had one or more conditional catch blocks with no unconditional catch block following them, then
         // there will be an unconditional rethrow, so the join point can never be reached from the last
@@ -1204,7 +1220,7 @@
     }
 
     private void jumpToLabel(final JoinPredecessor jumpOrigin, final Label label, final Map<Symbol, LvarType> types) {
-        getOrCreateJumpTarget(label).addOrigin(jumpOrigin, types);
+        getOrCreateJumpTarget(label).addOrigin(jumpOrigin, types, this);
     }
 
     @Override
@@ -1226,16 +1242,18 @@
 
         boolean cloned = false;
         for(final Symbol symbol: block.getSymbols()) {
-            // Undefine the symbol outside the block
-            if(localVariableTypes.containsKey(symbol)) {
-                if(!cloned) {
-                    localVariableTypes = cloneMap(localVariableTypes);
-                    cloned = true;
-                }
-                localVariableTypes.remove(symbol);
-            }
-
             if(symbol.hasSlot()) {
+                // Invalidate the symbol when its defining block ends
+                if (symbol.isBytecodeLocal()) {
+                    if(localVariableTypes.containsKey(symbol)) {
+                        if(!cloned) {
+                            localVariableTypes = cloneMap(localVariableTypes);
+                            cloned = true;
+                        }
+                    }
+                    invalidateSymbol(symbol);
+                }
+
                 final SymbolConversions conversions = symbolConversions.get(symbol);
                 if(conversions != null) {
                     // Potentially make some currently dead types live if they're needed as a source of a type
@@ -1605,10 +1623,19 @@
         }
         assert symbol.hasSlot();
         assert !symbol.isGlobal();
-        localVariableTypes = localVariableTypes.isEmpty() ? new IdentityHashMap<Symbol, LvarType>() : cloneMap(localVariableTypes);
+        cloneOrNewLocalVariableTypes();
         localVariableTypes.put(symbol, type);
     }
 
+    private void cloneOrNewLocalVariableTypes() {
+        localVariableTypes = localVariableTypes.isEmpty() ? new HashMap<Symbol, LvarType>() : cloneMap(localVariableTypes);
+    }
+
+    private void invalidateSymbol(final Symbol symbol) {
+        localVariableTypes.remove(symbol);
+        invalidatedSymbols.add(symbol);
+    }
+
     /**
      * Set a flag in the symbol marking it as needing to be able to store a value of a particular type. Every symbol for
      * a local variable will be assigned between 1 and 6 local variable slots for storing all types it is known to need
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java
index 3783ad8..22dc72e 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java
@@ -188,7 +188,8 @@
 
     @Override
     protected void loadValue(final Expression expr, final Type type) {
-        codegen.loadExpressionAsType(expr, type);
+        // Use generic type in order to avoid conversion between object types
+        codegen.loadExpressionAsType(expr, Type.generic(type));
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java b/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java
index 494afb4..94048f7 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java
@@ -77,6 +77,7 @@
     static final long CALL_WEIGHT      = 10;
     static final long CATCH_WEIGHT     = 10;
     static final long COMPARE_WEIGHT   =  6;
+    static final long CONST_WEIGHT     =  2;
     static final long CONTINUE_WEIGHT  =  1;
     static final long IF_WEIGHT        =  2;
     static final long LITERAL_WEIGHT   = 10;
@@ -185,7 +186,7 @@
 
     @Override
     public Node leaveIdentNode(final IdentNode identNode) {
-        weight += ACCESS_WEIGHT + identNode.getName().length() * 2;
+        weight += ACCESS_WEIGHT;
         return identNode;
     }
 
@@ -210,6 +211,11 @@
     @SuppressWarnings("rawtypes")
     @Override
     public boolean enterLiteralNode(final LiteralNode literalNode) {
+        if (literalNode instanceof LiteralNode.PrimitiveLiteralNode) {
+            weight += CONST_WEIGHT;
+            return false;
+        }
+
         weight += LITERAL_WEIGHT;
 
         if (literalNode instanceof ArrayLiteralNode) {
diff --git a/nashorn/src/jdk/nashorn/internal/ir/debug/PrintVisitor.java b/nashorn/src/jdk/nashorn/internal/ir/debug/PrintVisitor.java
index bb8d61a..fccad15 100644
--- a/nashorn/src/jdk/nashorn/internal/ir/debug/PrintVisitor.java
+++ b/nashorn/src/jdk/nashorn/internal/ir/debug/PrintVisitor.java
@@ -397,7 +397,7 @@
 
     @Override
     public boolean enterVarNode(final VarNode varNode) {
-        sb.append("var ");
+        sb.append(varNode.isConst() ? "const " : varNode.isLet() ? "let " : "var ");
         varNode.getName().toString(sb, printTypes);
         printLocalVariableConversion(varNode.getName());
         final Node init = varNode.getInit();
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeDataView.java b/nashorn/src/jdk/nashorn/internal/objects/NativeDataView.java
index 44d0606..759c168 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeDataView.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDataView.java
@@ -416,7 +416,7 @@
      * @return 32-bit unsigned int value at the byteOffset
      */
     @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
-    public static long getUint32(final Object self, final Object byteOffset, final Object littleEndian) {
+    public static double getUint32(final Object self, final Object byteOffset, final Object littleEndian) {
         try {
             return 0xFFFFFFFFL & getBuffer(self, littleEndian).getInt(JSType.toInt32(byteOffset));
         } catch (final IllegalArgumentException iae) {
@@ -432,7 +432,7 @@
      * @return 32-bit unsigned int value at the byteOffset
      */
     @SpecializedFunction
-    public static long getUint32(final Object self, final int byteOffset) {
+    public static double getUint32(final Object self, final int byteOffset) {
         try {
             return JSType.toUint32(getBuffer(self, false).getInt(JSType.toInt32(byteOffset)));
         } catch (final IllegalArgumentException iae) {
@@ -449,7 +449,7 @@
      * @return 32-bit unsigned int value at the byteOffset
      */
     @SpecializedFunction
-    public static long getUint32(final Object self, final int byteOffset, final boolean littleEndian) {
+    public static double getUint32(final Object self, final int byteOffset, final boolean littleEndian) {
         try {
             return JSType.toUint32(getBuffer(self, littleEndian).getInt(JSType.toInt32(byteOffset)));
         } catch (final IllegalArgumentException iae) {
@@ -837,9 +837,9 @@
      * @return undefined
      */
     @SpecializedFunction
-    public static Object setUint32(final Object self, final int byteOffset, final long value) {
+    public static Object setUint32(final Object self, final int byteOffset, final double value) {
         try {
-            getBuffer(self, false).putInt(byteOffset, (int)value);
+            getBuffer(self, false).putInt(byteOffset, (int) JSType.toUint32(value));
             return UNDEFINED;
         } catch (final IllegalArgumentException iae) {
             throw rangeError(iae, "dataview.offset");
@@ -856,9 +856,9 @@
      * @return undefined
      */
     @SpecializedFunction
-    public static Object setUint32(final Object self, final int byteOffset, final long value, final boolean littleEndian) {
+    public static Object setUint32(final Object self, final int byteOffset, final double value, final boolean littleEndian) {
         try {
-            getBuffer(self, littleEndian).putInt(byteOffset, (int)value);
+            getBuffer(self, littleEndian).putInt(byteOffset, (int) JSType.toUint32(value));
             return UNDEFINED;
         } catch (final IllegalArgumentException iae) {
             throw rangeError(iae, "dataview.offset");
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
index 9ca599c..89e5cb5 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
@@ -457,6 +457,8 @@
             return toPrimitive((ScriptObject)obj, hint);
         } else if (isPrimitive(obj)) {
             return obj;
+        } else if (hint == Number.class && obj instanceof Number) {
+            return ((Number) obj).doubleValue();
         } else if (obj instanceof JSObject) {
             return toPrimitive((JSObject)obj, hint);
         } else if (obj instanceof StaticClass) {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayData.java
index 331a8f5..7966659 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayData.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayData.java
@@ -107,14 +107,13 @@
 
         @Override
         public ArrayData ensure(final long safeIndex) {
-            if (safeIndex > 0L) {
-                if (safeIndex >= SparseArrayData.MAX_DENSE_LENGTH) {
-                    return new SparseArrayData(this, safeIndex + 1);
-                }
-                //known to fit in int
-                return toRealArrayData((int)safeIndex);
-           }
-           return this;
+            assert safeIndex >= 0L;
+            if (safeIndex >= SparseArrayData.MAX_DENSE_LENGTH) {
+                return new SparseArrayData(this, safeIndex + 1);
+            }
+            //known to fit in int
+            return toRealArrayData((int)safeIndex);
+
         }
 
         @Override
@@ -133,8 +132,8 @@
         }
 
         @Override
-        public void shiftLeft(final int by) {
-            //nop, always empty or we wouldn't be of this class
+        public ArrayData shiftLeft(final int by) {
+            return this; //nop, always empty or we wouldn't be of this class
         }
 
         @Override
@@ -451,13 +450,13 @@
     /**
      * Shift the array data left
      *
-     * TODO: explore start at an index and not at zero, to make these operations
-     * even faster. Offset everything from the index. Costs memory but is probably
-     * worth it
+     * TODO: This is used for Array.prototype.shift() which only shifts by 1,
+     * so we might consider dropping the offset parameter.
      *
      * @param by offset to shift
+     * @return New arraydata (or same)
      */
-    public abstract void shiftLeft(final int by);
+    public abstract ArrayData shiftLeft(final int by);
 
     /**
      * Shift the array right
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayFilter.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayFilter.java
index 19ecec2..47e6454 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayFilter.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayFilter.java
@@ -68,9 +68,10 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
+    public ArrayData shiftLeft(final int by) {
         underlying.shiftLeft(by);
         setLength(underlying.length());
+        return this;
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ByteBufferArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ByteBufferArrayData.java
index f18b4a4..2b03265 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ByteBufferArrayData.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ByteBufferArrayData.java
@@ -82,7 +82,7 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
+    public ArrayData shiftLeft(final int by) {
         throw unsupported("shiftLeft");
     }
 
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/DeletedArrayFilter.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/DeletedArrayFilter.java
index bd706c7..62e1ced 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/DeletedArrayFilter.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/DeletedArrayFilter.java
@@ -76,9 +76,10 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
+    public ArrayData shiftLeft(final int by) {
         super.shiftLeft(by);
         deleted.shiftLeft(by, length());
+        return this;
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/DeletedRangeArrayFilter.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/DeletedRangeArrayFilter.java
index 7a6f098..d471031 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/DeletedRangeArrayFilter.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/DeletedRangeArrayFilter.java
@@ -101,10 +101,12 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
+    public ArrayData shiftLeft(final int by) {
         super.shiftLeft(by);
         lo = Math.max(0, lo - by);
         hi = Math.max(-1, hi - by);
+
+        return isEmpty() ? getUnderlying() : this;
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/IntArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/IntArrayData.java
index b157e09..0f7d245 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/IntArrayData.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/IntArrayData.java
@@ -176,8 +176,15 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
-        System.arraycopy(array, by, array, 0, array.length - by);
+    public ArrayData shiftLeft(final int by) {
+        if (by >= length()) {
+            shrink(0);
+        } else {
+            System.arraycopy(array, by, array, 0, array.length - by);
+        }
+        setLength(Math.max(0, length() - by));
+
+        return this;
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java
index 7276b9a..9f3e866 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java
@@ -121,8 +121,14 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
-        System.arraycopy(array, by, array, 0, array.length - by);
+    public ArrayData shiftLeft(final int by) {
+        if (by >= length()) {
+            shrink(0);
+        } else {
+            System.arraycopy(array, by, array, 0, array.length - by);
+        }
+        setLength(Math.max(0, length() - by));
+        return this;
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
index cb99de8..027bd6b 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
@@ -98,8 +98,14 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
-        System.arraycopy(array, by, array, 0, array.length - by);
+    public ArrayData shiftLeft(final int by) {
+        if (by >= length()) {
+            shrink(0);
+        } else {
+            System.arraycopy(array, by, array, 0, array.length - by);
+        }
+        setLength(Math.max(0, length() - by));
+        return this;
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java
index 4d32bd4..26d89d4 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java
@@ -36,7 +36,8 @@
  * Handle arrays where the index is very large.
  */
 class SparseArrayData extends ArrayData {
-    static final int MAX_DENSE_LENGTH = 1024 * 1024;
+    /** Maximum size for dense arrays */
+    static final int MAX_DENSE_LENGTH = 128 * 1024;
 
     /** Underlying array. */
     private ArrayData underlying;
@@ -51,11 +52,11 @@
         this(underlying, length, new TreeMap<Long, Object>());
     }
 
-    SparseArrayData(final ArrayData underlying, final long length, final TreeMap<Long, Object> sparseMap) {
+    private SparseArrayData(final ArrayData underlying, final long length, final TreeMap<Long, Object> sparseMap) {
         super(length);
         assert underlying.length() <= length;
         this.underlying = underlying;
-        this.maxDenseLength = Math.max(MAX_DENSE_LENGTH, underlying.length());
+        this.maxDenseLength = underlying.length();
         this.sparseMap = sparseMap;
     }
 
@@ -89,38 +90,49 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
-        underlying.shiftLeft(by);
+    public ArrayData shiftLeft(final int by) {
+        underlying = underlying.shiftLeft(by);
 
         final TreeMap<Long, Object> newSparseMap = new TreeMap<>();
 
         for (final Map.Entry<Long, Object> entry : sparseMap.entrySet()) {
             final long newIndex = entry.getKey().longValue() - by;
-            if (newIndex < maxDenseLength) {
-                underlying = underlying.set((int) newIndex, entry.getValue(), false);
-            } else if (newIndex >= 0) {
-                newSparseMap.put(Long.valueOf(newIndex), entry.getValue());
+            if (newIndex >= 0) {
+                if (newIndex < maxDenseLength) {
+                    final long oldLength = underlying.length();
+                    underlying = underlying.ensure(newIndex)
+                            .set((int) newIndex, entry.getValue(), false)
+                            .safeDelete(oldLength, newIndex - 1, false);
+                } else {
+                    newSparseMap.put(Long.valueOf(newIndex), entry.getValue());
+                }
             }
         }
 
         sparseMap = newSparseMap;
         setLength(Math.max(length() - by, 0));
+
+        return sparseMap.isEmpty() ? underlying : this;
     }
 
     @Override
     public ArrayData shiftRight(final int by) {
         final TreeMap<Long, Object> newSparseMap = new TreeMap<>();
+        // Move elements from underlying to sparse map if necessary
         final long len = underlying.length();
         if (len + by > maxDenseLength) {
-            for (long i = maxDenseLength - by; i < len; i++) {
+            // Length of underlying array after shrinking, before right-shifting
+            final long tempLength = Math.max(0, maxDenseLength - by);
+            for (long i = tempLength; i < len; i++) {
                 if (underlying.has((int) i)) {
                     newSparseMap.put(Long.valueOf(i + by), underlying.getObject((int) i));
                 }
             }
-            underlying = underlying.shrink((int) (maxDenseLength - by));
+            underlying = underlying.shrink((int) tempLength);
+            underlying.setLength(tempLength);
         }
 
-        underlying.shiftRight(by);
+        underlying = underlying.shiftRight(by);
 
         for (final Map.Entry<Long, Object> entry : sparseMap.entrySet()) {
             final long newIndex = entry.getKey().longValue() + by;
@@ -135,14 +147,6 @@
 
     @Override
     public ArrayData ensure(final long safeIndex) {
-        // Usually #ensure only needs to be called if safeIndex is greater or equal current length.
-        // SparseArrayData is an exception as an index smaller than our current length may still
-        // exceed the underlying ArrayData's capacity. Because of this, SparseArrayData invokes
-        // its ensure method internally in various places where other ArrayData subclasses don't,
-        // making it safe for outside uses to only call ensure(safeIndex) if safeIndex >= length.
-        if (safeIndex < maxDenseLength && underlying.length() <= safeIndex) {
-            underlying = underlying.ensure(safeIndex);
-        }
         if (safeIndex >= length()) {
             setLength(safeIndex + 1);
         }
@@ -167,8 +171,7 @@
     public ArrayData set(final int index, final Object value, final boolean strict) {
         if (index >= 0 && index < maxDenseLength) {
             final long oldLength = underlying.length();
-            ensure(index);
-            underlying = underlying.set(index, value, strict).safeDelete(oldLength, index - 1, strict);
+            underlying = underlying.ensure(index).set(index, value, strict).safeDelete(oldLength, index - 1, strict);
             setLength(Math.max(underlying.length(), length()));
         } else {
             final Long longIndex = indexToKey(index);
@@ -183,8 +186,7 @@
     public ArrayData set(final int index, final int value, final boolean strict) {
         if (index >= 0 && index < maxDenseLength) {
             final long oldLength = underlying.length();
-            ensure(index);
-            underlying = underlying.set(index, value, strict).safeDelete(oldLength, index - 1, strict);
+            underlying = underlying.ensure(index).set(index, value, strict).safeDelete(oldLength, index - 1, strict);
             setLength(Math.max(underlying.length(), length()));
         } else {
             final Long longIndex = indexToKey(index);
@@ -198,8 +200,7 @@
     public ArrayData set(final int index, final double value, final boolean strict) {
         if (index >= 0 && index < maxDenseLength) {
             final long oldLength = underlying.length();
-            ensure(index);
-            underlying = underlying.set(index, value, strict).safeDelete(oldLength, index - 1, strict);
+            underlying = underlying.ensure(index).set(index, value, strict).safeDelete(oldLength, index - 1, strict);
             setLength(Math.max(underlying.length(), length()));
         } else {
             final Long longIndex = indexToKey(index);
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/TypedArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/TypedArrayData.java
index 56b9157a..55e26b2 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/TypedArrayData.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/TypedArrayData.java
@@ -98,7 +98,7 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
+    public ArrayData shiftLeft(final int by) {
         throw new UnsupportedOperationException();
     }
 
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/UndefinedArrayFilter.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/UndefinedArrayFilter.java
index 977b9e9..c6b1bd9 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/UndefinedArrayFilter.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/UndefinedArrayFilter.java
@@ -77,9 +77,10 @@
     }
 
     @Override
-    public void shiftLeft(final int by) {
+    public ArrayData shiftLeft(final int by) {
         super.shiftLeft(by);
         undefined.shiftLeft(by, length());
+        return this;
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java
index e8e493b3..8de9197 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java
@@ -39,9 +39,13 @@
 import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
 import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
 import jdk.nashorn.api.scripting.JSObject;
+import jdk.nashorn.api.scripting.ScriptObjectMirror;
 import jdk.nashorn.internal.lookup.MethodHandleFactory;
 import jdk.nashorn.internal.lookup.MethodHandleFunctionality;
+import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.JSType;
+import jdk.nashorn.internal.runtime.ScriptRuntime;
+import jdk.nashorn.internal.objects.Global;
 
 /**
  * A Dynalink linker to handle web browser built-in JS (DOM etc.) objects as well
@@ -141,9 +145,9 @@
     }
 
     private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
-        MethodHandle mh = JSOBJECT_CALL;
+        MethodHandle mh = NashornCallSiteDescriptor.isScope(desc)? JSOBJECT_SCOPE_CALL : JSOBJECT_CALL;
         if (NashornCallSiteDescriptor.isApplyToCall(desc)) {
-            mh = MH.insertArguments(JSOBJECT_CALL_TO_APPLY, 0, JSOBJECT_CALL);
+            mh = MH.insertArguments(JSOBJECT_CALL_TO_APPLY, 0, mh);
         }
         final MethodType type = desc.getMethodType();
         mh = type.parameterType(type.parameterCount() - 1) == Object[].class ?
@@ -171,6 +175,8 @@
             final int index = getIndex((Number)key);
             if (index > -1) {
                 return ((JSObject)jsobj).getSlot(index);
+            } else {
+                return ((JSObject)jsobj).getMember(JSType.toString(key));
             }
         } else if (isString(key)) {
             final String name = key.toString();
@@ -188,7 +194,12 @@
         if (key instanceof Integer) {
             ((JSObject)jsobj).setSlot((Integer)key, value);
         } else if (key instanceof Number) {
-            ((JSObject)jsobj).setSlot(getIndex((Number)key), value);
+            final int index = getIndex((Number)key);
+            if (index > -1) {
+                ((JSObject)jsobj).setSlot(index, value);
+            } else {
+                ((JSObject)jsobj).setMember(JSType.toString(key), value);
+            }
         } else if (isString(key)) {
             ((JSObject)jsobj).setMember(key.toString(), value);
         }
@@ -214,6 +225,19 @@
         }
     }
 
+    // This is used when a JSObject is called as scope call to do undefined -> Global this translation.
+    @SuppressWarnings("unused")
+    private static Object jsObjectScopeCall(final JSObject jsObj, final Object thiz, final Object[] args) {
+        final Object modifiedThiz;
+        if (thiz == ScriptRuntime.UNDEFINED && !jsObj.isStrictFunction()) {
+            final Global global = Context.getGlobal();
+            modifiedThiz = ScriptObjectMirror.wrap(global, global);
+        } else {
+            modifiedThiz = thiz;
+        }
+        return jsObj.call(modifiedThiz, args);
+    }
+
     private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
 
     // method handles of the current class
@@ -225,6 +249,7 @@
     private static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class);
     private static final MethodHandle JSOBJECT_SETMEMBER     = findJSObjectMH_V("setMember", Void.TYPE, String.class, Object.class);
     private static final MethodHandle JSOBJECT_CALL          = findJSObjectMH_V("call", Object.class, Object.class, Object[].class);
+    private static final MethodHandle JSOBJECT_SCOPE_CALL    = findOwnMH_S("jsObjectScopeCall", Object.class, JSObject.class, Object.class, Object[].class);
     private static final MethodHandle JSOBJECT_CALL_TO_APPLY = findOwnMH_S("callToApply", Object.class, MethodHandle.class, JSObject.class, Object.class, Object[].class);
     private static final MethodHandle JSOBJECT_NEW           = findJSObjectMH_V("newObject", Object.class, Object[].class);
 
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornLinker.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornLinker.java
index ddcbae1..b8e01ff 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornLinker.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornLinker.java
@@ -251,15 +251,15 @@
     @Override
     public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) {
         if(sourceType == NativeArray.class) {
-            // Prefer lists, as they're less costly to create than arrays.
-            if(isList(targetType1)) {
-                if(!isList(targetType2)) {
+            // Prefer those types we can convert to with just a wrapper (cheaper than Java array creation).
+            if(isArrayPreferredTarget(targetType1)) {
+                if(!isArrayPreferredTarget(targetType2)) {
                     return Comparison.TYPE_1_BETTER;
                 }
-            } else if(isList(targetType2)) {
+            } else if(isArrayPreferredTarget(targetType2)) {
                 return Comparison.TYPE_2_BETTER;
             }
-            // Then prefer arrays
+            // Then prefer Java arrays
             if(targetType1.isArray()) {
                 if(!targetType2.isArray()) {
                     return Comparison.TYPE_1_BETTER;
@@ -281,8 +281,8 @@
         return Comparison.INDETERMINATE;
     }
 
-    private static boolean isList(final Class<?> clazz) {
-        return clazz == List.class || clazz == Deque.class;
+    private static boolean isArrayPreferredTarget(final Class<?> clazz) {
+        return clazz == List.class || clazz == Collection.class || clazz == Queue.class || clazz == Deque.class;
     }
 
     private static final MethodHandle IS_SCRIPT_OBJECT = Guards.isInstance(ScriptObject.class, MH.type(Boolean.TYPE, Object.class));
diff --git a/nashorn/test/script/basic/JDK-8030182_2.js b/nashorn/test/script/basic/JDK-8030182_2.js
index 4c2f5c4..4b563de 100644
--- a/nashorn/test/script/basic/JDK-8030182_2.js
+++ b/nashorn/test/script/basic/JDK-8030182_2.js
@@ -31,7 +31,7 @@
 var str = "";
 
 // large code to force splitting
-for (i = 0; i < 1000; ++i)
+for (i = 0; i < 2000; ++i)
     str +="o = new Object()\n";
 
 str +="g()";
diff --git a/nashorn/test/script/basic/JDK-8163945.js b/nashorn/test/script/basic/JDK-8163945.js
new file mode 100644
index 0000000..781dd94
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8163945.js
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8163945: Honor Number type hint in toPrimitive on Numbers
+ *
+ * @test
+ * @run
+ */
+
+function assertLessThan(a, b) {
+    Assert.assertTrue(a < b);
+    Assert.assertTrue(a <= b);
+    Assert.assertFalse(a >= b);
+    Assert.assertFalse(a > b);
+}
+
+assertLessThan(new java.lang.Long(2), new java.lang.Long(10));
+assertLessThan(new java.lang.Long(2), 10);
+assertLessThan(2, new java.lang.Long(10));
+
+assertLessThan(new java.math.BigInteger(2), new java.math.BigInteger(10));
+assertLessThan(new java.math.BigInteger(2), 10);
+assertLessThan(2, new java.math.BigInteger(10));
+
+assertLessThan(new java.util.concurrent.atomic.AtomicInteger(2), new java.util.concurrent.atomic.AtomicInteger(10));
+assertLessThan(new java.util.concurrent.atomic.AtomicInteger(2), 10);
+assertLessThan(2, new java.util.concurrent.atomic.AtomicInteger(10));
diff --git a/nashorn/test/script/basic/JDK-8166902.js b/nashorn/test/script/basic/JDK-8166902.js
new file mode 100644
index 0000000..fb16450
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8166902.js
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * 
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ * 
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ * 
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ * 
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8166902: Nested object literal property maps not reset in optimistic recompilation
+ *
+ * @test
+ * @run
+ */
+
+var o = {
+    a: "A",
+    b: "B"
+};
+
+var m = {
+    x: { z: o.a },
+    y: o.b
+};
+
+Assert.assertEquals(m.x.z, "A");
+Assert.assertEquals(m.y, "B");
+
diff --git a/nashorn/test/script/basic/JDK-8170594.js b/nashorn/test/script/basic/JDK-8170594.js
new file mode 100644
index 0000000..6365500
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8170594.js
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * 
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ * 
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ * 
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ * 
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8170594: >>>=0 generates invalid bytecode for BaseNode LHS
+ *
+ * @test
+ * @run
+ */
+
+var obj1 = {x: "100"};
+(function (o, p) {
+ if (p) {
+   o.x >>>= 0;
+ }
+})(obj1, true)
+Assert.assertTrue(obj1.x === 100)
+
+var obj2 = ["100"];
+(function (o, p) {
+ if (p) {
+   o[0] >>>= 0;
+ }
+})(obj2, true)
+Assert.assertTrue(obj2[0] === 100)
diff --git a/nashorn/test/script/basic/JDK-8171219.js b/nashorn/test/script/basic/JDK-8171219.js
new file mode 100644
index 0000000..6c1cf72
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8171219.js
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * 
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ * 
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ * 
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ * 
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8171219: Missing checks in sparse array shift() implementation
+ *
+ * @test
+ * @run
+ */
+
+var a = [];
+a[1048577] = 1;
+a.shift();
+a[1] = 2;
+a.shift();
+var ka = Object.keys(a);
+Assert.assertTrue(ka.length === 2);
+Assert.assertTrue(ka[0] === '0');
+Assert.assertTrue(ka[1] === '1048575');
+Assert.assertTrue(a.length === 1048576);
+Assert.assertTrue(a[0] === 2);
+Assert.assertTrue(a[1048575] = 1);
+
+var b = [];
+b[1048577] = 1;
+b.unshift(2);
+b.shift();
+b[1] = 3;
+b.shift();
+var kb = Object.keys(b);
+Assert.assertTrue(kb.length === 2);
+Assert.assertTrue(kb[0] === '0');
+Assert.assertTrue(kb[1] === '1048576');
+Assert.assertTrue(b.length === 1048577);
+Assert.assertTrue(b[0] === 3);
+Assert.assertTrue(b[1048576] = 1);
+
diff --git a/nashorn/test/script/basic/JDK-8171849.js b/nashorn/test/script/basic/JDK-8171849.js
new file mode 100644
index 0000000..febc97c
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8171849.js
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * 
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ * 
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ * 
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ * 
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8171849: Collection and Queue conversions not prioritized for Arrays
+ *
+ * @test
+ * @run
+ */
+
+var acp = new (Java.type("jdk.nashorn.test.models.ArrayConversionPreferences"))
+
+var a = [1, "", {}]
+
+Assert.assertTrue(acp.testCollectionOverMap(a))
+Assert.assertTrue(acp.testCollectionOverArray(a))
+Assert.assertTrue(acp.testListOverMap(a))
+Assert.assertTrue(acp.testListOverArray(a))
+Assert.assertTrue(acp.testListOverCollection(a))
+Assert.assertTrue(acp.testQueueOverMap(a))
+Assert.assertTrue(acp.testQueueOverArray(a))
+Assert.assertTrue(acp.testQueueOverCollection(a))
+Assert.assertTrue(acp.testDequeOverMap(a))
+Assert.assertTrue(acp.testDequeOverArray(a))
+Assert.assertTrue(acp.testDequeOverCollection(a))
+Assert.assertTrue(acp.testDequeOverQueue(a))
+Assert.assertTrue(acp.testArrayOverMap(a))
diff --git a/nashorn/test/script/basic/JDK-8176511.js b/nashorn/test/script/basic/JDK-8176511.js
new file mode 100644
index 0000000..08fbd55
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8176511.js
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2017, 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-8176511: JSObject property access is broken for numeric keys outside the int range
+ *
+ * @test
+ * @run
+ */
+
+
+var reassignWithNewGlobal = loadWithNewGlobal({
+    script: '(function (o, i) { o[i] = o[i]; })', name: 'internal.js'
+
+});
+
+function test(i) {
+    var o = {};
+    o[i] = true;
+    var before = JSON.stringify(o);
+    reassignWithNewGlobal(o, i);
+    var after = JSON.stringify(o);
+    Assert.assertEquals(before, after);
+}
+
+test(-2147483649);
+test(-2147483648);
+test(2147483647);
+test(2147483648);
+
diff --git a/nashorn/test/script/basic/JDK-8181191.js b/nashorn/test/script/basic/JDK-8181191.js
new file mode 100644
index 0000000..4f4ef49
--- /dev/null
+++ b/nashorn/test/script/basic/JDK-8181191.js
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2017, 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-8181191: getUint32 returning Long
+ *
+ * @test
+ * @run
+ */
+
+
+function uint32(x) {
+    var buffer = new ArrayBuffer(16);
+    var dataview = new DataView(buffer);
+    dataview.setUint32(0, x);
+    return dataview.getUint32(0);
+}
+
+Assert.assertTrue(typeof uint32(0x7f) === 'number');
+Assert.assertTrue(typeof uint32(0x80) === 'number');
+Assert.assertTrue(typeof uint32(0xffffffff) === 'number');
+Assert.assertTrue(typeof uint32(0x100000000) === 'number');
+
+Assert.assertTrue(uint32(0x7f) === 0x7f);
+Assert.assertTrue(uint32(0x80) === 0x80);
+Assert.assertTrue(uint32(0xffffffff) === 0xffffffff);
+Assert.assertTrue(uint32(0x100000000) === 0x0);
+
+Assert.assertTrue(uint32(0x7f) === uint32(0x7f));
+Assert.assertTrue(uint32(0x80) === uint32(0x80));
+Assert.assertTrue(uint32(0xffffffff) === uint32(0xffffffff));
+Assert.assertTrue(uint32(0x100000000) === uint32(0x100000000));
diff --git a/nashorn/test/script/basic/es6/JDK-8168373.js b/nashorn/test/script/basic/es6/JDK-8168373.js
new file mode 100644
index 0000000..af26e73
--- /dev/null
+++ b/nashorn/test/script/basic/es6/JDK-8168373.js
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * 
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ * 
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ * 
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ * 
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8168373: don't emit conversions for symbols outside their lexical scope
+ *
+ * @test
+ * @run
+ * @option --language=es6
+ */
+
+function p() { return false } // "predicate"
+function r(x) { return x } // "read"
+
+(function() {
+  try { // Try creates control flow edges from assignments into catch blocks.
+    // Lexically scoped, never read int variable (undefined at catch block) but still with a cf edge into catch block.
+    // Since it's never read, it's not written either (Nashorn optimizes some dead writes).
+    let x = 0; 
+    if (p()) { throw {}; } // We need `p()` so this block doesn't get optimized away, for possibility of a `throw` 
+    x = 0.0; // change the type of x to double
+    r(x); // read x otherwise it's optimized away
+  } catch (e) {} // under the bug, "throw" will try to widen unwritten int x to double for here and cause a verifier error
+})()
diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptObjectMirrorTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptObjectMirrorTest.java
index f9c78fc..7656dc6 100644
--- a/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptObjectMirrorTest.java
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptObjectMirrorTest.java
@@ -41,6 +41,7 @@
 import javax.script.ScriptEngine;
 import javax.script.ScriptEngineManager;
 import javax.script.ScriptException;
+import jdk.nashorn.api.scripting.AbstractJSObject;
 import jdk.nashorn.api.scripting.JSObject;
 import jdk.nashorn.api.scripting.ScriptObjectMirror;
 import org.testng.annotations.Test;
@@ -386,4 +387,41 @@
         assertTrue(func.isFunction());
         assertEquals(func.call(e.eval("this"), "hello"), "hello world");
     }
+
+    // @bug 8170565: JSObject call() is passed undefined for the argument 'thiz'
+    @Test
+    public void jsObjectThisTest() throws Exception {
+        final ScriptEngineManager engineManager = new ScriptEngineManager();
+        final ScriptEngine e = engineManager.getEngineByName("nashorn");
+        e.put("func", new AbstractJSObject() {
+            @Override
+            public boolean isFunction() { return true; }
+
+            @Override
+            public Object call(Object thiz, Object...args) {
+                return thiz;
+            }
+        });
+
+        assertTrue((boolean)e.eval("func() === this"));
+
+        // check that there is no blind undefined->Global translation!
+        assertTrue((boolean)e.eval("typeof(Function.prototype.call.call(func, undefined)) == 'undefined'"));
+
+        // make sure that strict functions don't get translated this for scope calls!
+        e.put("sfunc", new AbstractJSObject() {
+            @Override
+            public boolean isFunction() { return true; }
+
+            @Override
+            public boolean isStrictFunction() { return true; }
+
+            @Override
+            public Object call(Object thiz, Object...args) {
+                return thiz;
+            }
+        });
+
+        assertTrue((boolean)e.eval("typeof sfunc() == 'undefined'"));
+    }
 }
diff --git a/nashorn/test/src/jdk/nashorn/test/models/ArrayConversionPreferences.java b/nashorn/test/src/jdk/nashorn/test/models/ArrayConversionPreferences.java
new file mode 100644
index 0000000..a88f3c3
--- /dev/null
+++ b/nashorn/test/src/jdk/nashorn/test/models/ArrayConversionPreferences.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  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 jdk.nashorn.test.models;
+
+import java.util.Collection;
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+
+public class ArrayConversionPreferences {
+    public boolean testCollectionOverMap(final Collection x) { return true; }
+    public boolean testCollectionOverMap(final Map x) { return false; }
+
+    public boolean testCollectionOverArray(final Collection x) { return true; }
+    public boolean testCollectionOverArray(final Object[] x) { return false; }
+
+    public boolean testListOverMap(final List x) { return true; }
+    public boolean testListOverMap(final Map x) { return false; }
+
+    public boolean testListOverArray(final List x) { return true; }
+    public boolean testListOverArray(final Object[] x) { return false; }
+
+    public boolean testListOverCollection(final List x) { return true; }
+    public boolean testListOverCollection(final Collection x) { return false; }
+
+    public boolean testQueueOverMap(final Queue x) { return true; }
+    public boolean testQueueOverMap(final Map x) { return false; }
+
+    public boolean testQueueOverArray(final Queue x) { return true; }
+    public boolean testQueueOverArray(final Object[] x) { return false; }
+
+    public boolean testQueueOverCollection(final Queue x) { return true; }
+    public boolean testQueueOverCollection(final Collection x) { return false; }
+
+    public boolean testDequeOverMap(final Deque x) { return true; }
+    public boolean testDequeOverMap(final Map x) { return false; }
+
+    public boolean testDequeOverArray(final Deque x) { return true; }
+    public boolean testDequeOverArray(final Object[] x) { return false; }
+
+    public boolean testDequeOverCollection(final Deque x) { return true; }
+    public boolean testDequeOverCollection(final Collection x) { return false; }
+
+    public boolean testDequeOverQueue(final Deque x) { return true; }
+    public boolean testDequeOverQueue(final Queue x) { return false; }
+
+    public boolean testArrayOverMap(final Object[] x) { return true; }
+    public boolean testArrayOverMap(final Map x) { return false; }
+}
+