changeset 26815:e42b578aa29e

Merge
author iklam
date Fri, 19 Sep 2014 13:47:19 -0700
parents c4aad88451f7 e9c76272cd40
children 11fbe62c7cd7
files hotspot/test/gc/class_unloading/AllocateBeyondMetaspaceSize.java hotspot/test/gc/g1/TestDeferredRSUpdate.java jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/api/util/ApClassLoader.java jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/api/util/ToolsJarNotFoundException.java jdk/make/gensrc/GensrcLocaleDataMetaInfo.gmk jdk/src/java.desktop/macosx/classes/sun/awt/datatransfer/flavormap.properties jdk/src/java.desktop/unix/classes/sun/awt/datatransfer/flavormap.properties jdk/src/java.desktop/windows/classes/sun/awt/datatransfer/flavormap.properties jdk/src/java.desktop/windows/classes/sun/awt/windows/WBufferStrategy.java jdk/src/java.desktop/windows/native/libawt/sun/java2d/d3d/D3DPipeline.cpp jdk/src/java.desktop/windows/native/libawt/sun/windows/WBufferStrategy.cpp jdk/src/java.security.jgss/share/classes/com/sun/security/jgss/AuthorizationDataEntry.java jdk/src/java.security.jgss/share/classes/com/sun/security/jgss/ExtendedGSSContext.java jdk/src/java.security.jgss/share/classes/com/sun/security/jgss/ExtendedGSSCredential.java jdk/src/java.security.jgss/share/classes/com/sun/security/jgss/GSSUtil.java jdk/src/java.security.jgss/share/classes/com/sun/security/jgss/InquireSecContextPermission.java jdk/src/java.security.jgss/share/classes/com/sun/security/jgss/InquireType.java jdk/src/java.security.jgss/share/classes/com/sun/security/jgss/package-info.java jdk/src/java.security.jgss/share/classes/com/sun/security/sasl/gsskerb/FactoryImpl.java jdk/src/java.security.jgss/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Base.java jdk/src/java.security.jgss/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Client.java jdk/src/java.security.jgss/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Server.java make/common/modules.list
diffstat 282 files changed, 10944 insertions(+), 4886 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Fri Sep 19 08:19:04 2014 -0400
+++ b/.hgtags	Fri Sep 19 13:47:19 2014 -0700
@@ -273,3 +273,4 @@
 f4269e8f454eb77763ecee228a88ae102a9aef6e jdk9-b28
 c36c0092693707a8255561433647e8c3cd724ccd jdk9-b29
 b2287cac7813c70ed7f679d9a46fe774bd4005f8 jdk9-b30
+9d0e6639a4d71b63507dd94b1a028e963b27e798 jdk9-b31
--- a/.hgtags-top-repo	Fri Sep 19 08:19:04 2014 -0400
+++ b/.hgtags-top-repo	Fri Sep 19 13:47:19 2014 -0700
@@ -273,3 +273,4 @@
 ea2f7981236f3812436958748ab3d26e80a35130 jdk9-b28
 9e6581aeda388a23fbee021fc33e6aa152a60657 jdk9-b29
 36e9bc875325813ac9c44ac0c617a463091fa9f5 jdk9-b30
+69a84c16d9c28e0e3d504b9c8766c24bafcd58f6 jdk9-b31
--- a/Makefile	Fri Sep 19 08:19:04 2014 -0400
+++ b/Makefile	Fri Sep 19 13:47:19 2014 -0700
@@ -70,8 +70,8 @@
   # Run the makefile with an arbitrary SPEC using -p -q (quiet dry-run and dump rules) to find
   # available PHONY targets. Use this list as valid targets to pass on to the repeated calls.
   all_phony_targets := $(sort $(filter-out $(global_targets), $(strip $(shell \
-      cd $(root_dir)/make && $(MAKE) -f Main.gmk -p -q FRC SPEC=$(firstword $(SPEC)) | \
-      grep "^.PHONY:" | head -n 1 | cut -d " " -f 2-))))
+      cd $(root_dir)/make && $(MAKE) -f Main.gmk -p -q FRC SPEC=$(firstword $(SPEC)) \
+      -I $(root_dir)/make/common | grep "^.PHONY:" | head -n 1 | cut -d " " -f 2-))))
 
   # Loop through the configurations and call the main-wrapper for each one. The wrapper
   # target will execute with a single configuration loaded.
@@ -115,12 +115,12 @@
 
     main-wrapper:
         ifneq ($(SEQUENTIAL_TARGETS), )
-	  (cd $(root_dir)/make && $(MAKE) -f Main.gmk SPEC=$(SPEC) -j 1 \
+	  (cd $(SRC_ROOT)/make && $(MAKE) -f Main.gmk SPEC=$(SPEC) -j 1 \
 	      $(VERBOSE) VERBOSE=$(VERBOSE) LOG_LEVEL=$(LOG_LEVEL) $(SEQUENTIAL_TARGETS))
         endif
         ifneq ($(PARALLEL_TARGETS), )
 	  @$(call AtMakeStart)
-	  (cd $(root_dir)/make && $(BUILD_LOG_WRAPPER) $(MAKE) -f Main.gmk SPEC=$(SPEC) -j $(JOBS) \
+	  (cd $(SRC_ROOT)/make && $(BUILD_LOG_WRAPPER) $(MAKE) -f Main.gmk SPEC=$(SPEC) -j $(JOBS) \
 	      $(VERBOSE) VERBOSE=$(VERBOSE) LOG_LEVEL=$(LOG_LEVEL) $(PARALLEL_TARGETS) \
 	      $(if $(filter true, $(OUTPUT_SYNC_SUPPORTED)), -O$(OUTPUT_SYNC)))
 	  @$(call AtMakeEnd)
--- a/common/autoconf/generated-configure.sh	Fri Sep 19 08:19:04 2014 -0400
+++ b/common/autoconf/generated-configure.sh	Fri Sep 19 13:47:19 2014 -0700
@@ -4327,7 +4327,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1410377275
+DATE_WHEN_GENERATED=1410791401
 
 ###############################################################################
 #
@@ -14642,7 +14642,7 @@
       FASTDEBUG="false"
       DEBUG_CLASSFILES="true"
       BUILD_VARIANT_RELEASE="-debug"
-      HOTSPOT_DEBUG_LEVEL="jvmg"
+      HOTSPOT_DEBUG_LEVEL="debug"
       HOTSPOT_EXPORT="debug"
       ;;
     optimized )
--- a/common/autoconf/hotspot-spec.gmk.in	Fri Sep 19 08:19:04 2014 -0400
+++ b/common/autoconf/hotspot-spec.gmk.in	Fri Sep 19 13:47:19 2014 -0700
@@ -97,8 +97,6 @@
 endif
 
 HOTSPOT_MAKE_ARGS:=@HOTSPOT_MAKE_ARGS@ @STATIC_CXX_SETTING@
-# This is used from the libjvm build for C/C++ code.
-HOTSPOT_BUILD_JOBS:=$(JOBS)
 # Control wether Hotspot runs Queens test after building
 TEST_IN_BUILD=@TEST_IN_BUILD@
 
--- a/common/autoconf/jdk-options.m4	Fri Sep 19 08:19:04 2014 -0400
+++ b/common/autoconf/jdk-options.m4	Fri Sep 19 13:47:19 2014 -0700
@@ -234,7 +234,7 @@
       FASTDEBUG="false"
       DEBUG_CLASSFILES="true"
       BUILD_VARIANT_RELEASE="-debug"
-      HOTSPOT_DEBUG_LEVEL="jvmg"
+      HOTSPOT_DEBUG_LEVEL="debug"
       HOTSPOT_EXPORT="debug"
       ;;
     optimized )
--- a/common/autoconf/spec.gmk.in	Fri Sep 19 08:19:04 2014 -0400
+++ b/common/autoconf/spec.gmk.in	Fri Sep 19 13:47:19 2014 -0700
@@ -245,6 +245,7 @@
 NASHORN_OUTPUTDIR=$(BUILD_OUTPUT)/nashorn
 IMAGES_OUTPUTDIR=$(BUILD_OUTPUT)/images
 TESTMAKE_OUTPUTDIR=$(BUILD_OUTPUT)/testmake
+MAKESUPPORT_OUTPUTDIR=$(BUILD_OUTPUT)/make-support
 
 LANGTOOLS_DIST=$(LANGTOOLS_OUTPUTDIR)/dist
 CORBA_DIST=$(CORBA_OUTPUTDIR)/dist
--- a/common/bin/unshuffle_list.txt	Fri Sep 19 08:19:04 2014 -0400
+++ b/common/bin/unshuffle_list.txt	Fri Sep 19 13:47:19 2014 -0700
@@ -1216,14 +1216,13 @@
 jdk/src/java.security.acl/share/classes/sun/security/acl : jdk/src/share/classes/sun/security/acl
 jdk/src/java.security.jgss/macosx/native/libosxkrb5/nativeccache.c : jdk/src/share/native/sun/security/krb5/nativeccache.c
 jdk/src/java.security.jgss/macosx/native/libosxkrb5/SCDynamicStoreConfig.m : jdk/src/macosx/native/sun/security/krb5/SCDynamicStoreConfig.m
-jdk/src/java.security.jgss/share/classes/com/sun/security/jgss : jdk/src/share/classes/com/sun/security/jgss
-jdk/src/java.security.jgss/share/classes/com/sun/security/sasl/gsskerb : jdk/src/share/classes/com/sun/security/sasl/gsskerb
 jdk/src/java.security.jgss/share/classes/javax/security/auth/kerberos : jdk/src/share/classes/javax/security/auth/kerberos
 jdk/src/java.security.jgss/share/classes/jgss-overview.html : jdk/src/share/classes/com/sun/security/jgss/jgss-overview.html
 jdk/src/java.security.jgss/share/classes/org/ietf/jgss : jdk/src/share/classes/org/ietf/jgss
 jdk/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego : jdk/src/share/classes/sun/net/www/protocol/http/spnego
 jdk/src/java.security.jgss/share/classes/sun/security/jgss : jdk/src/share/classes/sun/security/jgss
 jdk/src/java.security.jgss/share/classes/sun/security/krb5 : jdk/src/share/classes/sun/security/krb5
+jdk/src/java.security.jgss/windows/classes/sun/security/krb5 : jdk/src/windows/classes/sun/security/krb5
 jdk/src/java.security.jgss/share/classes/sun/security/ssl/krb5 : jdk/src/share/classes/sun/security/ssl/krb5
 jdk/src/java.security.jgss/share/native/libj2gss : jdk/src/share/native/sun/security/jgss/wrapper
 jdk/src/java.security.jgss/unix/native/libj2gss : jdk/src/solaris/native/sun/security/jgss/wrapper
@@ -1477,6 +1476,8 @@
 jdk/src/jdk.security.auth/share/classes/jaas-overview.html : jdk/src/share/classes/com/sun/security/auth/jaas-overview.html
 jdk/src/jdk.security.auth/unix/native/libjaas : jdk/src/solaris/native/com/sun/security/auth/module
 jdk/src/jdk.security.auth/windows/native/libjaas : jdk/src/windows/native/com/sun/security/auth/module
+jdk/src/jdk.security.jgss/share/classes/com/sun/security/jgss : jdk/src/share/classes/com/sun/security/jgss
+jdk/src/jdk.security.jgss/share/classes/com/sun/security/sasl/gsskerb : jdk/src/share/classes/com/sun/security/sasl/gsskerb
 jdk/src/jdk.snmp/share/classes/com/sun/jmx/snmp : jdk/src/share/classes/com/sun/jmx/snmp
 jdk/src/jdk.snmp/share/classes/sun/management/snmp : jdk/src/share/classes/sun/management/snmp
 jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs : jdk/src/share/classes/jdk/nio/zipfs
--- a/corba/.hgtags	Fri Sep 19 08:19:04 2014 -0400
+++ b/corba/.hgtags	Fri Sep 19 13:47:19 2014 -0700
@@ -273,3 +273,4 @@
 a00b04ef067e39f50b9a0fea6f1904e35d632a73 jdk9-b28
 163a9cd806fd09970baf1f5f42b92a3cfe7ee945 jdk9-b29
 98967ae6ae53ebf15615e07cd5a6b1ae04dfd84c jdk9-b30
+c432b80aadd0cb2b2361b02add4d671957d4cec9 jdk9-b31
--- a/hotspot/.hgtags	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/.hgtags	Fri Sep 19 13:47:19 2014 -0700
@@ -433,3 +433,4 @@
 657294869d7ff063e055f5492cab7ce5612ca851 jdk9-b28
 deb29e92f68ace2808a36ecfa18c7d61dcb645bb jdk9-b29
 5c722dffbc0f34eb8d903dca7b261e52248fa17e jdk9-b30
+9f7d155d28e519f3e4645dc21cf185c25f3176ed jdk9-b31
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java	Fri Sep 19 13:47:19 2014 -0700
@@ -107,7 +107,6 @@
   private Runtime1     runtime1;
   /** These constants come from globalDefinitions.hpp */
   private int          invocationEntryBCI;
-  private int          invalidOSREntryBCI;
   private ReversePtrs  revPtrs;
   private VMRegImpl    vmregImpl;
   private int          reserveForAllocationPrefetch;
@@ -295,7 +294,6 @@
 
     stackBias    = db.lookupIntConstant("STACK_BIAS").intValue();
     invocationEntryBCI = db.lookupIntConstant("InvocationEntryBci").intValue();
-    invalidOSREntryBCI = db.lookupIntConstant("InvalidOSREntryBci").intValue();
 
     // We infer the presence of C1 or C2 from a couple of fields we
     // already have present in the type database
@@ -733,11 +731,6 @@
     return invocationEntryBCI;
   }
 
-  /** FIXME: figure out where to stick this */
-  public int getInvalidOSREntryBCI() {
-    return invalidOSREntryBCI;
-  }
-
   // FIXME: figure out where to stick this
   public boolean wizardMode() {
     return true;
--- a/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -1166,9 +1166,9 @@
   beq(CCR0, overflow_with_error);
 
   // Has the nmethod been invalidated already?
-  lwz(Rtmp, nmethod::entry_bci_offset(), R3_RET);
-  cmpwi(CCR0, Rtmp, InvalidOSREntryBci);
-  beq(CCR0, overflow_with_error);
+  lbz(Rtmp, nmethod::state_offset(), R3_RET);
+  cmpwi(CCR0, Rtmp, nmethod::in_use);
+  bne(CCR0, overflow_with_error);
 
   // Migrate the interpreter frame off of the stack.
   // We can use all registers because we will not return to interpreter from this point.
--- a/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -1674,9 +1674,9 @@
       __ beq(CCR0, Lforward);
 
       // Has the nmethod been invalidated already?
-      __ lwz(R0, nmethod::entry_bci_offset(), R3_RET);
-      __ cmpwi(CCR0, R0, InvalidOSREntryBci);
-      __ beq(CCR0, Lforward);
+      __ lbz(R0, nmethod::state_offset(), R3_RET);
+      __ cmpwi(CCR0, R0, nmethod::in_use);
+      __ bne(CCR0, Lforward);
 
       // Migrate the interpreter frame off of the stack.
       // We can use all registers because we will not return to interpreter from this point.
--- a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -2407,8 +2407,8 @@
   br_null_short(O0, Assembler::pn, overflow_with_error);
 
   // Has the nmethod been invalidated already?
-  ld(O0, nmethod::entry_bci_offset(), O2);
-  cmp_and_br_short(O2, InvalidOSREntryBci, Assembler::equal, Assembler::pn, overflow_with_error);
+  ldub(O0, nmethod::state_offset(), O2);
+  cmp_and_br_short(O2, nmethod::in_use, Assembler::notEqual, Assembler::pn, overflow_with_error);
 
   // migrate the interpreter frame off of the stack
 
--- a/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -1636,8 +1636,8 @@
       __ br_null_short(O0, Assembler::pn, Lforward);
 
       // Has the nmethod been invalidated already?
-      __ ld(O0, nmethod::entry_bci_offset(), O2);
-      __ cmp_and_br_short(O2, InvalidOSREntryBci, Assembler::equal, Assembler::pn, Lforward);
+      __ ldub(O0, nmethod::state_offset(), O2);
+      __ cmp_and_br_short(O2, nmethod::in_use, Assembler::notEqual, Assembler::pn, Lforward);
 
       // migrate the interpreter frame off of the stack
 
--- a/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -1724,9 +1724,8 @@
       __ testptr(rax, rax);                      // test result
       __ jcc(Assembler::zero, dispatch);         // no osr if null
       // nmethod may have been invalidated (VM may block upon call_VM return)
-      __ movl(rcx, Address(rax, nmethod::entry_bci_offset()));
-      __ cmpl(rcx, InvalidOSREntryBci);
-      __ jcc(Assembler::equal, dispatch);
+      __ cmpb(Address(rax, nmethod::state_offset()), nmethod::in_use);
+      __ jcc(Assembler::notEqual, dispatch);
 
       // We have the address of an on stack replacement routine in rax,
       // We need to prepare to execute the OSR method. First we must
@@ -1734,8 +1733,7 @@
 
       __ mov(rbx, rax);                             // save the nmethod
 
-      const Register thread = rcx;
-      __ get_thread(thread);
+      __ get_thread(rcx);
       call_VM(noreg, CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_begin));
       // rax, is OSR buffer, move it to expected parameter location
       __ mov(rcx, rax);
--- a/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -1751,9 +1751,8 @@
       __ testptr(rax, rax);                        // test result
       __ jcc(Assembler::zero, dispatch);         // no osr if null
       // nmethod may have been invalidated (VM may block upon call_VM return)
-      __ movl(rcx, Address(rax, nmethod::entry_bci_offset()));
-      __ cmpl(rcx, InvalidOSREntryBci);
-      __ jcc(Assembler::equal, dispatch);
+      __ cmpb(Address(rax, nmethod::state_offset()), nmethod::in_use);
+      __ jcc(Assembler::notEqual, dispatch);
 
       // We have the address of an on stack replacement routine in eax
       // We need to prepare to execute the OSR method. First we must
--- a/hotspot/src/os/aix/vm/os_aix.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/os/aix/vm/os_aix.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -4002,10 +4002,6 @@
   return true;
 }
 
-// int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
-//   return ::vsnprintf(buf, count, format, args);
-// }
-
 // Is a (classpath) directory empty?
 bool os::dir_is_empty(const char* path) {
   DIR *dir = NULL;
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -3822,12 +3822,6 @@
   return true;
 }
 
-ATTRIBUTE_PRINTF(3, 0)
-int local_vsnprintf(char* buf, size_t count, const char* format,
-                    va_list args) {
-  return ::vsnprintf(buf, count, format, args);
-}
-
 // Is a (classpath) directory empty?
 bool os::dir_is_empty(const char* path) {
   DIR *dir = NULL;
--- a/hotspot/src/os/linux/vm/os_linux.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/os/linux/vm/os_linux.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -5063,11 +5063,6 @@
   return true;
 }
 
-int local_vsnprintf(char* buf, size_t count, const char* format,
-                    va_list args) {
-  return ::vsnprintf(buf, count, format, args);
-}
-
 // Is a (classpath) directory empty?
 bool os::dir_is_empty(const char* path) {
   DIR *dir = NULL;
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -2539,29 +2539,30 @@
   }
 }
 
+size_t os::Solaris::page_size_for_alignment(size_t alignment) {
+  assert(is_size_aligned(alignment, (size_t) vm_page_size()),
+         err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT,
+                 alignment, (size_t) vm_page_size()));
+
+  for (int i = 0; _page_sizes[i] != 0; i++) {
+    if (is_size_aligned(alignment, _page_sizes[i])) {
+      return _page_sizes[i];
+    }
+  }
+
+  return (size_t) vm_page_size();
+}
+
 int os::Solaris::commit_memory_impl(char* addr, size_t bytes,
                                     size_t alignment_hint, bool exec) {
   int err = Solaris::commit_memory_impl(addr, bytes, exec);
-  if (err == 0) {
-    if (UseLargePages && (alignment_hint > (size_t)vm_page_size())) {
-      // If the large page size has been set and the VM
-      // is using large pages, use the large page size
-      // if it is smaller than the alignment hint. This is
-      // a case where the VM wants to use a larger alignment size
-      // for its own reasons but still want to use large pages
-      // (which is what matters to setting the mpss range.
-      size_t page_size = 0;
-      if (large_page_size() < alignment_hint) {
-        assert(UseLargePages, "Expected to be here for large page use only");
-        page_size = large_page_size();
-      } else {
-        // If the alignment hint is less than the large page
-        // size, the VM wants a particular alignment (thus the hint)
-        // for internal reasons.  Try to set the mpss range using
-        // the alignment_hint.
-        page_size = alignment_hint;
-      }
-      // Since this is a hint, ignore any failures.
+  if (err == 0 && UseLargePages && alignment_hint > 0) {
+    assert(is_size_aligned(bytes, alignment_hint),
+           err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, alignment_hint));
+
+    // The syscall memcntl requires an exact page size (see man memcntl for details).
+    size_t page_size = page_size_for_alignment(alignment_hint);
+    if (page_size > (size_t) vm_page_size()) {
       (void)Solaris::setup_large_pages(addr, bytes, page_size);
     }
   }
@@ -3098,8 +3099,22 @@
   }
 }
 
-bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes,
-                                    size_t align) {
+bool os::Solaris::is_valid_page_size(size_t bytes) {
+  for (int i = 0; _page_sizes[i] != 0; i++) {
+    if (_page_sizes[i] == bytes) {
+      return true;
+    }
+  }
+  return false;
+}
+
+bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) {
+  assert(is_valid_page_size(align), err_msg(SIZE_FORMAT " is not a valid page size", align));
+  assert(is_ptr_aligned((void*) start, align),
+         err_msg(PTR_FORMAT " is not aligned to " SIZE_FORMAT, p2i((void*) start), align));
+  assert(is_size_aligned(bytes, align),
+         err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, align));
+
   // Signal to OS that we want large pages for addresses
   // from addr, addr + bytes
   struct memcntl_mha mpss_struct;
@@ -4769,29 +4784,6 @@
 
 bool os::check_heap(bool force) { return true; }
 
-typedef int (*vsnprintf_t)(char* buf, size_t count, const char* fmt, va_list argptr);
-static vsnprintf_t sol_vsnprintf = NULL;
-
-int local_vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr) {
-  if (!sol_vsnprintf) {
-    //search  for the named symbol in the objects that were loaded after libjvm
-    void* where = RTLD_NEXT;
-    if ((sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "__vsnprintf"))) == NULL) {
-      sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "vsnprintf"));
-    }
-    if (!sol_vsnprintf){
-      //search  for the named symbol in the objects that were loaded before libjvm
-      where = RTLD_DEFAULT;
-      if ((sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "__vsnprintf"))) == NULL) {
-        sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "vsnprintf"));
-      }
-      assert(sol_vsnprintf != NULL, "vsnprintf not found");
-    }
-  }
-  return (*sol_vsnprintf)(buf, count, fmt, argptr);
-}
-
-
 // Is a (classpath) directory empty?
 bool os::dir_is_empty(const char* path) {
   DIR *dir = NULL;
--- a/hotspot/src/os/solaris/vm/os_solaris.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/os/solaris/vm/os_solaris.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -97,6 +97,8 @@
   static meminfo_func_t _meminfo;
 
   // Large Page Support
+  static bool is_valid_page_size(size_t bytes);
+  static size_t page_size_for_alignment(size_t alignment);
   static bool setup_large_pages(caddr_t start, size_t bytes, size_t align);
 
   static void init_thread_fpu_state(void);
--- a/hotspot/src/share/vm/ci/ciField.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/ci/ciField.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -39,7 +39,6 @@
   CI_PACKAGE_ACCESS
   friend class ciEnv;
   friend class ciInstanceKlass;
-  friend class NonStaticFieldFiller;
 
 private:
   ciFlags          _flags;
--- a/hotspot/src/share/vm/ci/ciInstanceKlass.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/ci/ciInstanceKlass.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -44,7 +44,7 @@
 //
 // Loaded instance klass.
 ciInstanceKlass::ciInstanceKlass(KlassHandle h_k) :
-  ciKlass(h_k), _non_static_fields(NULL)
+  ciKlass(h_k)
 {
   assert(get_Klass()->oop_is_instance(), "wrong type");
   assert(get_instanceKlass()->is_loaded(), "must be at least loaded");
@@ -407,37 +407,6 @@
   return field;
 }
 
-// ------------------------------------------------------------------
-// ciInstanceKlass::non_static_fields.
-
-class NonStaticFieldFiller: public FieldClosure {
-  GrowableArray<ciField*>* _arr;
-  ciEnv* _curEnv;
-public:
-  NonStaticFieldFiller(ciEnv* curEnv, GrowableArray<ciField*>* arr) :
-    _curEnv(curEnv), _arr(arr)
-  {}
-  void do_field(fieldDescriptor* fd) {
-    ciField* field = new (_curEnv->arena()) ciField(fd);
-    _arr->append(field);
-  }
-};
-
-GrowableArray<ciField*>* ciInstanceKlass::non_static_fields() {
-  if (_non_static_fields == NULL) {
-    VM_ENTRY_MARK;
-    ciEnv* curEnv = ciEnv::current();
-    InstanceKlass* ik = get_instanceKlass();
-    int max_n_fields = ik->java_fields_count();
-
-    Arena* arena = curEnv->arena();
-    _non_static_fields =
-      new (arena) GrowableArray<ciField*>(arena, max_n_fields, 0, NULL);
-    NonStaticFieldFiller filler(curEnv, _non_static_fields);
-    ik->do_nonstatic_fields(&filler);
-  }
-  return _non_static_fields;
-}
 
 static int sort_field_by_offset(ciField** a, ciField** b) {
   return (*a)->offset_in_bytes() - (*b)->offset_in_bytes();
--- a/hotspot/src/share/vm/ci/ciInstanceKlass.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/ci/ciInstanceKlass.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -71,8 +71,6 @@
   //   Itsef: more than one implementors.
   ciInstanceKlass*       _implementor;
 
-  GrowableArray<ciField*>* _non_static_fields;
-
 protected:
   ciInstanceKlass(KlassHandle h_k);
   ciInstanceKlass(ciSymbol* name, jobject loader, jobject protection_domain);
@@ -181,8 +179,6 @@
   ciField* get_field_by_offset(int field_offset, bool is_static);
   ciField* get_field_by_name(ciSymbol* name, ciSymbol* signature, bool is_static);
 
-  GrowableArray<ciField*>* non_static_fields();
-
   // total number of nonstatic fields (including inherited):
   int nof_nonstatic_fields() {
     if (_nonstatic_fields == NULL)
--- a/hotspot/src/share/vm/code/nmethod.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/code/nmethod.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -1364,8 +1364,6 @@
   // Remove from list of active nmethods
   if (method() != NULL)
     method()->method_holder()->remove_osr_nmethod(this);
-  // Set entry as invalid
-  _entry_bci = InvalidOSREntryBci;
 }
 
 void nmethod::log_state_change() const {
--- a/hotspot/src/share/vm/code/nmethod.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/code/nmethod.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -202,13 +202,6 @@
   bool _oops_are_stale;  // indicates that it's no longer safe to access oops section
 #endif
 
-  enum { in_use       = 0,   // executable nmethod
-         not_entrant  = 1,   // marked for deoptimization but activations may still exist,
-                             // will be transformed to zombie when all activations are gone
-         zombie       = 2,   // no activations exist, nmethod is ready for purge
-         unloaded     = 3 }; // there should be no activations, should not be called,
-                             // will be transformed to zombie immediately
-
   jbyte _scavenge_root_state;
 
 #if INCLUDE_RTM_OPT
@@ -431,6 +424,13 @@
   address entry_point() const                     { return _entry_point;             } // normal entry point
   address verified_entry_point() const            { return _verified_entry_point;    } // if klass is correct
 
+  enum { in_use       = 0,   // executable nmethod
+         not_entrant  = 1,   // marked for deoptimization but activations may still exist,
+                             // will be transformed to zombie when all activations are gone
+         zombie       = 2,   // no activations exist, nmethod is ready for purge
+         unloaded     = 3 }; // there should be no activations, should not be called,
+                             // will be transformed to zombie immediately
+
   // flag accessing and manipulation
   bool  is_in_use() const                         { return _state == in_use; }
   bool  is_alive() const                          { return _state == in_use || _state == not_entrant; }
@@ -759,7 +759,7 @@
   // support for code generation
   static int verified_entry_point_offset()        { return offset_of(nmethod, _verified_entry_point); }
   static int osr_entry_point_offset()             { return offset_of(nmethod, _osr_entry_point); }
-  static int entry_bci_offset()                   { return offset_of(nmethod, _entry_bci); }
+  static int state_offset()                       { return offset_of(nmethod, _state); }
 
   // RedefineClasses support.   Mark metadata in nmethods as on_stack so that
   // redefine classes doesn't purge it.
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -4737,7 +4737,7 @@
 }
 
 bool G1PrintRegionLivenessInfoClosure::doHeapRegion(HeapRegion* r) {
-  const char* type = "";
+  const char* type       = r->get_type_str();
   HeapWord* bottom       = r->bottom();
   HeapWord* end          = r->end();
   size_t capacity_bytes  = r->capacity();
@@ -4748,15 +4748,7 @@
   size_t remset_bytes    = r->rem_set()->mem_size();
   size_t strong_code_roots_bytes = r->rem_set()->strong_code_roots_mem_size();
 
-  if (r->used() == 0) {
-    type = "FREE";
-  } else if (r->is_survivor()) {
-    type = "SURV";
-  } else if (r->is_young()) {
-    type = "EDEN";
-  } else if (r->startsHumongous()) {
-    type = "HUMS";
-
+  if (r->startsHumongous()) {
     assert(_hum_used_bytes == 0 && _hum_capacity_bytes == 0 &&
            _hum_prev_live_bytes == 0 && _hum_next_live_bytes == 0,
            "they should have been zeroed after the last time we used them");
@@ -4769,12 +4761,9 @@
                   &prev_live_bytes, &next_live_bytes);
     end = bottom + HeapRegion::GrainWords;
   } else if (r->continuesHumongous()) {
-    type = "HUMC";
     get_hum_bytes(&used_bytes, &capacity_bytes,
                   &prev_live_bytes, &next_live_bytes);
     assert(end == bottom + HeapRegion::GrainWords, "invariant");
-  } else {
-    type = "OLD";
   }
 
   _total_used_bytes      += used_bytes;
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -211,7 +211,10 @@
     HeapRegion* next = list->get_next_young_region();
     list->set_next_young_region(NULL);
     list->uninstall_surv_rate_group();
-    list->set_not_young();
+    // This is called before a Full GC and all the non-empty /
+    // non-humongous regions at the end of the Full GC will end up as
+    // old anyway.
+    list->set_old();
     list = next;
   }
 }
@@ -370,7 +373,7 @@
     if (curr == NULL)
       gclog_or_tty->print_cr("  empty");
     while (curr != NULL) {
-      gclog_or_tty->print_cr("  "HR_FORMAT", P: "PTR_FORMAT "N: "PTR_FORMAT", age: %4d",
+      gclog_or_tty->print_cr("  "HR_FORMAT", P: "PTR_FORMAT ", N: "PTR_FORMAT", age: %4d",
                              HR_FORMAT_PARAMS(curr),
                              curr->prev_top_at_mark_start(),
                              curr->next_top_at_mark_start(),
@@ -802,6 +805,7 @@
 #ifdef ASSERT
       for (uint i = first; i < first + obj_regions; ++i) {
         HeapRegion* hr = region_at(i);
+        assert(hr->is_free(), "sanity");
         assert(hr->is_empty(), "sanity");
         assert(is_on_master_free_list(hr), "sanity");
       }
@@ -1225,21 +1229,21 @@
 public:
   bool doHeapRegion(HeapRegion* hr) {
     assert(!hr->is_young(), "not expecting to find young regions");
-    // We only generate output for non-empty regions.
-    if (!hr->is_empty()) {
-      if (!hr->isHumongous()) {
-        _hr_printer->post_compaction(hr, G1HRPrinter::Old);
-      } else if (hr->startsHumongous()) {
-        if (hr->region_num() == 1) {
-          // single humongous region
-          _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);
-        } else {
-          _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);
-        }
+    if (hr->is_free()) {
+      // We only generate output for non-empty regions.
+    } else if (hr->startsHumongous()) {
+      if (hr->region_num() == 1) {
+        // single humongous region
+        _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);
       } else {
-        assert(hr->continuesHumongous(), "only way to get here");
-        _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);
+        _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);
       }
+    } else if (hr->continuesHumongous()) {
+      _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);
+    } else if (hr->is_old()) {
+      _hr_printer->post_compaction(hr, G1HRPrinter::Old);
+    } else {
+      ShouldNotReachHere();
     }
     return false;
   }
@@ -1477,9 +1481,7 @@
 
       // Discard all rset updates
       JavaThread::dirty_card_queue_set().abandon_logs();
-      assert(!G1DeferredRSUpdate
-             || (G1DeferredRSUpdate &&
-                (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
+      assert(dirty_card_queue_set().completed_buffers_num() == 0, "DCQS should be empty");
 
       _young_list->reset_sampled_info();
       // At this point there should be no regions in the
@@ -2090,15 +2092,13 @@
                                                 concurrent_g1_refine()->red_zone(),
                                                 Shared_DirtyCardQ_lock);
 
-  if (G1DeferredRSUpdate) {
-    dirty_card_queue_set().initialize(NULL, // Should never be called by the Java code
-                                      DirtyCardQ_CBL_mon,
-                                      DirtyCardQ_FL_lock,
-                                      -1, // never trigger processing
-                                      -1, // no limit on length
-                                      Shared_DirtyCardQ_lock,
-                                      &JavaThread::dirty_card_queue_set());
-  }
+  dirty_card_queue_set().initialize(NULL, // Should never be called by the Java code
+                                    DirtyCardQ_CBL_mon,
+                                    DirtyCardQ_FL_lock,
+                                    -1, // never trigger processing
+                                    -1, // no limit on length
+                                    Shared_DirtyCardQ_lock,
+                                    &JavaThread::dirty_card_queue_set());
 
   // Initialize the card queue set used to hold cards containing
   // references into the collection set.
@@ -2121,8 +2121,8 @@
   // We'll re-use the same region whether the alloc region will
   // require BOT updates or not and, if it doesn't, then a non-young
   // region will complain that it cannot support allocations without
-  // BOT updates. So we'll tag the dummy region as young to avoid that.
-  dummy_region->set_young();
+  // BOT updates. So we'll tag the dummy region as eden to avoid that.
+  dummy_region->set_eden();
   // Make sure it's full.
   dummy_region->set_top(dummy_region->end());
   G1AllocRegion::setup(this, dummy_region);
@@ -4031,14 +4031,6 @@
         if (_hr_printer.is_active()) {
           HeapRegion* hr = g1_policy()->collection_set();
           while (hr != NULL) {
-            G1HRPrinter::RegionType type;
-            if (!hr->is_young()) {
-              type = G1HRPrinter::Old;
-            } else if (hr->is_survivor()) {
-              type = G1HRPrinter::Survivor;
-            } else {
-              type = G1HRPrinter::Eden;
-            }
             _hr_printer.cset(hr);
             hr = hr->next_in_collection_set();
           }
@@ -5393,7 +5385,6 @@
 };
 
 void G1CollectedHeap::redirty_logged_cards() {
-  guarantee(G1DeferredRSUpdate, "Must only be called when using deferred RS updates.");
   double redirty_logged_cards_start = os::elapsedTime();
 
   uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
@@ -5448,9 +5439,10 @@
   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
   void do_oop(oop* p) {
     oop obj = *p;
+    assert(obj != NULL, "the caller should have filtered out NULL values");
 
     G1CollectedHeap::in_cset_state_t cset_state = _g1->in_cset_state(obj);
-    if (obj == NULL || cset_state == G1CollectedHeap::InNeither) {
+    if (cset_state == G1CollectedHeap::InNeither) {
       return;
     }
     if (cset_state == G1CollectedHeap::InCSet) {
@@ -6052,9 +6044,7 @@
   // RSets.
   enqueue_discovered_references(n_workers);
 
-  if (G1DeferredRSUpdate) {
-    redirty_logged_cards();
-  }
+  redirty_logged_cards();
   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 }
 
@@ -6062,7 +6052,7 @@
                                   FreeRegionList* free_list,
                                   bool par,
                                   bool locked) {
-  assert(!hr->isHumongous(), "this is only for non-humongous regions");
+  assert(!hr->is_free(), "the region should not be free");
   assert(!hr->is_empty(), "the region should not be empty");
   assert(_hrm.is_available(hr->hrm_index()), "region should be committed");
   assert(free_list != NULL, "pre-condition");
@@ -6092,14 +6082,14 @@
   // We need to read this before we make the region non-humongous,
   // otherwise the information will be gone.
   uint last_index = hr->last_hc_index();
-  hr->set_notHumongous();
+  hr->clear_humongous();
   free_region(hr, free_list, par);
 
   uint i = hr->hrm_index() + 1;
   while (i < last_index) {
     HeapRegion* curr_hr = region_at(i);
     assert(curr_hr->continuesHumongous(), "invariant");
-    curr_hr->set_notHumongous();
+    curr_hr->clear_humongous();
     free_region(curr_hr, free_list, par);
     i += 1;
   }
@@ -6407,9 +6397,9 @@
       if (cur->is_young()) {
         cur->set_young_index_in_cset(-1);
       }
-      cur->set_not_young();
       cur->set_evacuation_failed(false);
       // The region is now considered to be old.
+      cur->set_old();
       _old_set.add(cur);
       evacuation_info.increment_collectionset_used_after(cur->used());
     }
@@ -6696,16 +6686,15 @@
   TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { }
 
   bool doHeapRegion(HeapRegion* r) {
-    if (r->is_empty()) {
-      // We ignore empty regions, we'll empty the free list afterwards
-    } else if (r->is_young()) {
-      // We ignore young regions, we'll empty the young list afterwards
-    } else if (r->isHumongous()) {
+    if (r->is_old()) {
+      _old_set->remove(r);
+    } else {
+      // We ignore free regions, we'll empty the free list afterwards.
+      // We ignore young regions, we'll empty the young list afterwards.
       // We ignore humongous regions, we're not tearing down the
-      // humongous region set
-    } else {
-      // The rest should be old
-      _old_set->remove(r);
+      // humongous regions set.
+      assert(r->is_free() || r->is_young() || r->isHumongous(),
+             "it cannot be another type");
     }
     return false;
   }
@@ -6755,6 +6744,7 @@
 
     if (r->is_empty()) {
       // Add free regions to the free list
+      r->set_free();
       _hrm->insert_into_free_list(r);
     } else if (!_free_list_only) {
       assert(!r->is_young(), "we should not come across young regions");
@@ -6762,7 +6752,11 @@
       if (r->isHumongous()) {
         // We ignore humongous regions, we left the humongous set unchanged
       } else {
-        // The rest should be old, add them to the old set
+        // Objects that were compacted would have ended up on regions
+        // that were previously old or free.
+        assert(r->is_free() || r->is_old(), "invariant");
+        // We now consider them old, so register as such.
+        r->set_old();
         _old_set->add(r);
       }
       _total_used += r->used();
@@ -6829,7 +6823,7 @@
 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
                                                   size_t allocated_bytes) {
   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
-  assert(alloc_region->is_young(), "all mutator alloc regions should be young");
+  assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");
 
   g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);
   _summary_bytes_used += allocated_bytes;
@@ -6888,6 +6882,7 @@
         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
         check_bitmaps("Survivor Region Allocation", new_alloc_region);
       } else {
+        new_alloc_region->set_old();
         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
         check_bitmaps("Old Region Allocation", new_alloc_region);
       }
@@ -6999,9 +6994,11 @@
     } else if (hr->is_empty()) {
       assert(_hrm->is_free(hr), err_msg("Heap region %u is empty but not on the free list.", hr->hrm_index()));
       _free_count.increment(1u, hr->capacity());
-    } else {
+    } else if (hr->is_old()) {
       assert(hr->containing_set() == _old_set, err_msg("Heap region %u is old but not in the old set.", hr->hrm_index()));
       _old_count.increment(1u, hr->capacity());
+    } else {
+      ShouldNotReachHere();
     }
     return false;
   }
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -1665,7 +1665,7 @@
 // Add the heap region at the head of the non-incremental collection set
 void G1CollectorPolicy::add_old_region_to_cset(HeapRegion* hr) {
   assert(_inc_cset_build_state == Active, "Precondition");
-  assert(!hr->is_young(), "non-incremental add of young region");
+  assert(hr->is_old(), "the region should be old");
 
   assert(!hr->in_collection_set(), "should not already be in the CSet");
   hr->set_in_collection_set(true);
@@ -1811,7 +1811,7 @@
 // Add the region at the RHS of the incremental cset
 void G1CollectorPolicy::add_region_to_incremental_cset_rhs(HeapRegion* hr) {
   // We should only ever be appending survivors at the end of a pause
-  assert( hr->is_survivor(), "Logic");
+  assert(hr->is_survivor(), "Logic");
 
   // Do the 'common' stuff
   add_region_to_incremental_cset_common(hr);
@@ -1829,7 +1829,7 @@
 // Add the region to the LHS of the incremental cset
 void G1CollectorPolicy::add_region_to_incremental_cset_lhs(HeapRegion* hr) {
   // Survivors should be added to the RHS at the end of a pause
-  assert(!hr->is_survivor(), "Logic");
+  assert(hr->is_eden(), "Logic");
 
   // Do the 'common' stuff
   add_region_to_incremental_cset_common(hr);
@@ -1989,7 +1989,11 @@
   HeapRegion* hr = young_list->first_survivor_region();
   while (hr != NULL) {
     assert(hr->is_survivor(), "badly formed young list");
-    hr->set_young();
+    // There is a convention that all the young regions in the CSet
+    // are tagged as "eden", so we do this for the survivors here. We
+    // use the special set_eden_pre_gc() as it doesn't check that the
+    // region is free (which is not the case here).
+    hr->set_eden_pre_gc();
     hr = hr->get_next_young_region();
   }
 
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -299,13 +299,13 @@
   // Accessors
 
   void set_region_eden(HeapRegion* hr, int young_index_in_cset) {
-    hr->set_young();
+    hr->set_eden();
     hr->install_surv_rate_group(_short_lived_surv_rate_group);
     hr->set_young_index_in_cset(young_index_in_cset);
   }
 
   void set_region_survivor(HeapRegion* hr, int young_index_in_cset) {
-    assert(hr->is_young() && hr->is_survivor(), "pre-condition");
+    assert(hr->is_survivor(), "pre-condition");
     hr->install_surv_rate_group(_survivor_surv_rate_group);
     hr->set_young_index_in_cset(young_index_in_cset);
   }
--- a/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -176,15 +176,17 @@
 class RemoveSelfForwardPtrHRClosure: public HeapRegionClosure {
   G1CollectedHeap* _g1h;
   ConcurrentMark* _cm;
-  OopsInHeapRegionClosure *_update_rset_cl;
   uint _worker_id;
 
+  DirtyCardQueue _dcq;
+  UpdateRSetDeferred _update_rset_cl;
+
 public:
   RemoveSelfForwardPtrHRClosure(G1CollectedHeap* g1h,
-                                OopsInHeapRegionClosure* update_rset_cl,
                                 uint worker_id) :
-    _g1h(g1h), _update_rset_cl(update_rset_cl),
-    _worker_id(worker_id), _cm(_g1h->concurrent_mark()) { }
+    _g1h(g1h), _dcq(&g1h->dirty_card_queue_set()), _update_rset_cl(g1h, &_dcq),
+    _worker_id(worker_id), _cm(_g1h->concurrent_mark()) {
+    }
 
   bool doHeapRegion(HeapRegion *hr) {
     bool during_initial_mark = _g1h->g1_policy()->during_initial_mark_pause();
@@ -195,7 +197,7 @@
 
     if (hr->claimHeapRegion(HeapRegion::ParEvacFailureClaimValue)) {
       if (hr->evacuation_failed()) {
-        RemoveSelfForwardPtrObjClosure rspc(_g1h, _cm, hr, _update_rset_cl,
+        RemoveSelfForwardPtrObjClosure rspc(_g1h, _cm, hr, &_update_rset_cl,
                                             during_initial_mark,
                                             during_conc_mark,
                                             _worker_id);
@@ -214,7 +216,7 @@
         // whenever this might be required in the future.
         hr->rem_set()->reset_for_par_iteration();
         hr->reset_bot();
-        _update_rset_cl->set_region(hr);
+        _update_rset_cl.set_region(hr);
         hr->object_iterate(&rspc);
 
         hr->rem_set()->clean_strong_code_roots(hr);
@@ -238,16 +240,7 @@
     _g1h(g1h) { }
 
   void work(uint worker_id) {
-    UpdateRSetImmediate immediate_update(_g1h->g1_rem_set());
-    DirtyCardQueue dcq(&_g1h->dirty_card_queue_set());
-    UpdateRSetDeferred deferred_update(_g1h, &dcq);
-
-    OopsInHeapRegionClosure *update_rset_cl = &deferred_update;
-    if (!G1DeferredRSUpdate) {
-      update_rset_cl = &immediate_update;
-    }
-
-    RemoveSelfForwardPtrHRClosure rsfp_cl(_g1h, update_rset_cl, worker_id);
+    RemoveSelfForwardPtrHRClosure rsfp_cl(_g1h, worker_id);
 
     HeapRegion* hr = _g1h->start_cset_region_for_worker(worker_id);
     _g1h->collection_set_iterate_from(hr, &rsfp_cl);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -237,10 +237,8 @@
   _last_gc_worker_times_ms.verify();
   _last_gc_worker_other_times_ms.verify();
 
-  if (G1DeferredRSUpdate) {
-    _last_redirty_logged_cards_time_ms.verify();
-    _last_redirty_logged_cards_processed_cards.verify();
-  }
+  _last_redirty_logged_cards_time_ms.verify();
+  _last_redirty_logged_cards_processed_cards.verify();
 }
 
 void G1GCPhaseTimes::note_string_dedup_fixup_start() {
@@ -352,12 +350,10 @@
     _recorded_non_young_cset_choice_time_ms));
   print_stats(2, "Ref Proc", _cur_ref_proc_time_ms);
   print_stats(2, "Ref Enq", _cur_ref_enq_time_ms);
-  if (G1DeferredRSUpdate) {
-    print_stats(2, "Redirty Cards", _recorded_redirty_logged_cards_time_ms);
-    if (G1Log::finest()) {
-      _last_redirty_logged_cards_time_ms.print(3, "Parallel Redirty");
-      _last_redirty_logged_cards_processed_cards.print(3, "Redirtied Cards");
-    }
+  print_stats(2, "Redirty Cards", _recorded_redirty_logged_cards_time_ms);
+  if (G1Log::finest()) {
+    _last_redirty_logged_cards_time_ms.print(3, "Parallel Redirty");
+    _last_redirty_logged_cards_processed_cards.print(3, "Redirtied Cards");
   }
   if (G1ReclaimDeadHumongousObjectsAtYoungGC) {
     print_stats(2, "Humongous Reclaim", _cur_fast_reclaim_humongous_time_ms);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1HotCardCache.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1HotCardCache.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -27,7 +27,6 @@
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1HotCardCache.hpp"
 #include "gc_implementation/g1/g1RemSet.hpp"
-#include "gc_implementation/g1/heapRegion.hpp"
 #include "runtime/atomic.inline.hpp"
 
 G1HotCardCache::G1HotCardCache(G1CollectedHeap *g1h):
@@ -136,7 +135,6 @@
 }
 
 void G1HotCardCache::reset_card_counts(HeapRegion* hr) {
-  assert(!hr->isHumongous(), "Should have been cleared");
   _card_counts.clear_region(hr);
 }
 
--- a/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -84,20 +84,6 @@
   DirtyCardQueue& dirty_card_queue()             { return _dcq;  }
   G1SATBCardTableModRefBS* ctbs()                { return _ct_bs; }
 
-  template <class T> inline void immediate_rs_update(HeapRegion* from, T* p, int tid);
-
-  template <class T> void deferred_rs_update(HeapRegion* from, T* p, int tid) {
-    // If the new value of the field points to the same region or
-    // is the to-space, we don't need to include it in the Rset updates.
-    if (!from->is_in_reserved(oopDesc::load_decode_heap_oop(p)) && !from->is_survivor()) {
-      size_t card_index = ctbs()->index_for(p);
-      // If the card hasn't been added to the buffer, do it.
-      if (ctbs()->mark_card_deferred(card_index)) {
-        dirty_card_queue().enqueue((jbyte*)ctbs()->byte_for_index(card_index));
-      }
-    }
-  }
-
  public:
   G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp);
   ~G1ParScanThreadState();
@@ -124,8 +110,17 @@
     _refs->push(ref);
   }
 
-  template <class T> inline void update_rs(HeapRegion* from, T* p, int tid);
-
+  template <class T> void update_rs(HeapRegion* from, T* p, int tid) {
+    // If the new value of the field points to the same region or
+    // is the to-space, we don't need to include it in the Rset updates.
+    if (!from->is_in_reserved(oopDesc::load_decode_heap_oop(p)) && !from->is_survivor()) {
+      size_t card_index = ctbs()->index_for(p);
+      // If the card hasn't been added to the buffer, do it.
+      if (ctbs()->mark_card_deferred(card_index)) {
+        dirty_card_queue().enqueue((jbyte*)ctbs()->byte_for_index(card_index));
+      }
+    }
+  }
  private:
 
   inline HeapWord* allocate(GCAllocPurpose purpose, size_t word_sz);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.inline.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.inline.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -29,20 +29,6 @@
 #include "gc_implementation/g1/g1RemSet.inline.hpp"
 #include "oops/oop.inline.hpp"
 
-template <class T> inline void G1ParScanThreadState::immediate_rs_update(HeapRegion* from, T* p, int tid) {
-  if (!from->is_survivor()) {
-    _g1_rem->par_write_ref(from, p, tid);
-  }
-}
-
-template <class T> void G1ParScanThreadState::update_rs(HeapRegion* from, T* p, int tid) {
-  if (G1DeferredRSUpdate) {
-    deferred_rs_update(from, p, tid);
-  } else {
-    immediate_rs_update(from, p, tid);
-  }
-}
-
 template <class T> void G1ParScanThreadState::do_oop_evac(T* p, HeapRegion* from) {
   assert(!oopDesc::is_null(oopDesc::load_decode_heap_oop(p)),
          "Reference should not be NULL here as such are never pushed to the task queue.");
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -339,12 +339,8 @@
   // are just discarded (there's no need to update the RSets of regions
   // that were in the collection set - after the pause these regions
   // are wholly 'free' of live objects. In the event of an evacuation
-  // failure the cards/buffers in this queue set are:
-  // * passed to the DirtyCardQueueSet that is used to manage deferred
-  //   RSet updates, or
-  // * scanned for references that point into the collection set
-  //   and the RSet of the corresponding region in the collection set
-  //   is updated immediately.
+  // failure the cards/buffers in this queue set are passed to the
+  // DirtyCardQueueSet that is used to manage RSet updates
   DirtyCardQueue into_cset_dcq(&_g1->into_cset_dirty_card_queue_set());
 
   assert((ParallelGCThreads > 0) || worker_i == 0, "invariant");
@@ -358,7 +354,6 @@
 
 void G1RemSet::prepare_for_oops_into_collection_set_do() {
   cleanupHRRS();
-  ConcurrentG1Refine* cg1r = _g1->concurrent_g1_refine();
   _g1->set_refine_cte_cl_concurrency(false);
   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
   dcqs.concatenate_logs();
@@ -371,66 +366,6 @@
   _total_cards_scanned = 0;
 }
 
-
-// This closure, applied to a DirtyCardQueueSet, is used to immediately
-// update the RSets for the regions in the CSet. For each card it iterates
-// through the oops which coincide with that card. It scans the reference
-// fields in each oop; when it finds an oop that points into the collection
-// set, the RSet for the region containing the referenced object is updated.
-class UpdateRSetCardTableEntryIntoCSetClosure: public CardTableEntryClosure {
-  G1CollectedHeap* _g1;
-  CardTableModRefBS* _ct_bs;
-public:
-  UpdateRSetCardTableEntryIntoCSetClosure(G1CollectedHeap* g1,
-                                          CardTableModRefBS* bs):
-    _g1(g1), _ct_bs(bs)
-  { }
-
-  bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
-    // Construct the region representing the card.
-    HeapWord* start = _ct_bs->addr_for(card_ptr);
-    // And find the region containing it.
-    HeapRegion* r = _g1->heap_region_containing(start);
-
-    // Scan oops in the card looking for references into the collection set
-    // Don't use addr_for(card_ptr + 1) which can ask for
-    // a card beyond the heap.  This is not safe without a perm
-    // gen.
-    HeapWord* end   = start + CardTableModRefBS::card_size_in_words;
-    MemRegion scanRegion(start, end);
-
-    UpdateRSetImmediate update_rs_cl(_g1->g1_rem_set());
-    FilterIntoCSClosure update_rs_cset_oop_cl(NULL, _g1, &update_rs_cl);
-    FilterOutOfRegionClosure filter_then_update_rs_cset_oop_cl(r, &update_rs_cset_oop_cl);
-
-    // We can pass false as the "filter_young" parameter here as:
-    // * we should be in a STW pause,
-    // * the DCQS to which this closure is applied is used to hold
-    //   references that point into the collection set from the prior
-    //   RSet updating,
-    // * the post-write barrier shouldn't be logging updates to young
-    //   regions (but there is a situation where this can happen - see
-    //   the comment in G1RemSet::refine_card() below -
-    //   that should not be applicable here), and
-    // * during actual RSet updating, the filtering of cards in young
-    //   regions in HeapRegion::oops_on_card_seq_iterate_careful is
-    //   employed.
-    // As a result, when this closure is applied to "refs into cset"
-    // DCQS, we shouldn't see any cards in young regions.
-    update_rs_cl.set_region(r);
-    HeapWord* stop_point =
-      r->oops_on_card_seq_iterate_careful(scanRegion,
-                                          &filter_then_update_rs_cset_oop_cl,
-                                          false /* filter_young */,
-                                          NULL  /* card_ptr */);
-
-    // Since this is performed in the event of an evacuation failure, we
-    // we shouldn't see a non-null stop point
-    assert(stop_point == NULL, "saw an unallocated region");
-    return true;
-  }
-};
-
 void G1RemSet::cleanup_after_oops_into_collection_set_do() {
   guarantee( _cards_scanned != NULL, "invariant" );
   _total_cards_scanned = 0;
@@ -451,25 +386,10 @@
     double restore_remembered_set_start = os::elapsedTime();
 
     // Restore remembered sets for the regions pointing into the collection set.
-    if (G1DeferredRSUpdate) {
-      // If deferred RS updates are enabled then we just need to transfer
-      // the completed buffers from (a) the DirtyCardQueueSet used to hold
-      // cards that contain references that point into the collection set
-      // to (b) the DCQS used to hold the deferred RS updates
-      _g1->dirty_card_queue_set().merge_bufferlists(&into_cset_dcqs);
-    } else {
-
-      CardTableModRefBS* bs = (CardTableModRefBS*)_g1->barrier_set();
-      UpdateRSetCardTableEntryIntoCSetClosure update_rs_cset_immediate(_g1, bs);
-
-      int n_completed_buffers = 0;
-      while (into_cset_dcqs.apply_closure_to_completed_buffer(&update_rs_cset_immediate,
-                                                    0, 0, true)) {
-        n_completed_buffers++;
-      }
-      assert(n_completed_buffers == into_cset_n_buffers, "missed some buffers");
-    }
-
+    // We just need to transfer the completed buffers from the DirtyCardQueueSet
+    // used to hold cards that contain references that point into the collection set
+    // to the DCQS used to hold the deferred RS updates.
+    _g1->dirty_card_queue_set().merge_bufferlists(&into_cset_dcqs);
     _g1->g1_policy()->phase_times()->record_evac_fail_restore_remsets((os::elapsedTime() - restore_remembered_set_start) * 1000.0);
   }
 
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -193,18 +193,4 @@
   bool apply_to_weak_ref_discovered_field() { return true; }
 };
 
-class UpdateRSetImmediate: public OopsInHeapRegionClosure {
-private:
-  G1RemSet* _g1_rem_set;
-
-  template <class T> void do_oop_work(T* p);
-public:
-  UpdateRSetImmediate(G1RemSet* rs) :
-    _g1_rem_set(rs) {}
-
-  virtual void do_oop(narrowOop* p) { do_oop_work(p); }
-  virtual void do_oop(      oop* p) { do_oop_work(p); }
-};
-
-
 #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1REMSET_HPP
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -79,13 +79,4 @@
   _rs->par_write_ref(_from, p, _worker_i);
 }
 
-template <class T>
-inline void UpdateRSetImmediate::do_oop_work(T* p) {
-  assert(_from->is_in_reserved(p), "paranoia");
-  T heap_oop = oopDesc::load_heap_oop(p);
-  if (!oopDesc::is_null(heap_oop) && !_from->is_survivor()) {
-    _g1_rem_set->par_write_ref(_from, p, 0);
-  }
-}
-
 #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1REMSET_INLINE_HPP
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -259,14 +259,16 @@
     size_t code_root_elems = hrrs->strong_code_roots_list_length();
 
     RegionTypeCounter* current = NULL;
-    if (r->is_young()) {
+    if (r->is_free()) {
+      current = &_free;
+    } else if (r->is_young()) {
       current = &_young;
     } else if (r->isHumongous()) {
       current = &_humonguous;
-    } else if (r->is_empty()) {
-      current = &_free;
+    } else if (r->is_old()) {
+      current = &_old;
     } else {
-      current = &_old;
+      ShouldNotReachHere();
     }
     current->add(rs_mem_sz, occupied_cards, code_root_mem_sz, code_root_elems);
     _all.add(rs_mem_sz, occupied_cards, code_root_mem_sz, code_root_elems);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -31,8 +31,6 @@
 #include "oops/oop.inline.hpp"
 #include "utilities/macros.hpp"
 
-#if INCLUDE_ALL_GCS
-
 class DirtyCardQueueSet;
 class G1SATBCardTableLoggingModRefBS;
 
@@ -180,7 +178,4 @@
   void write_ref_array_work(MemRegion mr) { invalidate(mr); }
 };
 
-
-#endif // INCLUDE_ALL_GCS
-
 #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1SATBCARDTABLEMODREFBS_HPP
--- a/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -108,9 +108,6 @@
   develop(bool, G1RSBarrierRegionFilter, true,                              \
           "If true, generate region filtering code in RS barrier")          \
                                                                             \
-  develop(bool, G1DeferredRSUpdate, true,                                   \
-          "If true, use deferred RS updates")                               \
-                                                                            \
   develop(bool, G1RSLogCheckCardTable, false,                               \
           "If true, verify that no dirty cards remain after RS log "        \
           "processing.")                                                    \
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -211,8 +211,6 @@
 }
 
 void HeapRegion::hr_clear(bool par, bool clear_space, bool locked) {
-  assert(_humongous_type == NotHumongous,
-         "we should have already filtered out humongous regions");
   assert(_humongous_start_region == NULL,
          "we should have already filtered out humongous regions");
   assert(_end == _orig_end,
@@ -222,7 +220,7 @@
 
   set_young_index_in_cset(-1);
   uninstall_surv_rate_group();
-  set_young_type(NotYoung);
+  set_free();
   reset_pre_dummy_top();
 
   if (!par) {
@@ -273,7 +271,7 @@
   assert(top() == bottom(), "should be empty");
   assert(bottom() <= new_top && new_top <= new_end, "pre-condition");
 
-  _humongous_type = StartsHumongous;
+  _type.set_starts_humongous();
   _humongous_start_region = this;
 
   set_end(new_end);
@@ -287,11 +285,11 @@
   assert(top() == bottom(), "should be empty");
   assert(first_hr->startsHumongous(), "pre-condition");
 
-  _humongous_type = ContinuesHumongous;
+  _type.set_continues_humongous();
   _humongous_start_region = first_hr;
 }
 
-void HeapRegion::set_notHumongous() {
+void HeapRegion::clear_humongous() {
   assert(isHumongous(), "pre-condition");
 
   if (startsHumongous()) {
@@ -307,7 +305,6 @@
   }
 
   assert(capacity() == HeapRegion::GrainBytes, "pre-condition");
-  _humongous_type = NotHumongous;
   _humongous_start_region = NULL;
 }
 
@@ -327,12 +324,12 @@
                        MemRegion mr) :
     G1OffsetTableContigSpace(sharedOffsetArray, mr),
     _hrm_index(hrm_index),
-    _humongous_type(NotHumongous), _humongous_start_region(NULL),
+    _humongous_start_region(NULL),
     _in_collection_set(false),
     _next_in_special_set(NULL), _orig_end(NULL),
     _claimed(InitialClaimValue), _evacuation_failed(false),
     _prev_marked_bytes(0), _next_marked_bytes(0), _gc_efficiency(0.0),
-    _young_type(NotYoung), _next_young_region(NULL),
+    _next_young_region(NULL),
     _next_dirty_cards_region(NULL), _next(NULL), _prev(NULL),
 #ifdef ASSERT
     _containing_set(NULL),
@@ -686,26 +683,11 @@
 
 void HeapRegion::print() const { print_on(gclog_or_tty); }
 void HeapRegion::print_on(outputStream* st) const {
-  if (isHumongous()) {
-    if (startsHumongous())
-      st->print(" HS");
-    else
-      st->print(" HC");
-  } else {
-    st->print("   ");
-  }
+  st->print(" %2s", get_short_type_str());
   if (in_collection_set())
     st->print(" CS");
   else
     st->print("   ");
-  if (is_young())
-    st->print(is_survivor() ? " SU" : " Y ");
-  else
-    st->print("   ");
-  if (is_empty())
-    st->print(" F");
-  else
-    st->print("  ");
   st->print(" TS %5d", _gc_time_stamp);
   st->print(" PTAMS "PTR_FORMAT" NTAMS "PTR_FORMAT,
             prev_top_at_mark_start(), next_top_at_mark_start());
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -27,6 +27,7 @@
 
 #include "gc_implementation/g1/g1BlockOffsetTable.hpp"
 #include "gc_implementation/g1/g1_specialized_oop_closures.hpp"
+#include "gc_implementation/g1/heapRegionType.hpp"
 #include "gc_implementation/g1/survRateGroup.hpp"
 #include "gc_implementation/shared/ageTable.hpp"
 #include "gc_implementation/shared/spaceDecorator.hpp"
@@ -34,8 +35,6 @@
 #include "memory/watermark.hpp"
 #include "utilities/macros.hpp"
 
-#if INCLUDE_ALL_GCS
-
 // A HeapRegion is the smallest piece of a G1CollectedHeap that
 // can be collected independently.
 
@@ -55,10 +54,7 @@
 #define HR_FORMAT "%u:(%s)["PTR_FORMAT","PTR_FORMAT","PTR_FORMAT"]"
 #define HR_FORMAT_PARAMS(_hr_) \
                 (_hr_)->hrm_index(), \
-                (_hr_)->is_survivor() ? "S" : (_hr_)->is_young() ? "E" : \
-                (_hr_)->startsHumongous() ? "HS" : \
-                (_hr_)->continuesHumongous() ? "HC" : \
-                !(_hr_)->is_empty() ? "O" : "F", \
+                (_hr_)->get_short_type_str(), \
                 p2i((_hr_)->bottom()), p2i((_hr_)->top()), p2i((_hr_)->end())
 
 // sentinel value for hrm_index
@@ -215,12 +211,6 @@
   friend class VMStructs;
  private:
 
-  enum HumongousType {
-    NotHumongous = 0,
-    StartsHumongous,
-    ContinuesHumongous
-  };
-
   // The remembered set for this region.
   // (Might want to make this "inline" later, to avoid some alloc failure
   // issues.)
@@ -232,7 +222,8 @@
   // The index of this region in the heap region sequence.
   uint  _hrm_index;
 
-  HumongousType _humongous_type;
+  HeapRegionType _type;
+
   // For a humongous region, region in which it starts.
   HeapRegion* _humongous_start_region;
   // For the start region of a humongous sequence, it's original end().
@@ -274,13 +265,6 @@
   // The calculated GC efficiency of the region.
   double _gc_efficiency;
 
-  enum YoungType {
-    NotYoung,                   // a region is not young
-    Young,                      // a region is young
-    Survivor                    // a region is young and it contains survivors
-  };
-
-  volatile YoungType _young_type;
   int  _young_index_in_cset;
   SurvRateGroup* _surv_rate_group;
   int  _age_index;
@@ -305,12 +289,6 @@
     _next_top_at_mark_start = bot;
   }
 
-  void set_young_type(YoungType new_type) {
-    //assert(_young_type != new_type, "setting the same type" );
-    // TODO: add more assertions here
-    _young_type = new_type;
-  }
-
   // Cached attributes used in the collection set policy information
 
   // The RSet length that was added to the total value
@@ -430,9 +408,21 @@
     _prev_marked_bytes = _next_marked_bytes = 0;
   }
 
-  bool isHumongous() const { return _humongous_type != NotHumongous; }
-  bool startsHumongous() const { return _humongous_type == StartsHumongous; }
-  bool continuesHumongous() const { return _humongous_type == ContinuesHumongous; }
+  const char* get_type_str() const { return _type.get_str(); }
+  const char* get_short_type_str() const { return _type.get_short_str(); }
+
+  bool is_free() const { return _type.is_free(); }
+
+  bool is_young()    const { return _type.is_young();    }
+  bool is_eden()     const { return _type.is_eden();     }
+  bool is_survivor() const { return _type.is_survivor(); }
+
+  bool isHumongous() const { return _type.is_humongous(); }
+  bool startsHumongous() const { return _type.is_starts_humongous(); }
+  bool continuesHumongous() const { return _type.is_continues_humongous();   }
+
+  bool is_old() const { return _type.is_old(); }
+
   // For a humongous region, region in which it starts.
   HeapRegion* humongous_start_region() const {
     return _humongous_start_region;
@@ -496,7 +486,7 @@
   void set_continuesHumongous(HeapRegion* first_hr);
 
   // Unsets the humongous-related fields on the region.
-  void set_notHumongous();
+  void clear_humongous();
 
   // If the region has a remembered set, return a pointer to it.
   HeapRegionRemSet* rem_set() const {
@@ -623,9 +613,6 @@
   void calc_gc_efficiency(void);
   double gc_efficiency() { return _gc_efficiency;}
 
-  bool is_young() const     { return _young_type != NotYoung; }
-  bool is_survivor() const  { return _young_type == Survivor; }
-
   int  young_index_in_cset() const { return _young_index_in_cset; }
   void set_young_index_in_cset(int index) {
     assert( (index == -1) || is_young(), "pre-condition" );
@@ -677,11 +664,13 @@
     }
   }
 
-  void set_young() { set_young_type(Young); }
+  void set_free() { _type.set_free(); }
 
-  void set_survivor() { set_young_type(Survivor); }
+  void set_eden()        { _type.set_eden();        }
+  void set_eden_pre_gc() { _type.set_eden_pre_gc(); }
+  void set_survivor()    { _type.set_survivor();    }
 
-  void set_not_young() { set_young_type(NotYoung); }
+  void set_old() { _type.set_old(); }
 
   // Determine if an object has been allocated since the last
   // mark performed by the collector. This returns true iff the object
@@ -809,6 +798,4 @@
   bool complete() { return _complete; }
 };
 
-#endif // INCLUDE_ALL_GCS
-
 #endif // SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGION_HPP
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSet.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSet.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -42,7 +42,9 @@
   assert(hr->containing_set() == this, err_msg("Inconsistent containing set for %u", hr->hrm_index()));
   assert(!hr->is_young(), err_msg("Adding young region %u", hr->hrm_index())); // currently we don't use these sets for young regions
   assert(hr->isHumongous() == regions_humongous(), err_msg("Wrong humongous state for region %u and set %s", hr->hrm_index(), name()));
-  assert(hr->is_empty() == regions_empty(), err_msg("Wrong empty state for region %u and set %s", hr->hrm_index(), name()));
+  assert(hr->is_free() == regions_free(), err_msg("Wrong free state for region %u and set %s", hr->hrm_index(), name()));
+  assert(!hr->is_free() || hr->is_empty(), err_msg("Free region %u is not empty for set %s", hr->hrm_index(), name()));
+  assert(!hr->is_empty() || hr->is_free(), err_msg("Empty region %u is not free for set %s", hr->hrm_index(), name()));
   assert(hr->rem_set()->verify_ready_for_par_iteration(), err_msg("Wrong iteration state %u", hr->hrm_index()));
 }
 #endif
@@ -85,16 +87,16 @@
   out->print_cr("Set: %s ("PTR_FORMAT")", name(), this);
   out->print_cr("  Region Assumptions");
   out->print_cr("    humongous         : %s", BOOL_TO_STR(regions_humongous()));
-  out->print_cr("    empty             : %s", BOOL_TO_STR(regions_empty()));
+  out->print_cr("    free              : %s", BOOL_TO_STR(regions_free()));
   out->print_cr("  Attributes");
   out->print_cr("    length            : %14u", length());
   out->print_cr("    total capacity    : "SIZE_FORMAT_W(14)" bytes",
                 total_capacity_bytes());
 }
 
-HeapRegionSetBase::HeapRegionSetBase(const char* name, bool humongous, bool empty, HRSMtSafeChecker* mt_safety_checker)
+HeapRegionSetBase::HeapRegionSetBase(const char* name, bool humongous, bool free, HRSMtSafeChecker* mt_safety_checker)
   : _name(name), _verify_in_progress(false),
-    _is_humongous(humongous), _is_empty(empty), _mt_safety_checker(mt_safety_checker),
+    _is_humongous(humongous), _is_free(free), _mt_safety_checker(mt_safety_checker),
     _count()
 { }
 
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSet.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSet.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -81,7 +81,7 @@
   friend class VMStructs;
 private:
   bool _is_humongous;
-  bool _is_empty;
+  bool _is_free;
   HRSMtSafeChecker* _mt_safety_checker;
 
 protected:
@@ -102,9 +102,9 @@
   // not. Only used during verification.
   bool regions_humongous() { return _is_humongous; }
 
-  // Indicates whether all regions in the set should be empty or
+  // Indicates whether all regions in the set should be free or
   // not. Only used during verification.
-  bool regions_empty() { return _is_empty; }
+  bool regions_free() { return _is_free; }
 
   void check_mt_safety() {
     if (_mt_safety_checker != NULL) {
@@ -114,7 +114,7 @@
 
   virtual void fill_in_ext_msg_extra(hrs_ext_msg* msg) { }
 
-  HeapRegionSetBase(const char* name, bool humongous, bool empty, HRSMtSafeChecker* mt_safety_checker);
+  HeapRegionSetBase(const char* name, bool humongous, bool free, HRSMtSafeChecker* mt_safety_checker);
 
 public:
   const char* name() { return _name; }
@@ -171,7 +171,7 @@
   do {                                                                        \
     assert(((_set1_)->regions_humongous() ==                                  \
                                             (_set2_)->regions_humongous()) && \
-           ((_set1_)->regions_empty() == (_set2_)->regions_empty()),          \
+           ((_set1_)->regions_free() == (_set2_)->regions_free()),            \
            hrs_err_msg("the contents of set %s and set %s should match",      \
                        (_set1_)->name(), (_set2_)->name()));                  \
   } while (0)
@@ -184,7 +184,7 @@
 class HeapRegionSet : public HeapRegionSetBase {
 public:
   HeapRegionSet(const char* name, bool humongous, HRSMtSafeChecker* mt_safety_checker):
-    HeapRegionSetBase(name, humongous, false /* empty */, mt_safety_checker) { }
+    HeapRegionSetBase(name, humongous, false /* free */, mt_safety_checker) { }
 
   void bulk_remove(const HeapRegionSetCount& removed) {
     _count.decrement(removed.length(), removed.capacity());
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionType.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "gc_implementation/g1/heapRegionType.hpp"
+
+bool HeapRegionType::is_valid(Tag tag) {
+  switch (tag) {
+    case FreeTag:
+    case EdenTag:
+    case SurvTag:
+    case HumStartsTag:
+    case HumContTag:
+    case OldTag:
+      return true;
+  }
+  return false;
+}
+
+const char* HeapRegionType::get_str() const {
+  hrt_assert_is_valid(_tag);
+  switch (_tag) {
+    case FreeTag:      return "FREE";
+    case EdenTag:      return "EDEN";
+    case SurvTag:      return "SURV";
+    case HumStartsTag: return "HUMS";
+    case HumContTag:   return "HUMC";
+    case OldTag:       return "OLD";
+  }
+  ShouldNotReachHere();
+  // keep some compilers happy
+  return NULL;
+}
+
+const char* HeapRegionType::get_short_str() const {
+  hrt_assert_is_valid(_tag);
+  switch (_tag) {
+    case FreeTag:      return "F";
+    case EdenTag:      return "E";
+    case SurvTag:      return "S";
+    case HumStartsTag: return "HS";
+    case HumContTag:   return "HC";
+    case OldTag:       return "O";
+  }
+  ShouldNotReachHere();
+  // keep some compilers happy
+  return NULL;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionType.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGIONTYPE_HPP
+#define SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGIONTYPE_HPP
+
+#include "memory/allocation.hpp"
+
+#define hrt_assert_is_valid(tag) \
+  assert(is_valid((tag)), err_msg("invalid HR type: %u", (uint) (tag)))
+
+class HeapRegionType VALUE_OBJ_CLASS_SPEC {
+private:
+  // We encode the value of the heap region type so the generation can be
+  // determined quickly. The tag is split into two parts:
+  //
+  //   major type (young, humongous)                         : top N-1 bits
+  //   minor type (eden / survivor, starts / cont hum, etc.) : bottom 1 bit
+  //
+  // If there's need to increase the number of minor types in the
+  // future, we'll have to increase the size of the latter and hence
+  // decrease the size of the former.
+  //
+  // 0000 0 [ 0] Free
+  //
+  // 0001 0      Young Mask
+  // 0001 0 [ 2] Eden
+  // 0001 1 [ 3] Survivor
+  //
+  // 0010 0      Humongous Mask
+  // 0010 0 [ 4] Humongous Starts
+  // 0010 1 [ 5] Humongous Continues
+  //
+  // 01000 [ 8] Old
+  typedef enum {
+    FreeTag       = 0,
+
+    YoungMask     = 2,
+    EdenTag       = YoungMask,
+    SurvTag       = YoungMask + 1,
+
+    HumMask       = 4,
+    HumStartsTag  = HumMask,
+    HumContTag    = HumMask + 1,
+
+    OldTag        = 8
+  } Tag;
+
+  volatile Tag _tag;
+
+  static bool is_valid(Tag tag);
+
+  Tag get() const {
+    hrt_assert_is_valid(_tag);
+    return _tag;
+  }
+
+  // Sets the type to 'tag'.
+  void set(Tag tag) {
+    hrt_assert_is_valid(tag);
+    hrt_assert_is_valid(_tag);
+    _tag = tag;
+  }
+
+  // Sets the type to 'tag', expecting the type to be 'before'. This
+  // is available for when we want to add sanity checking to the type
+  // transition.
+  void set_from(Tag tag, Tag before) {
+    hrt_assert_is_valid(tag);
+    hrt_assert_is_valid(before);
+    hrt_assert_is_valid(_tag);
+    assert(_tag == before,
+           err_msg("HR tag: %u, expected: %u new tag; %u", _tag, before, tag));
+    _tag = tag;
+  }
+
+public:
+  // Queries
+
+  bool is_free() const { return get() == FreeTag; }
+
+  bool is_young()    const { return (get() & YoungMask) != 0; }
+  bool is_eden()     const { return get() == EdenTag;  }
+  bool is_survivor() const { return get() == SurvTag;  }
+
+  bool is_humongous()           const { return (get() & HumMask) != 0; }
+  bool is_starts_humongous()    const { return get() == HumStartsTag;  }
+  bool is_continues_humongous() const { return get() == HumContTag;    }
+
+  bool is_old() const { return get() == OldTag; }
+
+  // Setters
+
+  void set_free() { set(FreeTag); }
+
+  void set_eden()        { set_from(EdenTag, FreeTag); }
+  void set_eden_pre_gc() { set_from(EdenTag, SurvTag); }
+  void set_survivor()    { set_from(SurvTag, FreeTag); }
+
+  void set_starts_humongous()    { set_from(HumStartsTag, FreeTag); }
+  void set_continues_humongous() { set_from(HumContTag,   FreeTag); }
+
+  void set_old() { set(OldTag); }
+
+  // Misc
+
+  const char* get_str() const;
+  const char* get_short_str() const;
+
+  HeapRegionType() : _tag(FreeTag) { hrt_assert_is_valid(_tag); }
+};
+
+#endif // SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGIONTYPE_HPP
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -66,9 +66,10 @@
 
 void GenerationSizer::initialize_size_info() {
   trace_gen_sizes("ps heap raw");
-  const size_t page_sz = os::page_size_for_region(_min_heap_byte_size,
-                                                  _max_heap_byte_size,
-                                                  8);
+  const size_t max_page_sz = os::page_size_for_region(_max_heap_byte_size, 8);
+  const size_t min_pages = 4; // 1 for eden + 1 for each survivor + 1 for old
+  const size_t min_page_sz = os::page_size_for_region(_min_heap_byte_size, min_pages);
+  const size_t page_sz = MIN2(max_page_sz, min_page_sz);
 
   // Can a page size be something else than a power of two?
   assert(is_power_of_2((intptr_t)page_sz), "must be a power of 2");
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -41,7 +41,7 @@
 
   const size_t words = bits / BitsPerWord;
   const size_t raw_bytes = words * sizeof(idx_t);
-  const size_t page_sz = os::page_size_for_region(raw_bytes, raw_bytes, 10);
+  const size_t page_sz = os::page_size_for_region(raw_bytes, 10);
   const size_t granularity = os::vm_allocation_granularity();
   _reserved_byte_size = align_size_up(raw_bytes, MAX2(page_sz, granularity));
 
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -403,7 +403,7 @@
 ParallelCompactData::create_vspace(size_t count, size_t element_size)
 {
   const size_t raw_bytes = count * element_size;
-  const size_t page_sz = os::page_size_for_region(raw_bytes, raw_bytes, 10);
+  const size_t page_sz = os::page_size_for_region(raw_bytes, 10);
   const size_t granularity = os::vm_allocation_granularity();
   _reserved_byte_size = align_size_up(raw_bytes, MAX2(page_sz, granularity));
 
--- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -330,7 +330,7 @@
         if (do_OSR) {                                                                               \
           nmethod* osr_nmethod;                                                                     \
           OSR_REQUEST(osr_nmethod, branch_pc);                                                      \
-          if (osr_nmethod != NULL && osr_nmethod->osr_entry_bci() != InvalidOSREntryBci) {          \
+          if (osr_nmethod != NULL && osr_nmethod->is_in_use()) {                                    \
             intptr_t* buf;                                                                          \
             /* Call OSR migration with last java frame only, no checks. */                          \
             CALL_VM_NAKED_LJF(buf=SharedRuntime::OSR_migration_begin(THREAD));                      \
--- a/hotspot/src/share/vm/memory/heap.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/memory/heap.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -98,9 +98,13 @@
   _log2_segment_size = exact_log2(segment_size);
 
   // Reserve and initialize space for _memory.
-  const size_t page_size = os::can_execute_large_page_memory() ?
-          os::page_size_for_region(committed_size, reserved_size, 8) :
-          os::vm_page_size();
+  size_t page_size = os::vm_page_size();
+  if (os::can_execute_large_page_memory()) {
+    const size_t min_pages = 8;
+    page_size = MIN2(os::page_size_for_region(committed_size, min_pages),
+                     os::page_size_for_region(reserved_size, min_pages));
+  }
+
   const size_t granularity = os::vm_allocation_granularity();
   const size_t r_align = MAX2(page_size, granularity);
   const size_t r_size = align_size_up(reserved_size, r_align);
--- a/hotspot/src/share/vm/prims/jni.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/prims/jni.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -3848,6 +3848,7 @@
   unit_test_function_call
 
 // Forward declaration
+void TestOS_test();
 void TestReservedSpace_test();
 void TestReserveMemorySpecial_test();
 void TestVirtualSpace_test();
@@ -3871,6 +3872,7 @@
 void execute_internal_vm_tests() {
   if (ExecuteInternalVMTests) {
     tty->print_cr("Running internal VM tests");
+    run_unit_test(TestOS_test());
     run_unit_test(TestReservedSpace_test());
     run_unit_test(TestReserveMemorySpecial_test());
     run_unit_test(TestVirtualSpace_test());
--- a/hotspot/src/share/vm/runtime/os.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/runtime/os.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -1406,24 +1406,15 @@
   return (sp > (stack_limit + reserved_area));
 }
 
-size_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
-                                uint min_pages)
-{
+size_t os::page_size_for_region(size_t region_size, size_t min_pages) {
   assert(min_pages > 0, "sanity");
   if (UseLargePages) {
-    const size_t max_page_size = region_max_size / min_pages;
+    const size_t max_page_size = region_size / min_pages;
 
-    for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
-      const size_t sz = _page_sizes[i];
-      const size_t mask = sz - 1;
-      if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
-        // The largest page size with no fragmentation.
-        return sz;
-      }
-
-      if (sz <= max_page_size) {
-        // The largest page size that satisfies the min_pages requirement.
-        return sz;
+    for (size_t i = 0; _page_sizes[i] != 0; ++i) {
+      const size_t page_size = _page_sizes[i];
+      if (page_size <= max_page_size && is_size_aligned(region_size, page_size)) {
+        return page_size;
       }
     }
   }
@@ -1660,3 +1651,63 @@
   return result;
 }
 #endif
+
+/////////////// Unit tests ///////////////
+
+#ifndef PRODUCT
+
+#define assert_eq(a,b) assert(a == b, err_msg(SIZE_FORMAT " != " SIZE_FORMAT, a, b))
+
+class TestOS : AllStatic {
+  static size_t small_page_size() {
+    return os::vm_page_size();
+  }
+
+  static size_t large_page_size() {
+    const size_t large_page_size_example = 4 * M;
+    return os::page_size_for_region(large_page_size_example, 1);
+  }
+
+  static void test_page_size_for_region() {
+    if (UseLargePages) {
+      const size_t small_page = small_page_size();
+      const size_t large_page = large_page_size();
+
+      if (large_page > small_page) {
+        size_t num_small_pages_in_large = large_page / small_page;
+        size_t page = os::page_size_for_region(large_page, num_small_pages_in_large);
+
+        assert_eq(page, small_page);
+      }
+    }
+  }
+
+  static void test_page_size_for_region_alignment() {
+    if (UseLargePages) {
+      const size_t small_page = small_page_size();
+      const size_t large_page = large_page_size();
+      if (large_page > small_page) {
+        const size_t unaligned_region = large_page + 17;
+        size_t page = os::page_size_for_region(unaligned_region, 1);
+        assert_eq(page, small_page);
+
+        const size_t num_pages = 5;
+        const size_t aligned_region = large_page * num_pages;
+        page = os::page_size_for_region(aligned_region, num_pages);
+        assert_eq(page, large_page);
+      }
+    }
+  }
+
+ public:
+  static void run_tests() {
+    test_page_size_for_region();
+    test_page_size_for_region_alignment();
+  }
+};
+
+void TestOS_test() {
+  TestOS::run_tests();
+}
+
+#endif // PRODUCT
--- a/hotspot/src/share/vm/runtime/os.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/runtime/os.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -266,19 +266,11 @@
   // Return the default page size.
   static int    vm_page_size();
 
-  // Return the page size to use for a region of memory.  The min_pages argument
-  // is a hint intended to limit fragmentation; it says the returned page size
-  // should be <= region_max_size / min_pages.  Because min_pages is a hint,
-  // this routine may return a size larger than region_max_size / min_pages.
-  //
-  // The current implementation ignores min_pages if a larger page size is an
-  // exact multiple of both region_min_size and region_max_size.  This allows
-  // larger pages to be used when doing so would not cause fragmentation; in
-  // particular, a single page can be used when region_min_size ==
-  // region_max_size == a supported page size.
-  static size_t page_size_for_region(size_t region_min_size,
-                                     size_t region_max_size,
-                                     uint min_pages);
+  // Returns the page size to use for a region of memory.
+  // region_size / min_pages will always be greater than or equal to the
+  // returned value.
+  static size_t page_size_for_region(size_t region_size, size_t min_pages);
+
   // Return the largest page size that can be used
   static size_t max_page_size() {
     // The _page_sizes array is sorted in descending order.
--- a/hotspot/src/share/vm/runtime/virtualspace.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/runtime/virtualspace.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -38,7 +38,7 @@
 }
 
 ReservedSpace::ReservedSpace(size_t size) {
-  size_t page_size = os::page_size_for_region(size, size, 1);
+  size_t page_size = os::page_size_for_region(size, 1);
   bool large_pages = page_size != (size_t)os::vm_page_size();
   // Don't force the alignment to be large page aligned,
   // since that will waste memory.
@@ -357,7 +357,7 @@
 
 
 bool VirtualSpace::initialize(ReservedSpace rs, size_t committed_size) {
-  const size_t max_commit_granularity = os::page_size_for_region(rs.size(), rs.size(), 1);
+  const size_t max_commit_granularity = os::page_size_for_region(rs.size(), 1);
   return initialize_with_granularity(rs, committed_size, max_commit_granularity);
 }
 
@@ -992,7 +992,7 @@
     case Disable:
       return vs.initialize_with_granularity(rs, 0, os::vm_page_size());
     case Commit:
-      return vs.initialize_with_granularity(rs, 0, os::page_size_for_region(rs.size(), rs.size(), 1));
+      return vs.initialize_with_granularity(rs, 0, os::page_size_for_region(rs.size(), 1));
     }
   }
 
--- a/hotspot/src/share/vm/runtime/vmStructs.cpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/runtime/vmStructs.cpp	Fri Sep 19 13:47:19 2014 -0700
@@ -2518,7 +2518,6 @@
   /*********************************************/                         \
                                                                           \
   declare_constant(InvocationEntryBci)                                    \
-  declare_constant(InvalidOSREntryBci)                                    \
                                                                           \
   /***************/                                                       \
   /* OopMapValue */                                                       \
--- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -66,6 +66,9 @@
 #ifndef ATTRIBUTE_PRINTF
 #define ATTRIBUTE_PRINTF(fmt, vargs)
 #endif
+#ifndef ATTRIBUTE_SCANF
+#define ATTRIBUTE_SCANF(fmt, vargs)
+#endif
 
 
 #include "utilities/macros.hpp"
@@ -882,8 +885,7 @@
 
 // Handy constants for deciding which compiler mode to use.
 enum MethodCompilation {
-  InvocationEntryBci = -1,     // i.e., not a on-stack replacement compilation
-  InvalidOSREntryBci = -2
+  InvocationEntryBci = -1     // i.e., not a on-stack replacement compilation
 };
 
 // Enumeration to distinguish tiers of compilation
--- a/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -271,15 +271,16 @@
 #define PRAGMA_IMPLEMENTATION        #pragma implementation
 #define VALUE_OBJ_CLASS_SPEC
 
-#ifndef ATTRIBUTE_PRINTF
 // Diagnostic pragmas like the ones defined below in PRAGMA_FORMAT_NONLITERAL_IGNORED
 // were only introduced in GCC 4.2. Because we have no other possibility to ignore
 // these warnings for older versions of GCC, we simply don't decorate our printf-style
 // functions with __attribute__(format) in that case.
 #if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) || (__GNUC__ > 4)
+#ifndef ATTRIBUTE_PRINTF
 #define ATTRIBUTE_PRINTF(fmt,vargs)  __attribute__((format(printf, fmt, vargs)))
-#else
-#define ATTRIBUTE_PRINTF(fmt,vargs)
+#endif
+#ifndef ATTRIBUTE_SCANF
+#define ATTRIBUTE_SCANF(fmt,vargs)  __attribute__((format(scanf, fmt, vargs)))
 #endif
 #endif
 
--- a/hotspot/src/share/vm/utilities/globalDefinitions_sparcWorks.hpp	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/src/share/vm/utilities/globalDefinitions_sparcWorks.hpp	Fri Sep 19 13:47:19 2014 -0700
@@ -265,14 +265,6 @@
 
 inline int wcslen(const jchar* x) { return wcslen((const wchar_t*)x); }
 
-
-// Misc
-// NOTE: This one leads to an infinite recursion on Linux
-#ifndef LINUX
-int local_vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr);
-#define vsnprintf local_vsnprintf
-#endif
-
 // Portability macros
 #define PRAGMA_INTERFACE
 #define PRAGMA_IMPLEMENTATION
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/osr/TestRangeCheck.java	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,52 @@
+/*
+ * 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 TestRangeCheck
+ * @bug 8054883
+ * @summary Tests that range check is not skipped
+ */
+
+public class TestRangeCheck {
+    public static void main(String args[]) {
+        try {
+            test();
+            throw new AssertionError("Expected ArrayIndexOutOfBoundsException was not thrown");
+        } catch (ArrayIndexOutOfBoundsException e) {
+            System.out.println("Expected ArrayIndexOutOfBoundsException was thrown");
+        }
+    }
+
+    private static void test() {
+        int arr[] = new int[1];
+        int result = 1;
+
+        // provoke OSR compilation
+        for (int i = 0; i < Integer.MAX_VALUE; i++) {
+        }
+
+        if (result > 0 && arr[~result] > 0) {
+            arr[~result] = 0;
+        }
+    }
+}
--- a/hotspot/test/gc/arguments/TestParallelHeapSizeFlags.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/test/gc/arguments/TestParallelHeapSizeFlags.java	Fri Sep 19 13:47:19 2014 -0700
@@ -22,7 +22,6 @@
 */
 
 /*
- * @ignore 8049864
  * @test TestParallelHeapSizeFlags
  * @key gc
  * @bug 8006088
--- a/hotspot/test/gc/class_unloading/AllocateBeyondMetaspaceSize.java	Fri Sep 19 08:19:04 2014 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-import sun.hotspot.WhiteBox;
-
-class AllocateBeyondMetaspaceSize {
-  public static Object dummy;
-
-  public static void main(String [] args) {
-    if (args.length != 2) {
-      throw new IllegalArgumentException("Usage: <MetaspaceSize> <YoungGenSize>");
-    }
-
-    long metaspaceSize = Long.parseLong(args[0]);
-    long youngGenSize = Long.parseLong(args[1]);
-
-    run(metaspaceSize, youngGenSize);
-  }
-
-  private static void run(long metaspaceSize, long youngGenSize) {
-    WhiteBox wb = WhiteBox.getWhiteBox();
-
-    long allocationBeyondMetaspaceSize  = metaspaceSize * 2;
-    long metaspace = wb.allocateMetaspace(null, allocationBeyondMetaspaceSize);
-
-    triggerYoungGC(youngGenSize);
-
-    wb.freeMetaspace(null, metaspace, metaspace);
-  }
-
-  private static void triggerYoungGC(long youngGenSize) {
-    long approxAllocSize = 32 * 1024;
-    long numAllocations  = 2 * youngGenSize / approxAllocSize;
-
-    for (long i = 0; i < numAllocations; i++) {
-      dummy = new byte[(int)approxAllocSize];
-    }
-  }
-}
--- a/hotspot/test/gc/class_unloading/TestCMSClassUnloadingEnabledHWM.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/test/gc/class_unloading/TestCMSClassUnloadingEnabledHWM.java	Fri Sep 19 13:47:19 2014 -0700
@@ -26,7 +26,7 @@
  * @key gc
  * @bug 8049831
  * @library /testlibrary /testlibrary/whitebox
- * @build TestCMSClassUnloadingEnabledHWM AllocateBeyondMetaspaceSize
+ * @build TestCMSClassUnloadingEnabledHWM
  * @run main ClassFileInstaller sun.hotspot.WhiteBox
  *                              sun.hotspot.WhiteBox$WhiteBoxPermission
  * @run driver TestCMSClassUnloadingEnabledHWM
@@ -35,9 +35,11 @@
 
 import com.oracle.java.testlibrary.OutputAnalyzer;
 import com.oracle.java.testlibrary.ProcessTools;
-
+import java.lang.management.GarbageCollectorMXBean;
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.Arrays;
+import sun.hotspot.WhiteBox;
 
 public class TestCMSClassUnloadingEnabledHWM {
   private static long MetaspaceSize = 32 * 1024 * 1024;
@@ -48,15 +50,18 @@
       "-Xbootclasspath/a:.",
       "-XX:+UnlockDiagnosticVMOptions",
       "-XX:+WhiteBoxAPI",
+      "-Xmx128m",
+      "-XX:CMSMaxAbortablePrecleanTime=1",
+      "-XX:CMSWaitDuration=50",
       "-XX:MetaspaceSize=" + MetaspaceSize,
       "-Xmn" + YoungGenSize,
       "-XX:+UseConcMarkSweepGC",
       "-XX:" + (enableUnloading ? "+" : "-") + "CMSClassUnloadingEnabled",
       "-XX:+PrintHeapAtGC",
       "-XX:+PrintGCDetails",
-      "AllocateBeyondMetaspaceSize",
-      "" + MetaspaceSize,
-      "" + YoungGenSize);
+      "-XX:+PrintGCTimeStamps",
+      TestCMSClassUnloadingEnabledHWM.AllocateBeyondMetaspaceSize.class.getName(),
+      "" + MetaspaceSize);
     return new OutputAnalyzer(pb.start());
   }
 
@@ -88,5 +93,37 @@
     testWithCMSClassUnloading();
     testWithoutCMSClassUnloading();
   }
+
+  public static class AllocateBeyondMetaspaceSize {
+    public static void main(String [] args) throws Exception {
+      if (args.length != 1) {
+        throw new IllegalArgumentException("Usage: <MetaspaceSize>");
+      }
+
+      WhiteBox wb = WhiteBox.getWhiteBox();
+
+      // Allocate past the MetaspaceSize limit.
+      long metaspaceSize = Long.parseLong(args[0]);
+      long allocationBeyondMetaspaceSize  = metaspaceSize * 2;
+      long metaspace = wb.allocateMetaspace(null, allocationBeyondMetaspaceSize);
+
+      // Wait for at least one GC to occur. The caller will parse the log files produced.
+      GarbageCollectorMXBean cmsGCBean = getCMSGCBean();
+      while (cmsGCBean.getCollectionCount() == 0) {
+        Thread.sleep(100);
+      }
+
+      wb.freeMetaspace(null, metaspace, metaspace);
+    }
+
+    private static GarbageCollectorMXBean getCMSGCBean() {
+      for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
+        if (gcBean.getObjectName().toString().equals("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep")) {
+          return gcBean;
+        }
+      }
+      return null;
+    }
+  }
 }
 
--- a/hotspot/test/gc/class_unloading/TestG1ClassUnloadingHWM.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/test/gc/class_unloading/TestG1ClassUnloadingHWM.java	Fri Sep 19 13:47:19 2014 -0700
@@ -26,7 +26,7 @@
  * @key gc
  * @bug 8049831
  * @library /testlibrary /testlibrary/whitebox
- * @build TestG1ClassUnloadingHWM AllocateBeyondMetaspaceSize
+ * @build TestG1ClassUnloadingHWM
  * @run main ClassFileInstaller sun.hotspot.WhiteBox
  *                              sun.hotspot.WhiteBox$WhiteBoxPermission
  * @run driver TestG1ClassUnloadingHWM
@@ -35,9 +35,9 @@
 
 import com.oracle.java.testlibrary.OutputAnalyzer;
 import com.oracle.java.testlibrary.ProcessTools;
-
 import java.util.ArrayList;
 import java.util.Arrays;
+import sun.hotspot.WhiteBox;
 
 public class TestG1ClassUnloadingHWM {
   private static long MetaspaceSize = 32 * 1024 * 1024;
@@ -54,7 +54,7 @@
       "-XX:" + (enableUnloading ? "+" : "-") + "ClassUnloadingWithConcurrentMark",
       "-XX:+PrintHeapAtGC",
       "-XX:+PrintGCDetails",
-      "AllocateBeyondMetaspaceSize",
+      TestG1ClassUnloadingHWM.AllocateBeyondMetaspaceSize.class.getName(),
       "" + MetaspaceSize,
       "" + YoungGenSize);
     return new OutputAnalyzer(pb.start());
@@ -88,5 +88,36 @@
     testWithG1ClassUnloading();
     testWithoutG1ClassUnloading();
   }
+
+  public static class AllocateBeyondMetaspaceSize {
+    public static Object dummy;
+
+    public static void main(String [] args) throws Exception {
+      if (args.length != 2) {
+        throw new IllegalArgumentException("Usage: <MetaspaceSize> <YoungGenSize>");
+      }
+
+      WhiteBox wb = WhiteBox.getWhiteBox();
+
+      // Allocate past the MetaspaceSize limit
+      long metaspaceSize = Long.parseLong(args[0]);
+      long allocationBeyondMetaspaceSize  = metaspaceSize * 2;
+      long metaspace = wb.allocateMetaspace(null, allocationBeyondMetaspaceSize);
+
+      long youngGenSize = Long.parseLong(args[1]);
+      triggerYoungGCs(youngGenSize);
+
+      wb.freeMetaspace(null, metaspace, metaspace);
+    }
+
+    public static void triggerYoungGCs(long youngGenSize) {
+      long approxAllocSize = 32 * 1024;
+      long numAllocations  = 2 * youngGenSize / approxAllocSize;
+
+      for (long i = 0; i < numAllocations; i++) {
+        dummy = new byte[(int)approxAllocSize];
+      }
+    }
+  }
 }
 
--- a/hotspot/test/gc/g1/TestDeferredRSUpdate.java	Fri Sep 19 08:19:04 2014 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,79 +0,0 @@
-/*
- * 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 TestDeferredRSUpdate
- * @bug 8040977 8052170
- * @summary Ensure that running with -XX:-G1DeferredRSUpdate does not crash the VM
- * @key gc
- * @library /testlibrary
- */
-
-import com.oracle.java.testlibrary.ProcessTools;
-import com.oracle.java.testlibrary.OutputAnalyzer;
-
-public class TestDeferredRSUpdate {
-  public static void main(String[] args) throws Exception {
-    GCTest.main(args);
-
-    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC",
-                                                              "-Xmx10M",
-                                                              "-XX:+PrintGCDetails",
-                                                              // G1DeferredRSUpdate is a develop option, but we cannot limit execution of this test to only debug VMs.
-                                                              "-XX:+IgnoreUnrecognizedVMOptions",
-                                                              "-XX:-G1DeferredRSUpdate",
-                                                              GCTest.class.getName());
-
-    OutputAnalyzer output = new OutputAnalyzer(pb.start());
-    output.shouldHaveExitValue(0);
-  }
-
-  static class GCTest {
-    private static Object[] garbage = new Object[32];
-
-    public static void main(String [] args) {
-      System.out.println("Creating garbage");
-      // Create 128MB of garbage. This should result in at least one minor GC, with
-      // some objects copied to old gen. As references from old to young are installed,
-      // the crash due to the use before initialize occurs.
-      Object prev = null;
-      Object prevPrev = null;
-      for (int i = 0; i < 1024; i++) {
-        Object[] next = new Object[32 * 1024];
-        next[0] = prev;
-        next[1] = prevPrev;
-
-        Object[] cur = (Object[]) garbage[i % garbage.length];
-        if (cur != null) {
-          cur[0] = null;
-          cur[1] = null;
-        }
-        garbage[i % garbage.length] = next;
-
-        prevPrev = prev;
-        prev = next;
-      }
-      System.out.println("Done");
-    }
-  }
-}
--- a/hotspot/test/gc/g1/TestHumongousShrinkHeap.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/hotspot/test/gc/g1/TestHumongousShrinkHeap.java	Fri Sep 19 13:47:19 2014 -0700
@@ -26,7 +26,7 @@
  * @bug 8036025 8056043
  * @summary Verify that heap shrinks after GC in the presence of fragmentation due to humongous objects
  * @library /testlibrary
- * @run main/othervm -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=50 -XX:+UseG1GC -XX:G1HeapRegionSize=1M -verbose:gc TestHumongousShrinkHeap
+ * @run main/othervm -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=12 -XX:+UseG1GC -XX:G1HeapRegionSize=1M -verbose:gc TestHumongousShrinkHeap
  */
 
 import java.lang.management.ManagementFactory;
@@ -41,12 +41,24 @@
     public static final String MIN_FREE_RATIO_FLAG_NAME = "MinHeapFreeRatio";
     public static final String MAX_FREE_RATIO_FLAG_NAME = "MaxHeapFreeRatio";
 
-    private static final ArrayList<ArrayList<byte[]>> garbage = new ArrayList<>();
-    private static final int PAGE_SIZE = 1024 * 1024; // 1M
-    private static final int PAGES_NUM = 5;
+    private static final List<List<byte[]>> garbage = new ArrayList();
+    private static final int REGION_SIZE = 1024 * 1024; // 1M
+    private static final int LISTS_COUNT = 10;
+    private static final int HUMON_SIZE = Math.round(.9f * REGION_SIZE);
+    private static final long AVAILABLE_MEMORY
+                              = Runtime.getRuntime().freeMemory();
+    private static final int HUMON_COUNT
+                             = (int) ((AVAILABLE_MEMORY / HUMON_SIZE)
+            / LISTS_COUNT);
 
 
     public static void main(String[] args) {
+        System.out.format("Running with %s max heap size. "
+                + "Will allocate humongous object of %s size %d times.%n",
+                MemoryUsagePrinter.humanReadableByteCount(AVAILABLE_MEMORY, false),
+                MemoryUsagePrinter.humanReadableByteCount(HUMON_SIZE, false),
+                HUMON_COUNT
+        );
         new TestHumongousShrinkHeap().test();
     }
 
@@ -54,8 +66,8 @@
         System.gc();
         MemoryUsagePrinter.printMemoryUsage("init");
 
-        eat();
-        MemoryUsagePrinter.printMemoryUsage("eaten");
+        allocate();
+        MemoryUsagePrinter.printMemoryUsage("allocated");
         MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
 
         free();
@@ -72,15 +84,12 @@
         ));
     }
 
-    private void eat() {
-        int HumongousObjectSize = Math.round(.9f * PAGE_SIZE);
-        System.out.println("Will allocate objects of size=" +
-                MemoryUsagePrinter.humanReadableByteCount(HumongousObjectSize, true));
+    private void allocate() {
 
-        for (int i = 0; i < PAGES_NUM; i++) {
-            ArrayList<byte[]> stuff = new ArrayList<>();
-            eatList(stuff, 100, HumongousObjectSize);
-            MemoryUsagePrinter.printMemoryUsage("eat #" + i);
+        for (int i = 0; i < LISTS_COUNT; i++) {
+            List<byte[]> stuff = new ArrayList();
+            allocateList(stuff, HUMON_COUNT, HUMON_SIZE);
+            MemoryUsagePrinter.printMemoryUsage("allocate #" + (i+1));
             garbage.add(stuff);
         }
     }
@@ -90,12 +99,12 @@
         garbage.subList(0, garbage.size() - 1).clear();
 
         // do not free last one element from last list
-        ArrayList stuff = garbage.get(garbage.size() - 1);
+        List stuff = garbage.get(garbage.size() - 1);
         stuff.subList(0, stuff.size() - 1).clear();
         System.gc();
     }
 
-    private static void eatList(List garbage, int count, int size) {
+    private static void allocateList(List garbage, int count, int size) {
         for (int i = 0; i < count; i++) {
             garbage.add(new byte[size]);
         }
@@ -122,9 +131,9 @@
         float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
         System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
                 label,
-                humanReadableByteCount(memusage.getInit(), true),
-                humanReadableByteCount(memusage.getUsed(), true),
-                humanReadableByteCount(memusage.getCommitted(), true),
+                humanReadableByteCount(memusage.getInit(), false),
+                humanReadableByteCount(memusage.getUsed(), false),
+                humanReadableByteCount(memusage.getCommitted(), false),
                 freeratio * 100
         );
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/gc/g1/TestShrinkDefragmentedHeap.java	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,188 @@
+/*
+ * 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 TestShrinkDefragmentedHeap
+ * @bug 8038423
+ * @summary Verify that heap shrinks after GC in the presence of fragmentation due to humongous objects
+ *     1. allocate small objects mixed with humongous ones
+ *        "ssssHssssHssssHssssHssssHssssHssssH"
+ *     2. release all allocated object except the last humongous one
+ *        "..................................H"
+ *     3. invoke gc and check that memory returned to the system (amount of committed memory got down)
+ *
+ * @library /testlibrary
+ */
+import java.lang.management.ManagementFactory;
+import java.lang.management.MemoryUsage;
+import java.util.ArrayList;
+import java.util.List;
+import sun.management.ManagementFactoryHelper;
+import static com.oracle.java.testlibrary.Asserts.*;
+import com.oracle.java.testlibrary.ProcessTools;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+
+public class TestShrinkDefragmentedHeap {
+    // Since we store all the small objects, they become old and old regions are also allocated at the bottom of the heap
+    // together with humongous regions. So if there are a lot of old regions in the lower part of the heap,
+    // the humongous regions will be allocated in the upper part of the heap anyway.
+    // To avoid this the Eden needs to be big enough to fit all the small objects.
+    private static final int INITIAL_HEAP_SIZE  = 200 * 1024 * 1024;
+    private static final int MINIMAL_YOUNG_SIZE = 190 * 1024 * 1024;
+    private static final int REGION_SIZE        = 1 * 1024 * 1024;
+
+    public static void main(String[] args) throws Exception, Throwable {
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+                "-XX:InitialHeapSize=" + INITIAL_HEAP_SIZE,
+                "-Xmn" + MINIMAL_YOUNG_SIZE,
+                "-XX:MinHeapFreeRatio=10",
+                "-XX:MaxHeapFreeRatio=11",
+                "-XX:+UseG1GC",
+                "-XX:G1HeapRegionSize=" + REGION_SIZE,
+                "-verbose:gc",
+                GCTest.class.getName()
+        );
+
+        OutputAnalyzer output = ProcessTools.executeProcess(pb);
+        output.shouldHaveExitValue(0);
+    }
+
+    static class GCTest {
+
+        private static final String MIN_FREE_RATIO_FLAG_NAME = "MinHeapFreeRatio";
+        private static final String MAX_FREE_RATIO_FLAG_NAME = "MaxHeapFreeRatio";
+        private static final String NEW_SIZE_FLAG_NAME = "NewSize";
+
+        private static final ArrayList<ArrayList<byte[]>> garbage = new ArrayList<>();
+
+        private static final int SMALL_OBJS_SIZE  = 10 * 1024; // 10kB
+        private static final int SMALL_OBJS_COUNT = MINIMAL_YOUNG_SIZE / (SMALL_OBJS_SIZE-1);
+        private static final int ALLOCATE_COUNT = 3;
+        // try to put all humongous object into gap between min young size and initial heap size
+        // to avoid implicit GCs
+        private static final int HUMONG_OBJS_SIZE = (int) Math.max(
+                (INITIAL_HEAP_SIZE - MINIMAL_YOUNG_SIZE) / ALLOCATE_COUNT / 4,
+                REGION_SIZE * 1.1
+        );
+
+        private static final long initialHeapSize = getHeapMemoryUsage().getUsed();
+
+        public static void main(String[] args) throws InterruptedException {
+            new GCTest().test();
+        }
+
+        private void test() throws InterruptedException {
+            MemoryUsagePrinter.printMemoryUsage("init");
+
+            allocate();
+            System.gc();
+            MemoryUsage muFull = getHeapMemoryUsage();
+            MemoryUsagePrinter.printMemoryUsage("allocated");
+
+            free();
+            //Thread.sleep(1000); // sleep before measures due lags in JMX
+            MemoryUsage muFree = getHeapMemoryUsage();
+            MemoryUsagePrinter.printMemoryUsage("free");
+
+            assertLessThan(muFree.getCommitted(), muFull.getCommitted(), prepareMessageCommittedIsNotLess() );
+        }
+
+        private void allocate() {
+            System.out.format("Will allocate objects of small size = %s and humongous size = %s",
+                    MemoryUsagePrinter.humanReadableByteCount(SMALL_OBJS_SIZE, false),
+                    MemoryUsagePrinter.humanReadableByteCount(HUMONG_OBJS_SIZE, false)
+            );
+
+            for (int i = 0; i < ALLOCATE_COUNT; i++) {
+                ArrayList<byte[]> stuff = new ArrayList<>();
+                allocateList(stuff, SMALL_OBJS_COUNT / ALLOCATE_COUNT, SMALL_OBJS_SIZE);
+                garbage.add(stuff);
+
+                ArrayList<byte[]> humongousStuff = new ArrayList<>();
+                allocateList(humongousStuff, 4, HUMONG_OBJS_SIZE);
+                garbage.add(humongousStuff);
+            }
+        }
+
+        private void free() {
+            // do not free last one list
+            garbage.subList(0, garbage.size() - 1).clear();
+
+            // do not free last one element from last list
+            ArrayList stuff = garbage.get(garbage.size() - 1);
+            if (stuff.size() > 1) {
+                stuff.subList(0, stuff.size() - 1).clear();
+            }
+            System.gc();
+        }
+
+        private String prepareMessageCommittedIsNotLess() {
+            return String.format(
+                    "committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+                    + "%s = %s%n%s = %s",
+                    MIN_FREE_RATIO_FLAG_NAME,
+                    ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
+                    MAX_FREE_RATIO_FLAG_NAME,
+                    ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
+            );
+        }
+
+        private static void allocateList(List garbage, int count, int size) {
+            for (int i = 0; i < count; i++) {
+                garbage.add(new byte[size]);
+            }
+        }
+    }
+
+    static MemoryUsage getHeapMemoryUsage() {
+        return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
+    }
+
+    /**
+     * Prints memory usage to standard output
+     */
+    static class MemoryUsagePrinter {
+
+        public static String humanReadableByteCount(long bytes, boolean si) {
+            int unit = si ? 1000 : 1024;
+            if (bytes < unit) {
+                return bytes + " B";
+            }
+            int exp = (int) (Math.log(bytes) / Math.log(unit));
+            String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
+            return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
+        }
+
+        public static void printMemoryUsage(String label) {
+            MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
+            float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
+            System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
+                    label,
+                    humanReadableByteCount(memusage.getInit(), false),
+                    humanReadableByteCount(memusage.getUsed(), false),
+                    humanReadableByteCount(memusage.getCommitted(), false),
+                    freeratio * 100
+            );
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/memory/LargePages/TestLargePageSizeInBytes.java	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,61 @@
+/*
+ * 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 TestLargePageSizeInBytes
+ * @summary Tests that the flag -XX:LargePageSizeInBytes does not cause warnings on Solaris
+ * @bug 8049536
+ * @library /testlibrary
+ * @run driver TestLargePageSizeInBytes
+ */
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.Platform;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestLargePageSizeInBytes {
+    private static long M = 1024L * 1024L;
+    private static long G = 1024L * M;
+
+    public static void main(String[] args) throws Exception {
+        if (!Platform.isSolaris()) {
+            // We only use the syscall mencntl on Solaris
+            return;
+        }
+
+        testLargePageSizeInBytes(4 * M);
+        testLargePageSizeInBytes(256 * M);
+        testLargePageSizeInBytes(512 * M);
+        testLargePageSizeInBytes(2 * G);
+    }
+
+    private static void testLargePageSizeInBytes(long size) throws Exception {
+        ProcessBuilder pb =
+            ProcessTools.createJavaProcessBuilder("-XX:+UseLargePages",
+                                                  "-XX:LargePageSizeInBytes=" + size,
+                                                  "-version");
+
+        OutputAnalyzer out = new OutputAnalyzer(pb.start());
+        out.shouldNotContain("Attempt to use MPSS failed.");
+        out.shouldHaveExitValue(0);
+    }
+}
--- a/jaxp/.hgtags	Fri Sep 19 08:19:04 2014 -0400
+++ b/jaxp/.hgtags	Fri Sep 19 13:47:19 2014 -0700
@@ -273,3 +273,4 @@
 dc1e26434b3fd7e9b8eeab149103c1e30965f95c jdk9-b28
 30adcd13a313ea91e81164801a2f89282756d933 jdk9-b29
 d181d4002214e4914d5525bd5ee13369311c765c jdk9-b30
+292317ebc7dbaca6b3965f0bc7b38a2cee733b7a jdk9-b31
--- a/jaxws/.hgtags	Fri Sep 19 08:19:04 2014 -0400
+++ b/jaxws/.hgtags	Fri Sep 19 13:47:19 2014 -0700
@@ -276,3 +276,4 @@
 5282a14f131f897cc9575872c0fae72d47dc4e65 jdk9-b28
 3d1a4bfb6abbf5011ba6d8896301ee3b6ef3ba72 jdk9-b29
 e58d3ea638c3824f01547596b2a98aa5f77c4a5c jdk9-b30
+7af228ae847f3c02aaafb7b01cdbb3bdc2e89e77 jdk9-b31
--- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/api/util/ApClassLoader.java	Fri Sep 19 08:19:04 2014 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,152 +0,0 @@
-/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
- * 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.tools.internal.xjc.api.util;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.File;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.MalformedURLException;
-
-import com.sun.istack.internal.Nullable;
-
-/**
- * {@link ClassLoader} that loads Annotation Processing and specified classes
- * both into the same classloader, so that they can reference each other.
- *
- * @author Bhakti Mehta
- * @since 2.0 beta
- */
-public final class ApClassLoader extends URLClassLoader {
-    /**
-     * List of package prefixes we want to mask the
-     * parent classLoader from loading
-     */
-    private final String[] packagePrefixes;
-
-    /**
-     *
-     * @param packagePrefixes
-     *      The package prefixes that are forced to resolve within this class loader.
-     * @param parent
-     *      The parent class loader to delegate to. Null to indicate bootstrap classloader.
-     */
-    public ApClassLoader(@Nullable ClassLoader parent, String[] packagePrefixes) throws ToolsJarNotFoundException {
-        super(getToolsJar(parent),parent);
-        if(getURLs().length==0)
-            // if tools.jar was found in our classloader, no need to create
-            // a parallel classes
-            this.packagePrefixes = new String[0];
-        else
-            this.packagePrefixes = packagePrefixes;
-    }
-
-    public Class loadClass(String className) throws ClassNotFoundException {
-        for( String prefix : packagePrefixes ) {
-            if (className.startsWith(prefix) ) {
-                // we need to load those classes in this class loader
-                // without delegation.
-                return findClass(className);
-            }
-        }
-
-        return super.loadClass(className);
-
-    }
-
-    protected Class findClass(String name) throws ClassNotFoundException {
-
-        StringBuilder sb = new StringBuilder(name.length() + 6);
-        sb.append(name.replace('.','/')).append(".class");
-
-        InputStream is = getResourceAsStream(sb.toString());
-        if (is==null)
-            throw new ClassNotFoundException("Class not found" + sb);
-
-        try {
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            byte[] buf = new byte[1024];
-            int len;
-            while((len=is.read(buf))>=0)
-                baos.write(buf,0,len);
-
-            buf = baos.toByteArray();
-
-            // define package if not defined yet
-            int i = name.lastIndexOf('.');
-            if (i != -1) {
-                String pkgname = name.substring(0, i);
-                Package pkg = getPackage(pkgname);
-                if(pkg==null)
-                    definePackage(pkgname, null, null, null, null, null, null, null);
-            }
-
-            return defineClass(name,buf,0,buf.length);
-        } catch (IOException e) {
-            throw new ClassNotFoundException(name,e);
-        } finally {
-            try {
-                is.close();
-            } catch (IOException ioe) {
-                //ignore
-            }
-        }
-    }
-
-    /**
-     * Returns a class loader that can load classes from JDK tools.jar.
-     * @param parent
-     */
-    private static URL[] getToolsJar(@Nullable ClassLoader parent) throws ToolsJarNotFoundException {
-
-        try {
-            Class.forName("com.sun.tools.javac.Main", false, parent);
-            return new URL[0];
-            // we can already load them in the parent class loader.
-            // so no need to look for tools.jar.
-            // this happens when we are run inside IDE/Ant, or
-            // in Mac OS.
-        } catch (ClassNotFoundException e) {
-            // otherwise try to find tools.jar
-        }
-
-        File jreHome = new File(System.getProperty("java.home"));
-        File toolsJar = new File( jreHome.getParent(), "lib/tools.jar" );
-
-        if (!toolsJar.exists()) {
-            throw new ToolsJarNotFoundException(toolsJar);
-        }
-
-        try {
-            return new URL[]{toolsJar.toURL()};
-        } catch (MalformedURLException e) {
-            // impossible
-            throw new AssertionError(e);
-        }
-    }
-}
--- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/api/util/ToolsJarNotFoundException.java	Fri Sep 19 08:19:04 2014 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
- * 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.tools.internal.xjc.api.util;
-
-import java.io.File;
-
-/**
- * Signals an error when tools.jar was not found.
- *
- * Simply print out the message obtained by {@link #getMessage()}.
- *
- * @author Kohsuke Kawaguchi
- */
-public final class ToolsJarNotFoundException extends Exception {
-    /**
-     * Location where we expected to find tools.jar
-     */
-    public final File toolsJar;
-
-    public ToolsJarNotFoundException(File toolsJar) {
-        super(calcMessage(toolsJar));
-        this.toolsJar = toolsJar;
-    }
-
-    private static String calcMessage(File toolsJar) {
-        return Messages.TOOLS_JAR_NOT_FOUND.format(toolsJar.getPath());
-    }
-}
--- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/Invoker.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/Invoker.java	Fri Sep 19 13:47:19 2014 -0700
@@ -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
@@ -29,19 +29,16 @@
 import com.sun.istack.internal.tools.ParallelWorldClassLoader;
 import com.sun.tools.internal.ws.resources.WscompileMessages;
 import com.sun.tools.internal.ws.wscompile.Options;
-import com.sun.tools.internal.xjc.api.util.ToolsJarNotFoundException;
 import com.sun.xml.internal.bind.util.Which;
 
 import javax.xml.ws.Service;
 import javax.xml.ws.WebServiceFeature;
 import javax.xml.namespace.QName;
-import java.io.File;
 import java.io.OutputStream;
 import java.io.IOException;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
-import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLClassLoader;
 import java.util.ArrayList;
@@ -59,7 +56,7 @@
     /**
      * The list of package prefixes we want the
      * {@link MaskingClassLoader} to prevent the parent
-     * classLoader from loading
+     * class loader from loading
      */
     static final String[] maskedPackages = new String[]{
             "com.sun.istack.internal.tools.",
@@ -130,24 +127,6 @@
                     return -1;
                 }
 
-                //find and load tools.jar
-                List<URL> urls = new ArrayList<URL>();
-                findToolsJar(cl, urls);
-
-                if(urls.size() > 0){
-                    List<String> mask = new ArrayList<String>(Arrays.asList(maskedPackages));
-
-                    // first create a protected area so that we load JAXB/WS 2.1 API
-                    // and everything that depends on them inside
-                    cl = new MaskingClassLoader(cl,mask);
-
-                    // then this classloader loads the API and tools.jar
-                    cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), cl);
-
-                    // finally load the rest of the RI. The actual class files are loaded from ancestors
-                    cl = new ParallelWorldClassLoader(cl,"");
-                        }
-
             }
 
             Thread.currentThread().setContextClassLoader(cl);
@@ -158,8 +137,6 @@
             Method runMethod = compileTool.getMethod("run",String[].class);
             boolean r = (Boolean)runMethod.invoke(tool,new Object[]{args});
             return r ? 0 : 1;
-        } catch (ToolsJarNotFoundException e) {
-            System.err.println(e.getMessage());
         } catch (InvocationTargetException e) {
             throw e.getCause();
         } catch(ClassNotFoundException e){
@@ -167,8 +144,6 @@
         }finally {
             Thread.currentThread().setContextClassLoader(oldcc);
         }
-
-        return -1;
     }
 
     /**
@@ -203,10 +178,10 @@
 
 
     /**
-     * Creates a classloader that can load JAXB/WS 2.2 API and tools.jar,
-     * and then return a classloader that can RI classes, which can see all those APIs and tools.jar.
+     * Creates a class loader that can load JAXB/WS 2.2 API,
+     * and then return a class loader that can RI classes, which can see all those APIs.
      */
-    public static ClassLoader createClassLoader(ClassLoader cl) throws ClassNotFoundException, IOException, ToolsJarNotFoundException {
+    public static ClassLoader createClassLoader(ClassLoader cl) throws ClassNotFoundException, IOException {
 
         URL[] urls = findIstack22APIs(cl);
         if(urls.length==0)
@@ -223,7 +198,7 @@
         // and everything that depends on them inside
         cl = new MaskingClassLoader(cl,mask);
 
-        // then this classloader loads the API and tools.jar
+        // then this class loader loads the API
         cl = new URLClassLoader(urls, cl);
 
         // finally load the rest of the RI. The actual class files are loaded from ancestors
@@ -233,13 +208,13 @@
     }
 
     /**
-     * Creates a classloader for loading JAXB/WS 2.2 jar and tools.jar
+     * Creates a class loader for loading JAXB/WS 2.2 jar
      */
-    private static URL[] findIstack22APIs(ClassLoader cl) throws ClassNotFoundException, IOException, ToolsJarNotFoundException {
+    private static URL[] findIstack22APIs(ClassLoader cl) throws ClassNotFoundException, IOException {
         List<URL> urls = new ArrayList<URL>();
 
         if(Service.class.getClassLoader()==null) {
-            // JAX-WS API is loaded from bootstrap classloader
+            // JAX-WS API is loaded from bootstrap class loader
             URL res = cl.getResource("javax/xml/ws/EndpointContext.class");
             if(res==null)
                 throw new ClassNotFoundException("There's no JAX-WS 2.2 API in the classpath");
@@ -250,28 +225,7 @@
             urls.add(ParallelWorldClassLoader.toJarUrl(res));
         }
 
-        findToolsJar(cl, urls);
-
         return urls.toArray(new URL[urls.size()]);
     }
 
-    private static void findToolsJar(ClassLoader cl, List<URL> urls) throws ToolsJarNotFoundException, MalformedURLException {
-        try {
-            Class.forName("com.sun.tools.javac.Main",false,cl);
-            // we can already load them in the parent class loader.
-            // so no need to look for tools.jar.
-            // this happens when we are run inside IDE/Ant, or
-            // in Mac OS.
-        } catch (ClassNotFoundException e) {
-            // otherwise try to find tools.jar
-            File jreHome = new File(System.getProperty("java.home"));
-            File toolsJar = new File( jreHome.getParent(), "lib/tools.jar" );
-
-            if (!toolsJar.exists()) {
-                throw new ToolsJarNotFoundException(toolsJar);
-            }
-            urls.add(toolsJar.toURL());
-        }
-    }
-
 }
--- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/WsGen.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/WsGen.java	Fri Sep 19 13:47:19 2014 -0700
@@ -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
@@ -35,8 +35,7 @@
  */
 public class WsGen {
     /**
-     * CLI entry point. Use {@link Invoker} to
-     * load tools.jar
+     * CLI entry point. Use {@link Invoker} to load proper API version
      */
     public static void main(String[] args) throws Throwable {
         System.exit(Invoker.invoke("com.sun.tools.internal.ws.wscompile.WsgenTool", args));
@@ -50,7 +49,7 @@
      * it doesn't invoke {@link System#exit(int)}. This method
      * also doesn't play with classloaders. It's the caller's
      * responsibility to set up the classloader to load all jars
-     * needed to run the tool, including <tt>$JAVA_HOME/lib/tools.jar</tt>
+     * needed to run the tool.
      *
      * @return
      *      0 if the tool runs successfully.
--- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/WsImport.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/WsImport.java	Fri Sep 19 13:47:19 2014 -0700
@@ -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
@@ -35,8 +35,7 @@
  */
 public class WsImport {
     /**
-     * CLI entry point. Use {@link Invoker} to
-     * load tools.jar
+     * CLI entry point. Use {@link Invoker} to load proper API version
      */
     public static void main(String[] args) throws Throwable {
         System.exit(Invoker.invoke("com.sun.tools.internal.ws.wscompile.WsimportTool", args));
@@ -50,7 +49,7 @@
      * it doesn't invoke {@link System#exit(int)}. This method
      * also doesn't play with classloaders. It's the caller's
      * responsibility to set up the classloader to load all jars
-     * needed to run the tool, including <tt>$JAVA_HOME/lib/tools.jar</tt>
+     * needed to run the tool.
      *
      * @return
      *      0 if the tool runs successfully.
--- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/resources/JavacompilerMessages.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/resources/JavacompilerMessages.java	Fri Sep 19 13:47:19 2014 -0700
@@ -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
@@ -39,40 +39,16 @@
     private final static LocalizableMessageFactory messageFactory = new LocalizableMessageFactory("com.sun.tools.internal.ws.resources.javacompiler");
     private final static Localizer localizer = new Localizer();
 
-    public static Localizable localizableJAVACOMPILER_CLASSPATH_ERROR(Object arg0) {
-        return messageFactory.getMessage("javacompiler.classpath.error", arg0);
+    public static Localizable localizableNO_JAVACOMPILER_ERROR() {
+        return messageFactory.getMessage("no.javacompiler.error");
     }
 
     /**
-     * {0} is not available in the classpath, requires Sun's JDK version 5.0 or latter.
+     * No system compiler found, check your jdk.
      *
      */
-    public static String JAVACOMPILER_CLASSPATH_ERROR(Object arg0) {
-        return localizer.localize(localizableJAVACOMPILER_CLASSPATH_ERROR(arg0));
-    }
-
-    public static Localizable localizableJAVACOMPILER_NOSUCHMETHOD_ERROR(Object arg0) {
-        return messageFactory.getMessage("javacompiler.nosuchmethod.error", arg0);
-    }
-
-    /**
-     * There is no such method {0} available, requires Sun's JDK version 5.0 or latter.
-     *
-     */
-    public static String JAVACOMPILER_NOSUCHMETHOD_ERROR(Object arg0) {
-        return localizer.localize(localizableJAVACOMPILER_NOSUCHMETHOD_ERROR(arg0));
-    }
-
-    public static Localizable localizableJAVACOMPILER_ERROR(Object arg0) {
-        return messageFactory.getMessage("javacompiler.error", arg0);
-    }
-
-    /**
-     * error : {0}.
-     *
-     */
-    public static String JAVACOMPILER_ERROR(Object arg0) {
-        return localizer.localize(localizableJAVACOMPILER_ERROR(arg0));
+    public static String NO_JAVACOMPILER_ERROR() {
+        return localizer.localize(localizableNO_JAVACOMPILER_ERROR());
     }
 
 }
--- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/resources/javacompiler.properties	Fri Sep 19 08:19:04 2014 -0400
+++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/resources/javacompiler.properties	Fri Sep 19 13:47:19 2014 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,4 @@
 #
 # Generic Messages
 #
-javacompiler.classpath.error={0} is not available in the classpath, requires Sun's JDK version 5.0 or latter.
-javacompiler.nosuchmethod.error=There is no such method {0} available, requires Sun's JDK version 5.0 or latter.
-javacompiler.error=error : {0}.
+no.javacompiler.error=No system compiler found, check your jdk.
--- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wscompile/JavaCompilerHelper.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wscompile/JavaCompilerHelper.java	Fri Sep 19 13:47:19 2014 -0700
@@ -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
@@ -28,14 +28,13 @@
 import com.sun.istack.internal.tools.ParallelWorldClassLoader;
 import com.sun.tools.internal.ws.resources.JavacompilerMessages;
 
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
 import java.io.File;
 import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
 import java.net.MalformedURLException;
+import java.net.URISyntaxException;
 import java.net.URL;
-import java.net.URISyntaxException;
 
 /**
  * A helper class to invoke javac.
@@ -61,34 +60,17 @@
     }
 
     static boolean compile(String[] args, OutputStream out, ErrorReceiver receiver){
-        ClassLoader cl = Thread.currentThread().getContextClassLoader();
         try {
-            /* try to use the new compiler */
-            Class comSunToolsJavacMainClass =
-                    cl.loadClass("com.sun.tools.javac.Main");
-            try {
-                Method compileMethod =
-                        comSunToolsJavacMainClass.getMethod(
-                                "compile",
-                                compileMethodSignature);
-                    Object result =
-                            compileMethod.invoke(
-                                    null, args, new PrintWriter(out));
-                    return result instanceof Integer && (Integer) result == 0;
-            } catch (NoSuchMethodException e2) {
-                receiver.error(JavacompilerMessages.JAVACOMPILER_NOSUCHMETHOD_ERROR("getMethod(\"compile\", Class[])"), e2);
-            } catch (IllegalAccessException e) {
-                receiver.error(e);
-            } catch (InvocationTargetException e) {
-                receiver.error(e);
+            JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
+            if (comp == null) {
+                receiver.error(JavacompilerMessages.NO_JAVACOMPILER_ERROR(), null);
+                return false;
             }
-        } catch (ClassNotFoundException e) {
-            receiver.error(JavacompilerMessages.JAVACOMPILER_CLASSPATH_ERROR("com.sun.tools.javac.Main"), e);
+            return 0 == comp.run(null, out, out, args);
         } catch (SecurityException e) {
             receiver.error(e);
         }
         return false;
     }
 
-    private static final Class[] compileMethodSignature = {String[].class, PrintWriter.class};
 }
--- a/jdk/.hgtags	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/.hgtags	Fri Sep 19 13:47:19 2014 -0700
@@ -273,3 +273,4 @@
 1828f73b35cfe35e460e41fd6e087ab1f83e0621 jdk9-b28
 2da27e8e2c865e154f0c2eb9009f011a44649b11 jdk9-b29
 8d24fb4493f13d380a2adf62d444e1e5a4451f37 jdk9-b30
+71e99dae28f9791287b88d46e16a266b564f22be jdk9-b31
--- a/jdk/make/CreateJars.gmk	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/make/CreateJars.gmk	Fri Sep 19 13:47:19 2014 -0700
@@ -220,7 +220,6 @@
     sun/tools/serialver \
     sun/tools/tree \
     sun/tools/util \
-    sun/util/cldr/CLDRLocaleDataMetaInfo.class \
     sun/util/resources/provider/NonEnLocaleDataMetaInfo.class \
     META-INF/services/sun.util.locale.provider.LocaleDataMetaInfo \
     sun/util/resources/cldr \
@@ -452,11 +451,9 @@
 $(eval $(call SetupArchive,BUILD_CLDRDATA_JAR, \
     $(CLDR_METAINF_SERVICES), \
     SRCS := $(JDK_OUTPUTDIR)/modules/jdk.localedata \
-        $(JDK_OUTPUTDIR)/modules/java.base \
         $(CLDR_SERVICES_DIR), \
     SUFFIXES := .class, \
     INCLUDES := sun/text/resources/cldr \
-        sun/util/cldr/CLDRLocaleDataMetaInfo.class \
         sun/util/resources/cldr, \
     EXTRA_FILES := META-INF/services/sun.util.locale.provider.LocaleDataMetaInfo, \
     JAR := $(CLDRDATA_JAR_DST), \
--- a/jdk/make/gensrc/Gensrc-java.base.gmk	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/make/gensrc/Gensrc-java.base.gmk	Fri Sep 19 13:47:19 2014 -0700
@@ -29,14 +29,13 @@
 include GensrcProperties.gmk
 GENSRC_JAVA_BASE += $(GENSRC_PROPERTIES)
 
-include GensrcLocaleDataMetaInfo.gmk
+include GensrcLocaleData.gmk
 include GensrcCharacterData.gmk
 include GensrcMisc.gmk
 include GensrcCharsetMapping.gmk
 include GensrcCharsetCoder.gmk
 include GensrcBuffer.gmk
 include GensrcExceptions.gmk
-include GensrcCLDR.gmk
 
 java.base: $(GENSRC_JAVA_BASE)
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/gensrc/Gensrc-jdk.localedata.gmk	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,38 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+include GensrcCommon.gmk
+
+# Hook to include the corresponding custom file, if present.
+$(eval $(call IncludeCustomExtension, jdk, gensrc/Gensrc-jdk.localedata.gmk))
+
+include GensrcLocaleData.gmk
+include GensrcCLDR.gmk
+
+jdk.localedata: $(GENSRC_JDK_LOCALEDATA)
+
+all: jdk.localedata
+
+.PHONY: all jdk.localedata
--- a/jdk/make/gensrc/GensrcCLDR.gmk	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/make/gensrc/GensrcCLDR.gmk	Fri Sep 19 13:47:19 2014 -0700
@@ -27,9 +27,8 @@
 CLDRSRCDIR := $(JDK_TOPDIR)/src/jdk.localedata/share/classes/sun/util/cldr/resources/$(subst .,_,$(CLDRVERSION))
 
 GENSRC_DIR := $(JDK_OUTPUTDIR)/gensrc/jdk.localedata
-BASE_GENSRC_DIR := $(JDK_OUTPUTDIR)/gensrc/java.base
 
-CLDR_METAINFO_FILE := $(BASE_GENSRC_DIR)/sun/util/cldr/CLDRLocaleDataMetaInfo.java
+CLDR_METAINFO_FILE := $(GENSRC_DIR)/sun/util/resources/cldr/provider/CLDRLocaleDataMetaInfo.java
 
 $(CLDR_METAINFO_FILE): $(wildcard $(CLDRSRCDIR)/common/dtd/*.dtd) \
     $(wildcard $(CLDRSRCDIR)/common/main/*.xml) \
@@ -37,16 +36,6 @@
     $(BUILD_TOOLS_JDK)
 	$(MKDIR) -p $(GENSRC_DIR)
 	$(TOOL_CLDRCONVERTER) -base $(CLDRSRCDIR) -o $(GENSRC_DIR)
-	$(MKDIR) -p $(BASE_GENSRC_DIR)/sun/text/resources/cldr
-	$(MKDIR) -p $(BASE_GENSRC_DIR)/sun/util/resources/cldr
-	$(RM) -r $(BASE_GENSRC_DIR)/sun/text/resources/cldr/en \
-	    $(BASE_GENSRC_DIR)/sun/util/resources/cldr/en
-	$(MV) $(GENSRC_DIR)/sun/text/resources/cldr/en $(BASE_GENSRC_DIR)/sun/text/resources/cldr/en
-	$(MV) $(GENSRC_DIR)/sun/util/resources/cldr/en $(BASE_GENSRC_DIR)/sun/util/resources/cldr/en
-	$(MV) $(GENSRC_DIR)/sun/text/resources/cldr/*.java $(BASE_GENSRC_DIR)/sun/text/resources/cldr
-	$(MV) $(GENSRC_DIR)/sun/util/resources/cldr/*.java $(BASE_GENSRC_DIR)/sun/util/resources/cldr
-	$(MKDIR) -p $(@D)
-	$(MV) $(GENSRC_DIR)/sun/util/cldr/CLDRLocaleDataMetaInfo.java $@
 
 GENSRC_CLDR := $(CLDR_METAINFO_FILE)
-GENSRC_JAVA_BASE += $(GENSRC_CLDR)
+GENSRC_JDK_LOCALEDATA += $(GENSRC_CLDR)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/gensrc/GensrcLocaleData.gmk	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,152 @@
+#
+# 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.  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.
+#
+
+# Scan for all locale resources and extract for which locales there exists
+# resources. Then put this meta information about existing (supported?) locales
+# into LocaleDataMetaInfo.java
+
+# First go look for all locale files
+LOCALE_FILES := $(shell $(FIND) $(JDK_TOPDIR)/src/java.base/share/classes \
+    $(JDK_TOPDIR)/src/jdk.localedata/share/classes \
+    -name "FormatData_*.java" -o -name "FormatData_*.properties" -o \
+    -name "CollationData_*.java" -o -name "CollationData_*.properties" -o \
+    -name "TimeZoneNames_*.java" -o -name "TimeZoneNames_*.properties" -o \
+    -name "LocaleNames_*.java" -o -name "LocaleNames_*.properties" -o \
+    -name "CurrencyNames_*.java" -o -name "CurrencyNames_*.properties" -o \
+    -name "CalendarData_*.java" -o -name "CalendarData_*.properties" -o \
+    -name "BreakIteratorInfo_*.java" -o -name "BreakIteratorRules_*.java")
+
+# Then translate the locale files into for example: FormatData_sv
+LOCALE_RESOURCES := $(sort $(subst .properties,,$(subst .java,,$(notdir $(LOCALE_FILES)))))
+
+# Include the list of resources found during the previous compile.
+-include $(JDK_OUTPUTDIR)/gensrc/_the.locale_resources
+
+MISSING_RESOURCES := $(filter-out $(LOCALE_RESOURCES), $(PREV_LOCALE_RESOURCES))
+NEW_RESOURCES := $(filter-out $(PREV_LOCALE_RESOURCES), $(LOCALE_RESOURCES))
+
+ifneq (, $(MISSING_RESOURCES)$(NEW_RESOURCES))
+  # There is a difference in the number of supported resources. Trigger a regeneration.
+  $(shell $(RM) $(JDK_OUTPUTDIR)/gensrc/sun/util/locale/provider/LocaleDataMetaInfo.java)
+endif
+
+# The EN locales
+EN_LOCALES := en%
+
+# Locales that don't have any resource files should be included here.
+ALL_NON_EN_LOCALES := ja-JP-JP nb-NO nn-NO th-TH-TH
+
+SED_ENARGS := -e 's|$(HASH)warn This file is preprocessed before being compiled|// -- This file was mechanically generated: Do not edit! -- //|g'
+SED_NONENARGS := $(SED_ENARGS)
+
+# Fill in the languages and package names
+SED_ENARGS += -e 's/$(HASH)Lang$(HASH)/En/' \
+    -e 's/$(HASH)Package$(HASH)/sun.util.locale.provider/'
+SED_NONENARGS += -e 's/$(HASH)Lang$(HASH)/NonEn/' \
+    -e 's/$(HASH)Package$(HASH)/sun.util.resources.provider/'
+
+# This macro creates a sed expression that substitues for example:
+# #FormatData_ENLocales# with: en% locales.
+define CaptureLocale
+  $1_LOCALES := $$(subst _,-,$$(filter-out $1, $$(subst $1_,,$$(filter $1_%, $(LOCALE_RESOURCES)))))
+  $1_EN_LOCALES := $$(filter $(EN_LOCALES), $$($1_LOCALES))
+  $1_NON_EN_LOCALES := $$(filter-out $(EN_LOCALES), $$($1_LOCALES))
+
+  # Special handling for Chinese locales to include implicit scripts
+  $1_NON_EN_LOCALES := $$(subst zh-CN,zh-CN$$(SPACE)zh-Hans-CN, $$($1_NON_EN_LOCALES))
+  $1_NON_EN_LOCALES := $$(subst zh-SG,zh-SG$$(SPACE)zh-Hans-SG, $$($1_NON_EN_LOCALES))
+  $1_NON_EN_LOCALES := $$(subst zh-HK,zh-HK$$(SPACE)zh-Hant-HK, $$($1_NON_EN_LOCALES))
+  $1_NON_EN_LOCALES := $$(subst zh-MO,zh-MO$$(SPACE)zh-Hant-MO, $$($1_NON_EN_LOCALES))
+  $1_NON_EN_LOCALES := $$(subst zh-TW,zh-TW$$(SPACE)zh-Hant-TW, $$($1_NON_EN_LOCALES))
+
+  ALL_EN_LOCALES += $$($1_EN_LOCALES)
+  ALL_NON_EN_LOCALES += $$($1_NON_EN_LOCALES)
+
+  # Don't sed in a space if there are no locales.
+  SED_ENARGS += -e 's/$$(HASH)$1_Locales$$(HASH)/$$(if $$($1_EN_LOCALES),$$(SPACE)$$($1_EN_LOCALES),)/g'
+  SED_NONENARGS += -e 's/$$(HASH)$1_Locales$$(HASH)/$$(if $$($1_NON_EN_LOCALES),$$(SPACE)$$($1_NON_EN_LOCALES),)/g'
+endef
+
+#sun.text.resources.FormatData
+$(eval $(call CaptureLocale,FormatData))
+
+#sun.text.resources.CollationData
+$(eval $(call CaptureLocale,CollationData))
+
+#sun.text.resources.BreakIteratorInfo
+$(eval $(call CaptureLocale,BreakIteratorInfo))
+
+#sun.text.resources.BreakIteratorRules
+$(eval $(call CaptureLocale,BreakIteratorRules))
+
+#sun.util.resources.TimeZoneNames
+$(eval $(call CaptureLocale,TimeZoneNames))
+
+#sun.util.resources.LocaleNames
+$(eval $(call CaptureLocale,LocaleNames))
+
+#sun.util.resources.CurrencyNames
+$(eval $(call CaptureLocale,CurrencyNames))
+
+#sun.util.resources.CalendarData
+$(eval $(call CaptureLocale,CalendarData))
+
+SED_ENARGS += -e 's/$(HASH)AvailableLocales_Locales$(HASH)/$(sort $(ALL_EN_LOCALES))/g'
+SED_NONENARGS += -e 's/$(HASH)AvailableLocales_Locales$(HASH)/$(sort $(ALL_NON_EN_LOCALES))/g'
+
+$(JDK_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/EnLocaleDataMetaInfo.java: \
+    $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/locale/provider/LocaleDataMetaInfo-XLocales.java.template
+	$(MKDIR) -p $(@D)
+	$(ECHO) Creating sun/util/locale/provider/EnLocaleDataMetaInfo.java from $(words $(LOCALE_RESOURCES)) found resources.
+	$(PRINTF) "PREV_LOCALE_RESOURCES:=$(LOCALE_RESOURCES)" > $(JDK_OUTPUTDIR)/gensrc/_the.locale_resources
+	$(SED) $(SED_ENARGS) $< > $@
+
+$(JDK_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonEnLocaleDataMetaInfo.java: \
+    $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/locale/provider/LocaleDataMetaInfo-XLocales.java.template
+	$(MKDIR) -p $(@D)
+	$(ECHO) Creating sun/util/resources/provider/NonEnLocaleDataMetaInfo.java from $(words $(LOCALE_RESOURCES)) found resources.
+	$(PRINTF) "PREV_LOCALE_RESOURCES:=$(LOCALE_RESOURCES)" > $(JDK_OUTPUTDIR)/gensrc/_the.locale_resources
+	$(SED) $(SED_NONENARGS) $< > $@
+
+GENSRC_BASELOCALEDATA := $(JDK_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/EnLocaleDataMetaInfo.java
+GENSRC_LOCALEDATA := $(JDK_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonEnLocaleDataMetaInfo.java
+
+################################################################################
+
+GENSRC_CRBC_DST := $(JDK_OUTPUTDIR)/gensrc/java.base/sun/util/CoreResourceBundleControl.java
+GENSRC_CRBC_CMD := $(JDK_TOPDIR)/make/scripts/localelist.sh
+
+JRE_NONEXIST_LOCALES := en en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR sv_SE zh
+
+$(GENSRC_CRBC_DST): $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/CoreResourceBundleControl-XLocales.java.template \
+    $(GENSRC_CRBC_CMD)
+	$(MKDIR) -p $(@D)
+	NAWK="$(NAWK)" SED="$(SED)" $(SH) $(GENSRC_CRBC_CMD) "$(JRE_NONEXIST_LOCALES)" $< $@
+
+GENSRC_BASELOCALEDATA += $(GENSRC_CRBC_DST)
+GENSRC_JAVA_BASE += $(GENSRC_BASELOCALEDATA)
+GENSRC_JDK_LOCALEDATA += $(GENSRC_LOCALEDATA)
+
+################################################################################
--- a/jdk/make/gensrc/GensrcLocaleDataMetaInfo.gmk	Fri Sep 19 08:19:04 2014 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,151 +0,0 @@
-#
-# 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.  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.
-#
-
-# Scan for all locale resources and extract for which locales there exists
-# resources. Then put this meta information about existing (supported?) locales
-# into LocaleDataMetaInfo.java
-
-# First go look for all locale files
-LOCALE_FILES := $(shell $(FIND) $(JDK_TOPDIR)/src/java.base/share/classes \
-    $(JDK_TOPDIR)/src/jdk.localedata/share/classes \
-    -name "FormatData_*.java" -o -name "FormatData_*.properties" -o \
-    -name "CollationData_*.java" -o -name "CollationData_*.properties" -o \
-    -name "TimeZoneNames_*.java" -o -name "TimeZoneNames_*.properties" -o \
-    -name "LocaleNames_*.java" -o -name "LocaleNames_*.properties" -o \
-    -name "CurrencyNames_*.java" -o -name "CurrencyNames_*.properties" -o \
-    -name "CalendarData_*.java" -o -name "CalendarData_*.properties" -o \
-    -name "BreakIteratorInfo_*.java" -o -name "BreakIteratorRules_*.java")
-
-# Then translate the locale files into for example: FormatData_sv
-LOCALE_RESOURCES := $(sort $(subst .properties,,$(subst .java,,$(notdir $(LOCALE_FILES)))))
-
-# Include the list of resources found during the previous compile.
--include $(JDK_OUTPUTDIR)/gensrc/_the.locale_resources
-
-MISSING_RESOURCES := $(filter-out $(LOCALE_RESOURCES), $(PREV_LOCALE_RESOURCES))
-NEW_RESOURCES := $(filter-out $(PREV_LOCALE_RESOURCES), $(LOCALE_RESOURCES))
-
-ifneq (, $(MISSING_RESOURCES)$(NEW_RESOURCES))
-  # There is a difference in the number of supported resources. Trigger a regeneration.
-  $(shell $(RM) $(JDK_OUTPUTDIR)/gensrc/sun/util/locale/provider/LocaleDataMetaInfo.java)
-endif
-
-# The EN locales
-EN_LOCALES := en%
-
-# Locales that don't have any resource files should be included here.
-ALL_NON_EN_LOCALES := ja-JP-JP nb-NO nn-NO th-TH-TH
-
-SED_ENARGS := -e 's|$(HASH)warn This file is preprocessed before being compiled|// -- This file was mechanically generated: Do not edit! -- //|g'
-SED_NONENARGS := $(SED_ENARGS)
-
-# Fill in the languages and package names
-SED_ENARGS += -e 's/$(HASH)Lang$(HASH)/En/' \
-    -e 's/$(HASH)Package$(HASH)/sun.util.locale.provider/'
-SED_NONENARGS += -e 's/$(HASH)Lang$(HASH)/NonEn/' \
-    -e 's/$(HASH)Package$(HASH)/sun.util.resources.provider/'
-
-# This macro creates a sed expression that substitues for example:
-# #FormatData_ENLocales# with: en% locales.
-define CaptureLocale
-  $1_LOCALES := $$(subst _,-,$$(filter-out $1, $$(subst $1_,,$$(filter $1_%, $(LOCALE_RESOURCES)))))
-  $1_EN_LOCALES := $$(filter $(EN_LOCALES), $$($1_LOCALES))
-  $1_NON_EN_LOCALES := $$(filter-out $(EN_LOCALES), $$($1_LOCALES))
-
-  # Special handling for Chinese locales to include implicit scripts
-  $1_NON_EN_LOCALES := $$(subst zh-CN,zh-CN$$(SPACE)zh-Hans-CN, $$($1_NON_EN_LOCALES))
-  $1_NON_EN_LOCALES := $$(subst zh-SG,zh-SG$$(SPACE)zh-Hans-SG, $$($1_NON_EN_LOCALES))
-  $1_NON_EN_LOCALES := $$(subst zh-HK,zh-HK$$(SPACE)zh-Hant-HK, $$($1_NON_EN_LOCALES))
-  $1_NON_EN_LOCALES := $$(subst zh-MO,zh-MO$$(SPACE)zh-Hant-MO, $$($1_NON_EN_LOCALES))
-  $1_NON_EN_LOCALES := $$(subst zh-TW,zh-TW$$(SPACE)zh-Hant-TW, $$($1_NON_EN_LOCALES))
-
-  ALL_EN_LOCALES += $$($1_EN_LOCALES)
-  ALL_NON_EN_LOCALES += $$($1_NON_EN_LOCALES)
-
-  # Don't sed in a space if there are no locales.
-  SED_ENARGS += -e 's/$$(HASH)$1_Locales$$(HASH)/$$(if $$($1_EN_LOCALES),$$(SPACE)$$($1_EN_LOCALES),)/g'
-  SED_NONENARGS += -e 's/$$(HASH)$1_Locales$$(HASH)/$$(if $$($1_NON_EN_LOCALES),$$(SPACE)$$($1_NON_EN_LOCALES),)/g'
-endef
-
-#sun.text.resources.FormatData
-$(eval $(call CaptureLocale,FormatData))
-
-#sun.text.resources.CollationData
-$(eval $(call CaptureLocale,CollationData))
-
-#sun.text.resources.BreakIteratorInfo
-$(eval $(call CaptureLocale,BreakIteratorInfo))
-
-#sun.text.resources.BreakIteratorRules
-$(eval $(call CaptureLocale,BreakIteratorRules))
-
-#sun.util.resources.TimeZoneNames
-$(eval $(call CaptureLocale,TimeZoneNames))
-
-#sun.util.resources.LocaleNames
-$(eval $(call CaptureLocale,LocaleNames))
-
-#sun.util.resources.CurrencyNames
-$(eval $(call CaptureLocale,CurrencyNames))
-
-#sun.util.resources.CalendarData
-$(eval $(call CaptureLocale,CalendarData))
-
-SED_ENARGS += -e 's/$(HASH)AvailableLocales_Locales$(HASH)/$(sort $(ALL_EN_LOCALES))/g'
-SED_NONENARGS += -e 's/$(HASH)AvailableLocales_Locales$(HASH)/$(sort $(ALL_NON_EN_LOCALES))/g'
-
-$(JDK_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/EnLocaleDataMetaInfo.java: \
-    $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/locale/provider/LocaleDataMetaInfo-XLocales.java.template
-	$(MKDIR) -p $(@D)
-	$(ECHO) Creating sun/util/locale/provider/EnLocaleDataMetaInfo.java from $(words $(LOCALE_RESOURCES)) found resources.
-	$(PRINTF) "PREV_LOCALE_RESOURCES:=$(LOCALE_RESOURCES)" > $(JDK_OUTPUTDIR)/gensrc/_the.locale_resources
-	$(SED) $(SED_ENARGS) $< > $@
-
-$(JDK_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonEnLocaleDataMetaInfo.java: \
-    $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/locale/provider/LocaleDataMetaInfo-XLocales.java.template
-	$(MKDIR) -p $(@D)
-	$(ECHO) Creating sun/util/resources/provider/NonEnLocaleDataMetaInfo.java from $(words $(LOCALE_RESOURCES)) found resources.
-	$(PRINTF) "PREV_LOCALE_RESOURCES:=$(LOCALE_RESOURCES)" > $(JDK_OUTPUTDIR)/gensrc/_the.locale_resources
-	$(SED) $(SED_NONENARGS) $< > $@
-
-GENSRC_LOCALEDATAMETAINFO := $(JDK_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/EnLocaleDataMetaInfo.java \
-    $(JDK_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonEnLocaleDataMetaInfo.java
-
-################################################################################
-
-GENSRC_CRBC_DST := $(JDK_OUTPUTDIR)/gensrc/java.base/sun/util/CoreResourceBundleControl.java
-GENSRC_CRBC_CMD := $(JDK_TOPDIR)/make/scripts/localelist.sh
-
-JRE_NONEXIST_LOCALES := en en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR sv_SE zh
-
-$(GENSRC_CRBC_DST): $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/CoreResourceBundleControl-XLocales.java.template \
-    $(GENSRC_CRBC_CMD)
-	$(MKDIR) -p $(@D)
-	NAWK="$(NAWK)" SED="$(SED)" $(SH) $(GENSRC_CRBC_CMD) "$(JRE_NONEXIST_LOCALES)" $< $@
-
-GENSRC_LOCALEDATAMETAINFO += $(GENSRC_CRBC_DST)
-GENSRC_JAVA_BASE += $(GENSRC_LOCALEDATAMETAINFO)
-
-################################################################################
--- a/jdk/make/lib/Awt2dLibraries.gmk	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/make/lib/Awt2dLibraries.gmk	Fri Sep 19 13:47:19 2014 -0700
@@ -217,10 +217,8 @@
       -I$(JDK_OUTPUTDIR)/gensrc_headers/java.base \
       #
   LIBAWT_EXFILES += \
-      sun/java2d/d3d/D3DPipeline.cpp \
       sun/java2d/d3d/D3DShaderGen.c \
       sun/awt/image/cvutils/img_colors.c \
-      sun/windows/WBufferStrategy.cpp \
       #
 
   LIBAWT_LANG := C++
--- a/jdk/make/src/classes/build/tools/cldrconverter/ResourceBundleGenerator.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/make/src/classes/build/tools/cldrconverter/ResourceBundleGenerator.java	Fri Sep 19 13:47:19 2014 -0700
@@ -143,8 +143,9 @@
 
     @Override
     public void generateMetaInfo(Map<String, SortedSet<String>> metaInfo) throws IOException {
-        String dirName = CLDRConverter.DESTINATION_DIR + File.separator + "sun" + File.separator + "util" + File.separator
-                + "cldr" + File.separator;
+        String dirName = CLDRConverter.DESTINATION_DIR + File.separator + "sun" + File.separator + "util" +
+            File.separator + "resources" + File.separator + "cldr" + File.separator +
+            "provider" + File.separator ;
         File dir = new File(dirName);
         if (!dir.exists()) {
             dir.mkdirs();
@@ -158,7 +159,7 @@
         try (PrintWriter out = new PrintWriter(file, "us-ascii")) {
             out.println(CopyrightHeaders.getOpenJDKCopyright());
 
-            out.println("package sun.util.cldr;\n\n"
+            out.println("package sun.util.resources.cldr.provider;\n\n"
                       + "import java.util.ListResourceBundle;\n"
                       + "import sun.util.locale.provider.LocaleProviderAdapter;\n"
                       + "import sun.util.locale.provider.LocaleDataMetaInfo;\n");
--- a/jdk/make/src/classes/build/tools/module/GenJdepsModulesXml.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/make/src/classes/build/tools/module/GenJdepsModulesXml.java	Fri Sep 19 13:47:19 2014 -0700
@@ -25,29 +25,17 @@
 
 package build.tools.module;
 
-import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
+import java.io.UncheckedIOException;
 import java.nio.file.Files;
 import java.nio.file.NoSuchFileException;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.nio.file.attribute.BasicFileAttributes;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Map;
-import java.util.Objects;
 import java.util.Set;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import javax.xml.namespace.QName;
-import javax.xml.stream.*;
-import javax.xml.stream.events.Attribute;
-import javax.xml.stream.events.XMLEvent;
+import java.util.stream.Collectors;
 
 /**
  * GenJdepsModulesXml augments the input modules.xml file(s)
@@ -97,14 +85,14 @@
         Set<Module> modules = new HashSet<>();
         for (; i < args.length; i++) {
             Path p = Paths.get(args[i]);
-            try (InputStream in = new BufferedInputStream(Files.newInputStream(p))) {
-                Set<Module> mods = gentool.load(in);
-                modules.addAll(mods);
-            }
+            modules.addAll(ModulesXmlReader.readModules(p)
+                    .stream()
+                    .map(gentool::buildIncludes)
+                    .collect(Collectors.toSet()));
         }
 
         Files.createDirectories(outfile.getParent());
-        gentool.writeXML(modules, outfile);
+        ModulesXmlWriter.writeModules(modules, outfile);
     }
 
     final Path modulepath;
@@ -112,228 +100,21 @@
         this.modulepath = modulepath;
     }
 
-    private static final String MODULES   = "modules";
-    private static final String MODULE    = "module";
-    private static final String NAME      = "name";
-    private static final String DEPEND    = "depend";
-    private static final String EXPORT    = "export";
-    private static final String TO        = "to";
-    private static final String INCLUDE   = "include";
-    private static final QName  REEXPORTS = new QName("re-exports");
-    private Set<Module> load(InputStream in) throws XMLStreamException, IOException {
-        Set<Module> modules = new HashSet<>();
-        XMLInputFactory factory = XMLInputFactory.newInstance();
-        XMLEventReader stream = factory.createXMLEventReader(in);
-        Module.Builder mb = null;
-        String modulename = null;
-        String pkg = null;
-        Set<String> permits = new HashSet<>();
-        while (stream.hasNext()) {
-            XMLEvent event = stream.nextEvent();
-            if (event.isStartElement()) {
-                String startTag = event.asStartElement().getName().getLocalPart();
-                switch (startTag) {
-                    case MODULES:
-                        break;
-                    case MODULE:
-                        if (mb != null) {
-                            throw new RuntimeException("end tag for module is missing");
-                        }
-                        modulename = getNextTag(stream, NAME);
-                        mb = new Module.Builder();
-                        mb.name(modulename);
-                        break;
-                    case NAME:
-                        throw new RuntimeException(event.toString());
-                    case DEPEND:
-                        boolean reexports = false;
-                        Attribute attr = event.asStartElement().getAttributeByName(REEXPORTS);
-                        if (attr != null) {
-                            String value = attr.getValue();
-                            if (value.equals("true") || value.equals("false")) {
-                                reexports = Boolean.parseBoolean(value);
-                            } else {
-                                throw new RuntimeException("unexpected attribute " + attr.toString());
-                            }
-                        }
-                        mb.require(getData(stream), reexports);
-                        break;
-                    case INCLUDE:
-                        throw new RuntimeException("unexpected " + event);
-                    case EXPORT:
-                        pkg = getNextTag(stream, NAME);
-                        break;
-                    case TO:
-                        permits.add(getData(stream));
-                        break;
-                    default:
-                }
-            } else if (event.isEndElement()) {
-                String endTag = event.asEndElement().getName().getLocalPart();
-                switch (endTag) {
-                    case MODULE:
-                        buildIncludes(mb, modulename);
-                        modules.add(mb.build());
-                        mb = null;
-                        break;
-                    case EXPORT:
-                        if (pkg == null) {
-                            throw new RuntimeException("export-to is malformed");
-                        }
-                        mb.exportTo(pkg, permits);
-                        pkg = null;
-                        permits.clear();
-                        break;
-                    default:
-                }
-            } else if (event.isCharacters()) {
-                String s = event.asCharacters().getData();
-                if (!s.trim().isEmpty()) {
-                    throw new RuntimeException("export-to is malformed");
-                }
-            }
-        }
-        return modules;
-    }
-
-    private String getData(XMLEventReader reader) throws XMLStreamException {
-        XMLEvent e = reader.nextEvent();
-        if (e.isCharacters()) {
-            return e.asCharacters().getData();
-        }
-        throw new RuntimeException(e.toString());
-    }
-
-    private String getNextTag(XMLEventReader reader, String tag) throws XMLStreamException {
-        XMLEvent e = reader.nextTag();
-        if (e.isStartElement()) {
-            String t = e.asStartElement().getName().getLocalPart();
-            if (!tag.equals(t)) {
-                throw new RuntimeException(e + " expected: " + tag);
-            }
-            return getData(reader);
-        }
-        throw new RuntimeException("export-to name is missing:" + e);
-    }
-    private void writeXML(Set<Module> modules, Path path)
-            throws IOException, XMLStreamException
-    {
-        XMLOutputFactory xof = XMLOutputFactory.newInstance();
-        try (OutputStream out = Files.newOutputStream(path)) {
-            int depth = 0;
-            XMLStreamWriter xtw = xof.createXMLStreamWriter(out, "UTF-8");
-            xtw.writeStartDocument("utf-8","1.0");
-            writeStartElement(xtw, MODULES, depth);
-            modules.stream()
-                   .sorted(Comparator.comparing(Module::name))
-                   .forEach(m -> writeModuleElement(xtw, m, depth+1));
-            writeEndElement(xtw, depth);
-            xtw.writeCharacters("\n");
-            xtw.writeEndDocument();
-            xtw.flush();
-            xtw.close();
-        }
-    }
-
-    private void writeElement(XMLStreamWriter xtw, String element, String value, int depth) {
-        try {
-            writeStartElement(xtw, element, depth);
-            xtw.writeCharacters(value);
-            xtw.writeEndElement();
-        } catch (XMLStreamException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    private void writeDependElement(XMLStreamWriter xtw, Module.Dependence d, int depth) {
-        try {
-            writeStartElement(xtw, DEPEND, depth);
-            if (d.reexport) {
-                xtw.writeAttribute("re-exports", "true");
-            }
-            xtw.writeCharacters(d.name);
-            xtw.writeEndElement();
-        } catch (XMLStreamException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    private void writeExportElement(XMLStreamWriter xtw, String pkg, int depth) {
-        writeExportElement(xtw, pkg, Collections.emptySet(), depth);
-    }
-
-    private void writeExportElement(XMLStreamWriter xtw, String pkg,
-                                    Set<String> permits, int depth) {
-        try {
-            writeStartElement(xtw, EXPORT, depth);
-            writeElement(xtw, NAME, pkg, depth+1);
-            if (!permits.isEmpty()) {
-                permits.stream().sorted()
-                       .forEach(m -> writeElement(xtw, TO, m, depth + 1));
-            }
-            writeEndElement(xtw, depth);
-        } catch (XMLStreamException e) {
-            throw new RuntimeException(e);
-        }
-    }
-    private void writeModuleElement(XMLStreamWriter xtw, Module m, int depth) {
-        try {
-            writeStartElement(xtw, MODULE, depth);
-            writeElement(xtw, NAME, m.name(), depth+1);
-            m.requires().stream().sorted(Comparator.comparing(d -> d.name))
-                        .forEach(d -> writeDependElement(xtw, d, depth+1));
-            m.exports().keySet().stream()
-                       .filter(pn -> m.exports().get(pn).isEmpty())
-                       .sorted()
-                       .forEach(pn -> writeExportElement(xtw, pn, depth+1));
-            m.exports().entrySet().stream()
-                       .filter(e -> !e.getValue().isEmpty())
-                       .sorted(Map.Entry.comparingByKey())
-                       .forEach(e -> writeExportElement(xtw, e.getKey(), e.getValue(), depth+1));
-            m.packages().stream().sorted()
-                        .forEach(p -> writeElement(xtw, INCLUDE, p, depth+1));
-            writeEndElement(xtw, depth);
-        } catch (XMLStreamException e) {
-            throw new RuntimeException(e);
-
-        }
-    }
-
-    /** Two spaces; the default indentation. */
-    public static final String DEFAULT_INDENT = "  ";
-
-    /** stack[depth] indicates what's been written into the current scope. */
-    private static String[] stack = new String[] { "\n",
-        "\n" + DEFAULT_INDENT,
-        "\n" + DEFAULT_INDENT + DEFAULT_INDENT,
-        "\n" + DEFAULT_INDENT + DEFAULT_INDENT + DEFAULT_INDENT};
-
-    private void writeStartElement(XMLStreamWriter xtw, String name, int depth)
-            throws XMLStreamException
-    {
-        xtw.writeCharacters(stack[depth]);
-        xtw.writeStartElement(name);
-    }
-
-    private void writeEndElement(XMLStreamWriter xtw, int depth) throws XMLStreamException {
-        xtw.writeCharacters(stack[depth]);
-        xtw.writeEndElement();
-    }
-
-    private String packageName(Path p) {
+    private static String packageName(Path p) {
         return packageName(p.toString().replace(File.separatorChar, '/'));
     }
-    private String packageName(String name) {
+    private static String packageName(String name) {
         int i = name.lastIndexOf('/');
         return (i > 0) ? name.substring(0, i).replace('/', '.') : "";
     }
 
-    private boolean includes(String name) {
-        return name.endsWith(".class") && !name.equals("module-info.class");
+    private static boolean includes(String name) {
+        return name.endsWith(".class");
     }
 
-    public void buildIncludes(Module.Builder mb, String modulename) throws IOException {
-        Path mclasses = modulepath.resolve(modulename);
+    public Module buildIncludes(Module module) {
+        Module.Builder mb = new Module.Builder(module);
+        Path mclasses = modulepath.resolve(module.name());
         try {
             Files.find(mclasses, Integer.MAX_VALUE, (Path p, BasicFileAttributes attr)
                          -> includes(p.getFileName().toString()))
@@ -341,145 +122,9 @@
                  .forEach(mb::include);
         } catch (NoSuchFileException e) {
             // aggregate module may not have class
+        } catch (IOException ioe) {
+            throw new UncheckedIOException(ioe);
         }
-    }
-
-    static class Module {
-        static class Dependence {
-            final String name;
-            final boolean reexport;
-            Dependence(String name) {
-                this(name, false);
-            }
-            Dependence(String name, boolean reexport) {
-                this.name = name;
-                this.reexport = reexport;
-            }
-
-            @Override
-            public int hashCode() {
-                int hash = 5;
-                hash = 11 * hash + Objects.hashCode(this.name);
-                hash = 11 * hash + (this.reexport ? 1 : 0);
-                return hash;
-            }
-
-            public boolean equals(Object o) {
-                Dependence d = (Dependence)o;
-                return this.name.equals(d.name) && this.reexport == d.reexport;
-            }
-        }
-        private final String moduleName;
-        private final Set<Dependence> requires;
-        private final Map<String, Set<String>> exports;
-        private final Set<String> packages;
-
-        private Module(String name,
-                Set<Dependence> requires,
-                Map<String, Set<String>> exports,
-                Set<String> packages) {
-            this.moduleName = name;
-            this.requires = Collections.unmodifiableSet(requires);
-            this.exports = Collections.unmodifiableMap(exports);
-            this.packages = Collections.unmodifiableSet(packages);
-        }
-
-        public String name() {
-            return moduleName;
-        }
-
-        public Set<Dependence> requires() {
-            return requires;
-        }
-
-        public Map<String, Set<String>> exports() {
-            return exports;
-        }
-
-        public Set<String> packages() {
-            return packages;
-        }
-
-        @Override
-        public boolean equals(Object ob) {
-            if (!(ob instanceof Module)) {
-                return false;
-            }
-            Module that = (Module) ob;
-            return (moduleName.equals(that.moduleName)
-                    && requires.equals(that.requires)
-                    && exports.equals(that.exports)
-                    && packages.equals(that.packages));
-        }
-
-        @Override
-        public int hashCode() {
-            int hc = moduleName.hashCode();
-            hc = hc * 43 + requires.hashCode();
-            hc = hc * 43 + exports.hashCode();
-            hc = hc * 43 + packages.hashCode();
-            return hc;
-        }
-
-        @Override
-        public String toString() {
-            StringBuilder sb = new StringBuilder();
-            sb.append("module ").append(moduleName).append(" {").append("\n");
-            requires.stream().sorted().forEach(d ->
-                    sb.append(String.format("   requires %s%s%n", d.reexport ? "public " : "", d.name)));
-            exports.entrySet().stream().filter(e -> e.getValue().isEmpty())
-                    .sorted(Map.Entry.comparingByKey())
-                    .forEach(e -> sb.append(String.format("   exports %s%n", e.getKey())));
-            exports.entrySet().stream().filter(e -> !e.getValue().isEmpty())
-                    .sorted(Map.Entry.comparingByKey())
-                    .forEach(e -> sb.append(String.format("   exports %s to %s%n", e.getKey(), e.getValue())));
-            packages.stream().sorted().forEach(pn -> sb.append(String.format("   includes %s%n", pn)));
-            sb.append("}");
-            return sb.toString();
-        }
-
-        static class Builder {
-            private String name;
-            private final Set<Dependence> requires = new HashSet<>();
-            private final Map<String, Set<String>> exports = new HashMap<>();
-            private final Set<String> packages = new HashSet<>();
-
-            public Builder() {
-            }
-
-            public Builder name(String n) {
-                name = n;
-                return this;
-            }
-
-            public Builder require(String d, boolean reexport) {
-                requires.add(new Dependence(d, reexport));
-                return this;
-            }
-
-            public Builder include(String p) {
-                packages.add(p);
-                return this;
-            }
-
-            public Builder export(String p) {
-                return exportTo(p, Collections.emptySet());
-            }
-
-            public Builder exportTo(String p, Set<String> ms) {
-                Objects.requireNonNull(p);
-                Objects.requireNonNull(ms);
-                if (exports.containsKey(p)) {
-                    throw new RuntimeException(name + " already exports " + p);
-                }
-                exports.put(p, new HashSet<>(ms));
-                return this;
-            }
-
-            public Module build() {
-                Module m = new Module(name, requires, exports, packages);
-                return m;
-            }
-        }
+        return mb.build();
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/src/classes/build/tools/module/GenModulesList.java	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package build.tools.module;
+
+import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * $ java build.tools.module.GenModulesList \
+ *        -o modules.list \
+ *        top/modules.xml ...
+ */
+public final class GenModulesList {
+    private final static String USAGE =
+        "Usage: GenModulesList -o <output file> path-to-modules-xml";
+
+    private Set<Module> modules = new HashSet<>();
+    private HashMap<String,Module> nameToModule = new HashMap<>();
+
+    public static void main(String[] args) throws Exception {
+        GenModulesList gen = new GenModulesList();
+        gen.run(args);
+    }
+
+    void run(String[] args) throws Exception {
+        Path outfile = null;
+        int i = 0;
+        while (i < args.length) {
+            String arg = args[i];
+            if (arg.equals("-o")) {
+                outfile = Paths.get(args[i+1]);
+                i = i+2;
+            } else {
+                break;
+            }
+        }
+        if (outfile == null || i >= args.length) {
+            System.err.println(USAGE);
+            System.exit(-1);
+        }
+
+        for (; i < args.length; i++) {
+            Path p = Paths.get(args[i]);
+            modules.addAll(ModulesXmlReader.readModules(p));
+        }
+
+        modules.stream()
+               .forEach(m -> nameToModule.put(m.name(), m));
+
+        Path parent = outfile.getParent();
+        if (parent != null)
+            Files.createDirectories(parent);
+
+        Iterable<Module> sortedModules = (new TopoSorter(modules)).result();
+        try (PrintWriter writer = new PrintWriter(outfile.toFile())) {
+            for (Module m : sortedModules) {
+                if (isNotAggregator(m)) {
+                    String deps = getModuleDependences(m).stream()
+                            .filter(GenModulesList::isNotAggregator)
+                            .map(Module::name)
+                            .collect(Collectors.joining(" "));
+                    writer.format("%s: %s%n", m.name(), deps);
+                }
+            }
+        }
+    }
+
+    private Module nameToModule(String name) {
+        return nameToModule.get(name);
+    }
+
+    private Set<Module> getModuleDependences(Module m) {
+        return m.requires().stream()
+                .map(d -> d.name())
+                .map(this::nameToModule)
+                .collect(Collectors.toSet());
+    }
+
+    static boolean isNotAggregator(Module m) {
+        return isNotAggregator(m.name());
+    }
+
+    static boolean isNotAggregator(String name) {
+        return AGGREGATORS.contains(name) ? false : true;
+    }
+
+    static final List<String> AGGREGATORS = Arrays.asList(new String[] {
+            "java.se", "java.compact1", "java.compact2",
+            "java.compact3", "jdk.compact3"});
+
+    class TopoSorter {
+        final Deque<Module> result = new LinkedList<>();
+        final Deque<Module> nodes = new LinkedList<>();
+
+        TopoSorter(Collection<Module> nodes) {
+            nodes.stream()
+                 .forEach(m -> this.nodes.add(m));
+
+            sort();
+        }
+
+        public Iterable<Module> result() {
+            return result;
+        }
+
+        private void sort() {
+            Deque<Module> visited = new LinkedList<>();
+            Deque<Module> done = new LinkedList<>();
+            Module node;
+            while ((node = nodes.poll()) != null) {
+                if (!visited.contains(node)) {
+                    visit(node, visited, done);
+                }
+            }
+        }
+
+        private void visit(Module m, Deque<Module> visited, Deque<Module> done) {
+            if (visited.contains(m)) {
+                if (!done.contains(m)) {
+                    throw new IllegalArgumentException("Cyclic detected: " +
+                            m + " " + getModuleDependences(m));
+                }
+                return;
+            }
+            visited.add(m);
+            getModuleDependences(m).stream()
+                                   .forEach(x -> visit(x, visited, done));
+            done.add(m);
+            result.addLast(m);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/src/classes/build/tools/module/Module.java	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package build.tools.module;
+
+import java.util.*;
+
+public class Module {
+    static class Dependence {
+        final String name;
+        final boolean reexport;
+        Dependence(String name) {
+            this(name, false);
+        }
+        Dependence(String name, boolean reexport) {
+            this.name = name;
+            this.reexport = reexport;
+        }
+
+        public String name() {
+            return name;
+        }
+
+        @Override
+        public int hashCode() {
+            int hash = 5;
+            hash = 11 * hash + Objects.hashCode(this.name);
+            hash = 11 * hash + (this.reexport ? 1 : 0);
+            return hash;
+        }
+
+        public boolean equals(Object o) {
+            Dependence d = (Dependence)o;
+            return this.name.equals(d.name) && this.reexport == d.reexport;
+        }
+    }
+    private final String moduleName;
+    private final Set<Dependence> requires;
+    private final Map<String, Set<String>> exports;
+    private final Set<String> packages;
+
+    private Module(String name,
+            Set<Dependence> requires,
+            Map<String, Set<String>> exports,
+            Set<String> packages) {
+        this.moduleName = name;
+        this.requires = Collections.unmodifiableSet(requires);
+        this.exports = Collections.unmodifiableMap(exports);
+        this.packages = Collections.unmodifiableSet(packages);
+    }
+
+    public String name() {
+        return moduleName;
+    }
+
+    public Set<Dependence> requires() {
+        return requires;
+    }
+
+    public Map<String, Set<String>> exports() {
+        return exports;
+    }
+
+    public Set<String> packages() {
+        return packages;
+    }
+
+    @Override
+    public boolean equals(Object ob) {
+        if (!(ob instanceof Module)) {
+            return false;
+        }
+        Module that = (Module) ob;
+        return (moduleName.equals(that.moduleName)
+                && requires.equals(that.requires)
+                && exports.equals(that.exports)
+                && packages.equals(that.packages));
+    }
+
+    @Override
+    public int hashCode() {
+        int hc = moduleName.hashCode();
+        hc = hc * 43 + requires.hashCode();
+        hc = hc * 43 + exports.hashCode();
+        hc = hc * 43 + packages.hashCode();
+        return hc;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("module ").append(moduleName).append(" {").append("\n");
+        requires.stream().sorted().forEach(d ->
+                sb.append(String.format("   requires %s%s%n", d.reexport ? "public " : "", d.name)));
+        exports.entrySet().stream().filter(e -> e.getValue().isEmpty())
+                .sorted(Map.Entry.comparingByKey())
+                .forEach(e -> sb.append(String.format("   exports %s%n", e.getKey())));
+        exports.entrySet().stream().filter(e -> !e.getValue().isEmpty())
+                .sorted(Map.Entry.comparingByKey())
+                .forEach(e -> sb.append(String.format("   exports %s to %s%n", e.getKey(), e.getValue())));
+        packages.stream().sorted().forEach(pn -> sb.append(String.format("   includes %s%n", pn)));
+        sb.append("}");
+        return sb.toString();
+    }
+
+    static class Builder {
+        private String name;
+        private final Set<Dependence> requires = new HashSet<>();
+        private final Map<String, Set<String>> exports = new HashMap<>();
+        private final Set<String> packages = new HashSet<>();
+
+        public Builder() {
+        }
+
+        public Builder(Module module) {
+            name = module.name();
+            requires.addAll(module.requires());
+            exports.putAll(module.exports());
+            packages.addAll(module.packages());
+        }
+
+        public Builder name(String n) {
+            name = n;
+            return this;
+        }
+
+        public Builder require(String d, boolean reexport) {
+            requires.add(new Dependence(d, reexport));
+            return this;
+        }
+
+        public Builder include(String p) {
+            packages.add(p);
+            return this;
+        }
+
+        public Builder export(String p) {
+            return exportTo(p, Collections.emptySet());
+        }
+
+        public Builder exportTo(String p, Set<String> ms) {
+            Objects.requireNonNull(p);
+            Objects.requireNonNull(ms);
+            if (exports.containsKey(p)) {
+                throw new RuntimeException(name + " already exports " + p);
+            }
+            exports.put(p, new HashSet<>(ms));
+            return this;
+        }
+
+        public Module build() {
+            Module m = new Module(name, requires, exports, packages);
+            return m;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/src/classes/build/tools/module/ModulesXmlReader.java	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package build.tools.module;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLEventReader;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.Attribute;
+import javax.xml.stream.events.XMLEvent;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashSet;
+import java.util.Set;
+
+public class ModulesXmlReader {
+
+    private ModulesXmlReader() {}
+
+    public static Set<Module> readModules(Path modulesXml)
+        throws XMLStreamException, IOException
+    {
+        Set<Module> modules = new HashSet<>();
+        try (InputStream in = new BufferedInputStream(Files.newInputStream(modulesXml))) {
+            Set<Module> mods = ModulesXmlReader.load(in);
+            modules.addAll(mods);
+        }
+        return modules;
+    }
+
+    private static final String MODULES   = "modules";
+    private static final String MODULE    = "module";
+    private static final String NAME      = "name";
+    private static final String DEPEND    = "depend";
+    private static final String EXPORT    = "export";
+    private static final String TO        = "to";
+    private static final String INCLUDE   = "include";
+    private static final QName  REEXPORTS = new QName("re-exports");
+    private static Set<Module> load(InputStream in)
+        throws XMLStreamException, IOException
+    {
+        Set<Module> modules = new HashSet<>();
+        XMLInputFactory factory = XMLInputFactory.newInstance();
+        XMLEventReader stream = factory.createXMLEventReader(in);
+        Module.Builder mb = null;
+        String modulename = null;
+        String pkg = null;
+        Set<String> permits = new HashSet<>();
+        while (stream.hasNext()) {
+            XMLEvent event = stream.nextEvent();
+            if (event.isStartElement()) {
+                String startTag = event.asStartElement().getName().getLocalPart();
+                switch (startTag) {
+                    case MODULES:
+                        break;
+                    case MODULE:
+                        if (mb != null) {
+                            throw new RuntimeException("end tag for module is missing");
+                        }
+                        modulename = getNextTag(stream, NAME);
+                        mb = new Module.Builder();
+                        mb.name(modulename);
+                        break;
+                    case NAME:
+                        throw new RuntimeException(event.toString());
+                    case DEPEND:
+                        boolean reexports = false;
+                        Attribute attr = event.asStartElement().getAttributeByName(REEXPORTS);
+                        if (attr != null) {
+                            String value = attr.getValue();
+                            if (value.equals("true") || value.equals("false")) {
+                                reexports = Boolean.parseBoolean(value);
+                            } else {
+                                throw new RuntimeException("unexpected attribute " + attr.toString());
+                            }
+                        }
+                        mb.require(getData(stream), reexports);
+                        break;
+                    case INCLUDE:
+                        throw new RuntimeException("unexpected " + event);
+                    case EXPORT:
+                        pkg = getNextTag(stream, NAME);
+                        break;
+                    case TO:
+                        permits.add(getData(stream));
+                        break;
+                    default:
+                }
+            } else if (event.isEndElement()) {
+                String endTag = event.asEndElement().getName().getLocalPart();
+                switch (endTag) {
+                    case MODULE:
+                        modules.add(mb.build());
+                        mb = null;
+                        break;
+                    case EXPORT:
+                        if (pkg == null) {
+                            throw new RuntimeException("export-to is malformed");
+                        }
+                        mb.exportTo(pkg, permits);
+                        pkg = null;
+                        permits.clear();
+                        break;
+                    default:
+                }
+            } else if (event.isCharacters()) {
+                String s = event.asCharacters().getData();
+                if (!s.trim().isEmpty()) {
+                    throw new RuntimeException("export-to is malformed");
+                }
+            }
+        }
+        return modules;
+    }
+
+    private static String getData(XMLEventReader reader)
+        throws XMLStreamException
+    {
+        XMLEvent e = reader.nextEvent();
+        if (e.isCharacters())
+            return e.asCharacters().getData();
+
+        throw new RuntimeException(e.toString());
+    }
+
+    private static String getNextTag(XMLEventReader reader, String tag)
+        throws XMLStreamException
+    {
+        XMLEvent e = reader.nextTag();
+        if (e.isStartElement()) {
+            String t = e.asStartElement().getName().getLocalPart();
+            if (!tag.equals(t)) {
+                throw new RuntimeException(e + " expected: " + tag);
+            }
+            return getData(reader);
+        }
+        throw new RuntimeException("export-to name is missing:" + e);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/src/classes/build/tools/module/ModulesXmlWriter.java	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package build.tools.module;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Map;
+import java.util.Set;
+
+public final class ModulesXmlWriter {
+
+    private ModulesXmlWriter() {}
+
+    public static void writeModules(Set<Module> modules, Path path)
+        throws IOException, XMLStreamException
+    {
+        writeXML(modules, path);
+    }
+
+    private static final String MODULES   = "modules";
+    private static final String MODULE    = "module";
+    private static final String NAME      = "name";
+    private static final String DEPEND    = "depend";
+    private static final String EXPORT    = "export";
+    private static final String TO        = "to";
+    private static final String INCLUDE   = "include";
+    private static final QName  REEXPORTS = new QName("re-exports");
+
+    private static void writeXML(Set<Module> modules, Path path)
+        throws IOException, XMLStreamException
+    {
+        XMLOutputFactory xof = XMLOutputFactory.newInstance();
+        try (OutputStream out = Files.newOutputStream(path)) {
+            int depth = 0;
+            XMLStreamWriter xtw = xof.createXMLStreamWriter(out, "UTF-8");
+            xtw.writeStartDocument("utf-8","1.0");
+            writeStartElement(xtw, MODULES, depth);
+            modules.stream()
+                   .sorted(Comparator.comparing(Module::name))
+                   .forEach(m -> writeModuleElement(xtw, m, depth+1));
+            writeEndElement(xtw, depth);
+            xtw.writeCharacters("\n");
+            xtw.writeEndDocument();
+            xtw.flush();
+            xtw.close();
+        }
+    }
+
+    private static void writeElement(XMLStreamWriter xtw,
+                                     String element,
+                                     String value,
+                                     int depth) {
+        try {
+            writeStartElement(xtw, element, depth);
+            xtw.writeCharacters(value);
+            xtw.writeEndElement();
+        } catch (XMLStreamException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private static void writeDependElement(XMLStreamWriter xtw,
+                                           Module.Dependence d,
+                                           int depth) {
+        try {
+            writeStartElement(xtw, DEPEND, depth);
+            if (d.reexport) {
+                xtw.writeAttribute("re-exports", "true");
+            }
+            xtw.writeCharacters(d.name);
+            xtw.writeEndElement();
+        } catch (XMLStreamException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private static void writeExportElement(XMLStreamWriter xtw,
+                                           String pkg,
+                                           int depth) {
+        writeExportElement(xtw, pkg, Collections.emptySet(), depth);
+    }
+
+    private static void writeExportElement(XMLStreamWriter xtw,
+                                           String pkg,
+                                           Set<String> permits,
+                                           int depth) {
+        try {
+            writeStartElement(xtw, EXPORT, depth);
+            writeElement(xtw, NAME, pkg, depth+1);
+            if (!permits.isEmpty()) {
+                permits.stream().sorted()
+                       .forEach(m -> writeElement(xtw, TO, m, depth + 1));
+            }
+            writeEndElement(xtw, depth);
+        } catch (XMLStreamException e) {
+            throw new RuntimeException(e);
+        }
+    }
+    private static void writeModuleElement(XMLStreamWriter xtw,
+                                           Module m,
+                                           int depth) {
+        try {
+            writeStartElement(xtw, MODULE, depth);
+            writeElement(xtw, NAME, m.name(), depth+1);
+            m.requires().stream().sorted(Comparator.comparing(d -> d.name))
+                        .forEach(d -> writeDependElement(xtw, d, depth+1));
+            m.exports().keySet().stream()
+                       .filter(pn -> m.exports().get(pn).isEmpty())
+                       .sorted()
+                       .forEach(pn -> writeExportElement(xtw, pn, depth+1));
+            m.exports().entrySet().stream()
+                       .filter(e -> !e.getValue().isEmpty())
+                       .sorted(Map.Entry.comparingByKey())
+                       .forEach(e -> writeExportElement(xtw, e.getKey(), e.getValue(), depth+1));
+            m.packages().stream().sorted()
+                        .forEach(p -> writeElement(xtw, INCLUDE, p, depth+1));
+            writeEndElement(xtw, depth);
+        } catch (XMLStreamException e) {
+            throw new RuntimeException(e);
+
+        }
+    }
+
+    /** Two spaces; the default indentation. */
+    public static final String DEFAULT_INDENT = "  ";
+
+    /** stack[depth] indicates what's been written into the current scope. */
+    private static String[] stack = new String[] { "\n",
+        "\n" + DEFAULT_INDENT,
+        "\n" + DEFAULT_INDENT + DEFAULT_INDENT,
+        "\n" + DEFAULT_INDENT + DEFAULT_INDENT + DEFAULT_INDENT};
+
+    private static void writeStartElement(XMLStreamWriter xtw,
+                                          String name,
+                                          int depth)
+        throws XMLStreamException
+    {
+        xtw.writeCharacters(stack[depth]);
+        xtw.writeStartElement(name);
+    }
+
+    private static void writeEndElement(XMLStreamWriter xtw, int depth)
+        throws XMLStreamException
+    {
+        xtw.writeCharacters(stack[depth]);
+        xtw.writeEndElement();
+    }
+}
--- a/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Fri Sep 19 13:47:19 2014 -0700
@@ -62,7 +62,7 @@
     private static final String CLL_SIG = "(L" + CLS + ";L" + OBJ + ";)L" + OBJ + ";";
 
     /** Name of its super class*/
-    private static final String superName = LF;
+    private static final String superName = OBJ;
 
     /** Name of new class */
     private final String className;
@@ -97,7 +97,7 @@
         if (DUMP_CLASS_FILES) {
             className = makeDumpableClassName(className);
         }
-        this.className  = superName + "$" + className;
+        this.className  = LF + "$" + className;
         this.sourceFile = "LambdaForm$" + className;
         this.lambdaForm = lambdaForm;
         this.invokerName = invokerName;
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Fri Sep 19 13:47:19 2014 -0700
@@ -188,7 +188,6 @@
     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
                                             boolean strict, boolean monobox) {
         MethodType dstType = target.type();
-        assert(dstType.parameterCount() == target.type().parameterCount());
         if (srcType == dstType)
             return target;
         if (USE_LAMBDA_FORM_EDITOR) {
@@ -265,6 +264,7 @@
 
     static MethodHandle makePairwiseConvertIndirect(MethodHandle target, MethodType srcType,
                                                     boolean strict, boolean monobox) {
+        assert(target.type().parameterCount() == srcType.parameterCount());
         // Calculate extra arguments (temporaries) required in the names array.
         Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox);
         final int INARG_COUNT = srcType.parameterCount();
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Fri Sep 19 13:47:19 2014 -0700
@@ -2023,8 +2023,9 @@
      */
     public static
     MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
+        explicitCastArgumentsChecks(target, newType);
+        // use the asTypeCache when possible:
         MethodType oldType = target.type();
-        // use the asTypeCache when possible:
         if (oldType == newType)  return target;
         if (oldType.explicitCastEquivalentToAsType(newType)) {
             return target.asType(newType);
@@ -2032,6 +2033,12 @@
         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
     }
 
+    private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
+        if (target.type().parameterCount() != newType.parameterCount()) {
+            throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
+        }
+    }
+
     /**
      * Produces a method handle which adapts the calling sequence of the
      * given method handle to a new type, by reordering the arguments.
@@ -2164,7 +2171,7 @@
                 // dropIdx is missing from reorder; add it in at the end
                 int oldArity = reorder.length;
                 target = dropArguments(target, oldArity, newType.parameterType(dropIdx));
-                reorder = Arrays.copyOf(reorder, oldArity+1);
+                reorder = Arrays.copyOf(reorder, oldArity + 1);
                 reorder[oldArity] = dropIdx;
             }
             assert(target == originalTarget || permuteArgumentChecks(reorder, newType, target.type()));
@@ -2182,9 +2189,9 @@
             long mask = 0;
             for (int arg : reorder) {
                 assert(arg < newArity);
-                mask |= (1 << arg);
+                mask |= (1L << arg);
             }
-            if (mask == (1 << newArity) - 1) {
+            if (mask == (1L << newArity) - 1) {
                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
                 return -1;
             }
@@ -2193,16 +2200,18 @@
             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
             assert(zeroPos < newArity);
             return zeroPos;
+        } else {
+            BitSet mask = new BitSet(newArity);
+            for (int arg : reorder) {
+                assert (arg < newArity);
+                mask.set(arg);
+            }
+            int zeroPos = mask.nextClearBit(0);
+            assert(zeroPos <= newArity);
+            if (zeroPos == newArity)
+                return -1;
+            return zeroPos;
         }
-        BitSet mask = new BitSet(newArity);
-        for (int arg : reorder) {
-            assert(arg < newArity);
-            mask.set(arg);
-        }
-        int zeroPos = mask.nextClearBit(0);
-        if (zeroPos == newArity)
-            return -1;
-        return zeroPos;
     }
 
     /**
@@ -2218,32 +2227,42 @@
             long mask = 0;
             for (int i = 0; i < reorder.length; i++) {
                 int arg = reorder[i];
-                if (arg >= newArity)  return reorder.length;
-                int bit = 1 << arg;
-                if ((mask & bit) != 0)
+                if (arg >= newArity) {
+                    return reorder.length;
+                }
+                long bit = 1L << arg;
+                if ((mask & bit) != 0) {
                     return i;  // >0 indicates a dup
+                }
                 mask |= bit;
             }
-            if (mask == (1 << newArity) - 1) {
+            if (mask == (1L << newArity) - 1) {
                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
                 return 0;
             }
             // find first zero
             long zeroBit = Long.lowestOneBit(~mask);
             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
-            assert(zeroPos < newArity);
+            assert(zeroPos <= newArity);
+            if (zeroPos == newArity) {
+                return 0;
+            }
             return ~zeroPos;
         } else {
             // same algorithm, different bit set
             BitSet mask = new BitSet(newArity);
             for (int i = 0; i < reorder.length; i++) {
                 int arg = reorder[i];
-                if (arg >= newArity)  return reorder.length;
-                if (mask.get(arg))
+                if (arg >= newArity) {
+                    return reorder.length;
+                }
+                if (mask.get(arg)) {
                     return i;  // >0 indicates a dup
+                }
                 mask.set(arg);
             }
             int zeroPos = mask.nextClearBit(0);
+            assert(zeroPos <= newArity);
             if (zeroPos == newArity) {
                 return 0;
             }
@@ -2479,6 +2498,7 @@
     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
         MethodType oldType = target.type();  // get NPE
         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
+        MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
         if (dropped == 0)  return target;
         BoundMethodHandle result = target.rebind();
         LambdaForm lform = result.form;
@@ -2490,7 +2510,6 @@
         } else {
             lform = lform.addArguments(pos, valueTypes);
         }
-        MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
         result = result.copyWith(newType, lform);
         return result;
     }
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java	Fri Sep 19 13:47:19 2014 -0700
@@ -869,9 +869,7 @@
         if (dstTypes == srcTypes) {
             return true;
         }
-        if (dstTypes.length != srcTypes.length) {
-            return false;
-        }
+        assert(dstTypes.length == srcTypes.length);
         for (int i = 0; i < dstTypes.length; i++) {
             if (!explicitCastEquivalentToAsType(srcTypes[i], dstTypes[i])) {
                 return false;
--- a/jdk/src/java.base/share/classes/java/math/MutableBigInteger.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.base/share/classes/java/math/MutableBigInteger.java	Fri Sep 19 13:47:19 2014 -0700
@@ -1261,19 +1261,20 @@
             int sigma = (int) Math.max(0, n32 - b.bitLength());   // step 3: sigma = max{T | (2^T)*B < beta^n}
             MutableBigInteger bShifted = new MutableBigInteger(b);
             bShifted.safeLeftShift(sigma);   // step 4a: shift b so its length is a multiple of n
-            safeLeftShift(sigma);     // step 4b: shift this by the same amount
+            MutableBigInteger aShifted = new MutableBigInteger (this);
+            aShifted.safeLeftShift(sigma);     // step 4b: shift a by the same amount
 
-            // step 5: t is the number of blocks needed to accommodate this plus one additional bit
-            int t = (int) ((bitLength()+n32) / n32);
+            // step 5: t is the number of blocks needed to accommodate a plus one additional bit
+            int t = (int) ((aShifted.bitLength()+n32) / n32);
             if (t < 2) {
                 t = 2;
             }
 
-            // step 6: conceptually split this into blocks a[t-1], ..., a[0]
-            MutableBigInteger a1 = getBlock(t-1, t, n);   // the most significant block of this
+            // step 6: conceptually split a into blocks a[t-1], ..., a[0]
+            MutableBigInteger a1 = aShifted.getBlock(t-1, t, n);   // the most significant block of a
 
             // step 7: z[t-2] = [a[t-1], a[t-2]]
-            MutableBigInteger z = getBlock(t-2, t, n);    // the second to most significant block
+            MutableBigInteger z = aShifted.getBlock(t-2, t, n);    // the second to most significant block
             z.addDisjoint(a1, n);   // z[t-2]
 
             // do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers
@@ -1284,7 +1285,7 @@
                 ri = z.divide2n1n(bShifted, qi);
 
                 // step 8b: z = [ri, a[i-1]]
-                z = getBlock(i-1, t, n);   // a[i-1]
+                z = aShifted.getBlock(i-1, t, n);   // a[i-1]
                 z.addDisjoint(ri, n);
                 quotient.addShifted(qi, i*n);   // update q (part of step 9)
             }
@@ -1292,7 +1293,7 @@
             ri = z.divide2n1n(bShifted, qi);
             quotient.add(qi);
 
-            ri.rightShift(sigma);   // step 9: this and b were shifted, so shift back
+            ri.rightShift(sigma);   // step 9: a and b were shifted, so shift back
             return ri;
         }
     }
--- a/jdk/src/java.base/share/classes/java/util/zip/ZipInputStream.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.base/share/classes/java/util/zip/ZipInputStream.java	Fri Sep 19 13:47:19 2014 -0700
@@ -336,8 +336,21 @@
         return new ZipEntry(name);
     }
 
-    /*
+    /**
      * Reads end of deflated entry as well as EXT descriptor if present.
+     *
+     * Local headers for DEFLATED entries may optionally be followed by a
+     * data descriptor, and that data descriptor may optionally contain a
+     * leading signature (EXTSIG).
+     *
+     * From the zip spec http://www.pkware.com/documents/casestudies/APPNOTE.TXT
+     *
+     * """Although not originally assigned a signature, the value 0x08074b50
+     * has commonly been adopted as a signature value for the data descriptor
+     * record.  Implementers should be aware that ZIP files may be
+     * encountered with or without this signature marking data descriptors
+     * and should account for either case when reading ZIP files to ensure
+     * compatibility."""
      */
     private void readEnd(ZipEntry e) throws IOException {
         int n = inf.getRemaining();
@@ -356,7 +369,7 @@
                     e.csize = get64(tmpbuf, ZIP64_EXTSIZ - ZIP64_EXTCRC);
                     e.size = get64(tmpbuf, ZIP64_EXTLEN - ZIP64_EXTCRC);
                     ((PushbackInputStream)in).unread(
-                        tmpbuf, ZIP64_EXTHDR - ZIP64_EXTCRC - 1, ZIP64_EXTCRC);
+                        tmpbuf, ZIP64_EXTHDR - ZIP64_EXTCRC, ZIP64_EXTCRC);
                 } else {
                     e.crc = get32(tmpbuf, ZIP64_EXTCRC);
                     e.csize = get64(tmpbuf, ZIP64_EXTSIZ);
@@ -370,7 +383,7 @@
                     e.csize = get32(tmpbuf, EXTSIZ - EXTCRC);
                     e.size = get32(tmpbuf, EXTLEN - EXTCRC);
                     ((PushbackInputStream)in).unread(
-                                               tmpbuf, EXTHDR - EXTCRC - 1, EXTCRC);
+                                               tmpbuf, EXTHDR - EXTCRC, EXTCRC);
                 } else {
                     e.crc = get32(tmpbuf, EXTCRC);
                     e.csize = get32(tmpbuf, EXTSIZ);
--- a/jdk/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c	Fri Sep 19 13:47:19 2014 -0700
@@ -34,6 +34,10 @@
 #include <fcntl.h>
 #include <sys/uio.h>
 #include <unistd.h>
+#if defined(__linux__)
+#include <linux/fs.h>
+#include <sys/ioctl.h>
+#endif
 #include "nio.h"
 #include "nio_util.h"
 
@@ -177,10 +181,21 @@
 JNIEXPORT jlong JNICALL
 Java_sun_nio_ch_FileDispatcherImpl_size0(JNIEnv *env, jobject this, jobject fdo)
 {
+    jint fd = fdval(env, fdo);
     struct stat64 fbuf;
 
-    if (fstat64(fdval(env, fdo), &fbuf) < 0)
+    if (fstat64(fd, &fbuf) < 0)
         return handle(env, -1, "Size failed");
+
+#ifdef BLKGETSIZE64
+    if (S_ISBLK(fbuf.st_mode)) {
+        uint64_t size;
+        if (ioctl(fd, BLKGETSIZE64, &size) < 0)
+            return handle(env, -1, "Size failed");
+        return (jlong)size;
+    }
+#endif
+
     return fbuf.st_size;
 }
 
--- a/jdk/src/java.base/windows/native/libnet/NetworkInterface.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.base/windows/native/libnet/NetworkInterface.c	Fri Sep 19 13:47:19 2014 -0700
@@ -990,9 +990,11 @@
       case MIB_IF_TYPE_FDDI:
       case IF_TYPE_IEEE80211:
         len = ifRowP->dwPhysAddrLen;
-        ret = (*env)->NewByteArray(env, len);
-        if (!IS_NULL(ret)) {
-          (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *) ifRowP->bPhysAddr);
+        if (len > 0) {
+            ret = (*env)->NewByteArray(env, len);
+            if (!IS_NULL(ret)) {
+              (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *) ifRowP->bPhysAddr);
+            }
         }
         break;
       }
--- a/jdk/src/java.desktop/macosx/classes/sun/awt/datatransfer/flavormap.properties	Fri Sep 19 08:19:04 2014 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,76 +0,0 @@
-#
-# This properties file is used to initialize the default
-# java.awt.datatransfer.SystemFlavorMap. It contains the Mac OS X platform-specific,
-# default mappings between common Mac OS X selection atoms and platform-independent
-# MIME type strings, which will be converted into 
-# java.awt.datatransfer.DataFlavors.
-#
-# The standard format is:
-#
-# <native>=<MIME type>,<MIME type>, ...
-#
-# <native> should be a string identifier that the native platform will
-# recognize as a valid data format. <MIME type> should specify both a MIME
-# primary type and a MIME subtype separated by a '/'. The MIME type may include
-# parameters, where each parameter is a key/value pair separated by '=', and
-# where each parameter to the MIME type is separated by a ';'.
-#
-# Because SystemFlavorMap implements FlavorTable, developers are free to
-# duplicate DataFlavor values and set multiple values for a single native by
-# separating them with ",". If a mapping contains a duplicate key or value,
-# earlier mappings which included this key or value will be preferred.
-#
-# Mappings whose values specify DataFlavors with primary MIME types of
-# "text", and which support the charset parameter, should specify the exact
-# format in which the native platform expects the data. The "charset"
-# parameter specifies the char to byte encoding, the "eoln" parameter
-# specifies the end-of-line marker, and the "terminators" parameter specifies
-# the number of terminating NUL bytes. Note that "eoln" and "terminators"
-# are not standardized MIME type parameters. They are specific to this file
-# format ONLY. They will not appear in any of the DataFlavors returned by the
-# SystemFlavorMap at the Java level.
-#
-# If the "charset" parameter is omitted, or has zero length, the platform
-# default encoding is assumed. If the "eoln" parameter is omitted, or has
-# zero length, "\n" is assumed. If the "terminators" parameter is omitted,
-# or has a value less than zero, zero is assumed.
-#
-# Upon initialization, the data transfer subsystem will record the specified
-# details of the native text format, but the default SystemFlavorMap will
-# present a large set of synthesized DataFlavors which map, in both
-# directions, to the native. After receiving data from the application in one
-# of the synthetic DataFlavors, the data transfer subsystem will transform
-# the data stream into the format specified in this file before passing the
-# transformed stream to the native system.
-#
-# Mappings whose values specify DataFlavors with primary MIME types of
-# "text", but which do not support the charset parameter, will be treated as
-# opaque, 8-bit data. They will not undergo any transformation process, and
-# any "charset", "eoln", or "terminators" parameters specified in this file
-# will be ignored.
-#
-# See java.awt.datatransfer.DataFlavor.selectBestTextFlavor for a list of
-# text flavors which support the charset parameter.
-
-UTF8_STRING=text/plain;charset=UTF-8;eoln="\n";terminators=0
-
-# The COMPOUND_TEXT support for inter-client text transfer is disabled by 
-# default. The reason is that many native applications prefer this format over 
-# other native text formats, but are unable to decode the textual data in this 
-# format properly. This results in java-to-native text transfer failures.
-# To enable the COMPOUND_TEXT support for this JRE installation uncomment 
-# the line below.
-
-# COMPOUND_TEXT=text/plain;charset=x-compound-text;eoln="\n";terminators=0
-
-TEXT=text/plain;eoln="\n";terminators=0
-STRING=text/plain;charset=UTF-8;eoln="\n";terminators=0
-FILE_NAME=application/x-java-file-list;class=java.util.List
-text/uri-list=application/x-java-file-list;class=java.util.List
-PNG=image/x-java-image;class=java.awt.Image
-JFIF=image/x-java-image;class=java.awt.Image
-TIFF=image/x-java-image;class=java.awt.Image
-RICH_TEXT=text/rtf
-HTML=text/html;charset=utf-8;eoln="\r\n";terminators=1
-URL=application/x-java-url;class=java.net.URL,\
-    text/uri-list;eoln="\r\n";terminators=1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/datatransfer/resources/flavormap.properties	Fri Sep 19 13:47:19 2014 -0700
@@ -0,0 +1,76 @@
+#
+# This properties file is used to initialize the default
+# java.awt.datatransfer.SystemFlavorMap. It contains the Mac OS X platform-specific,
+# default mappings between common Mac OS X selection atoms and platform-independent
+# MIME type strings, which will be converted into 
+# java.awt.datatransfer.DataFlavors.
+#
+# The standard format is:
+#
+# <native>=<MIME type>,<MIME type>, ...
+#
+# <native> should be a string identifier that the native platform will
+# recognize as a valid data format. <MIME type> should specify both a MIME
+# primary type and a MIME subtype separated by a '/'. The MIME type may include
+# parameters, where each parameter is a key/value pair separated by '=', and
+# where each parameter to the MIME type is separated by a ';'.
+#
+# Because SystemFlavorMap implements FlavorTable, developers are free to
+# duplicate DataFlavor values and set multiple values for a single native by
+# separating them with ",". If a mapping contains a duplicate key or value,
+# earlier mappings which included this key or value will be preferred.
+#
+# Mappings whose values specify DataFlavors with primary MIME types of
+# "text", and which support the charset parameter, should specify the exact
+# format in which the native platform expects the data. The "charset"
+# parameter specifies the char to byte encoding, the "eoln" parameter
+# specifies the end-of-line marker, and the "terminators" parameter specifies
+# the number of terminating NUL bytes. Note that "eoln" and "terminators"
+# are not standardized MIME type parameters. They are specific to this file
+# format ONLY. They will not appear in any of the DataFlavors returned by the
+# SystemFlavorMap at the Java level.
+#
+# If the "charset" parameter is omitted, or has zero length, the platform
+# default encoding is assumed. If the "eoln" parameter is omitted, or has
+# zero length, "\n" is assumed. If the "terminators" parameter is omitted,
+# or has a value less than zero, zero is assumed.
+#
+# Upon initialization, the data transfer subsystem will record the specified
+# details of the native text format, but the default SystemFlavorMap will
+# present a large set of synthesized DataFlavors which map, in both
+# directions, to the native. After receiving data from the application in one
+# of the synthetic DataFlavors, the data transfer subsystem will transform
+# the data stream into the format specified in this file before passing the
+# transformed stream to the native system.
+#
+# Mappings whose values specify DataFlavors with primary MIME types of
+# "text", but which do not support the charset parameter, will be treated as
+# opaque, 8-bit data. They will not undergo any transformation process, and
+# any "charset", "eoln", or "terminators" parameters specified in this file
+# will be ignored.
+#
+# See java.awt.datatransfer.DataFlavor.selectBestTextFlavor for a list of
+# text flavors which support the charset parameter.
+
+UTF8_STRING=text/plain;charset=UTF-8;eoln="\n";terminators=0
+
+# The COMPOUND_TEXT support for inter-client text transfer is disabled by 
+# default. The reason is that many native applications prefer this format over 
+# other native text formats, but are unable to decode the textual data in this 
+# format properly. This results in java-to-native text transfer failures.
+# To enable the COMPOUND_TEXT support for this JRE installation uncomment 
+# the line below.
+
+# COMPOUND_TEXT=text/plain;charset=x-compound-text;eoln="\n";terminators=0
+
+TEXT=text/plain;eoln="\n";terminators=0
+STRING=text/plain;charset=UTF-8;eoln="\n";terminators=0
+FILE_NAME=application/x-java-file-list;class=java.util.List
+text/uri-list=application/x-java-file-list;class=java.util.List
+PNG=image/x-java-image;class=java.awt.Image
+JFIF=image/x-java-image;class=java.awt.Image
+TIFF=image/x-java-image;class=java.awt.Image
+RICH_TEXT=text/rtf
+HTML=text/html;charset=utf-8;eoln="\r\n";terminators=1
+URL=application/x-java-url;class=java.net.URL,\
+    text/uri-list;eoln="\r\n";terminators=1
--- a/jdk/src/java.desktop/share/classes/java/awt/event/InputMethodEvent.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/classes/java/awt/event/InputMethodEvent.java	Fri Sep 19 13:47:19 2014 -0700
@@ -418,7 +418,8 @@
     private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
         s.defaultReadObject();
         if (when == 0) {
-            when = getMostRecentEventTimeForSource(this.source);
+            // Can't use getMostRecentEventTimeForSource because source is always null during deserialization
+            when = EventQueue.getMostRecentEventTime();
         }
     }
 
--- a/jdk/src/java.desktop/share/classes/javax/swing/JDesktopPane.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JDesktopPane.java	Fri Sep 19 13:47:19 2014 -0700
@@ -43,6 +43,7 @@
 import java.beans.PropertyVetoException;
 import java.util.Set;
 import java.util.TreeSet;
+import java.util.LinkedHashSet;
 /**
  * A container used to create a multiple-document interface or a virtual desktop.
  * You create <code>JInternalFrame</code> objects and add them to the
@@ -271,7 +272,7 @@
 
     private static Collection<JInternalFrame> getAllFrames(Container parent) {
         int i, count;
-        Collection<JInternalFrame> results = new ArrayList<JInternalFrame>();
+        Collection<JInternalFrame> results = new LinkedHashSet<>();
         count = parent.getComponentCount();
         for (i = 0; i < count; i++) {
             Component next = parent.getComponent(i);
--- a/jdk/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceDataProxy.java	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceDataProxy.java	Fri Sep 19 13:47:19 2014 -0700
@@ -65,7 +65,11 @@
                                            int w, int h)
     {
         if (cachedData == null) {
-            cachedData = oglgc.createManagedSurface(w, h, transparency);
+            try {
+                cachedData = oglgc.createManagedSurface(w, h, transparency);
+            } catch (OutOfMemoryError er) {
+                return null;
+            }
         }
         return cachedData;
     }
--- a/jdk/src/java.desktop/share/native/libfontmanager/freetypeScaler.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/libfontmanager/freetypeScaler.c	Fri Sep 19 13:47:19 2014 -0700
@@ -1082,86 +1082,60 @@
         return 1;
 }
 
+static void addSeg(GPData *gp, jbyte type) {
+    gp->pointTypes[gp->numTypes++] = type;
+}
+
+static void addCoords(GPData *gp, FT_Vector *p) {
+    gp->pointCoords[gp->numCoords++] =  F26Dot6ToFloat(p->x);
+    gp->pointCoords[gp->numCoords++] = -F26Dot6ToFloat(p->y);
+}
+
+static int moveTo(FT_Vector *to, GPData *gp) {
+    if (gp->numCoords)
+        addSeg(gp, SEG_CLOSE);
+    addCoords(gp, to);
+    addSeg(gp, SEG_MOVETO);
+    return FT_Err_Ok;
+}
+
+static int lineTo(FT_Vector *to, GPData *gp) {
+    addCoords(gp, to);
+    addSeg(gp, SEG_LINETO);
+    return FT_Err_Ok;
+}
+
+static int conicTo(FT_Vector *control, FT_Vector *to, GPData *gp) {
+    addCoords(gp, control);
+    addCoords(gp, to);
+    addSeg(gp, SEG_QUADTO);
+    return FT_Err_Ok;
+}
+
+static int cubicTo(FT_Vector *control1,
+                   FT_Vector *control2,
+                   FT_Vector *to,
+                   GPData    *gp) {
+    addCoords(gp, control1);
+    addCoords(gp, control2);
+    addCoords(gp, to);
+    addSeg(gp, SEG_CUBICTO);
+    return FT_Err_Ok;
+}
+
 static void addToGP(GPData* gpdata, FT_Outline*outline) {
-    jbyte current_type=SEG_UNKNOWN;
-    int i, j;
-    jfloat x, y;
+    static const FT_Outline_Funcs outline_funcs = {
+        (FT_Outline_MoveToFunc) moveTo,
+        (FT_Outline_LineToFunc) lineTo,
+        (FT_Outline_ConicToFunc) conicTo,
+        (FT_Outline_CubicToFunc) cubicTo,
+        0, /* shift */
+        0, /* delta */
+    };
 
-    j = 0;
-    for(i=0; i<outline->n_points; i++) {
-        x =  F26Dot6ToFloat(outline->points[i].x);
-        y = -F26Dot6ToFloat(outline->points[i].y);
-
-        if (FT_CURVE_TAG(outline->tags[i]) == FT_CURVE_TAG_ON) {
-            /* If bit 0 is unset, the point is "off" the curve,
-             i.e., a Bezier control point, while it is "on" when set. */
-            if (current_type == SEG_UNKNOWN) { /* special case:
-                                                  very first point */
-                /* add segment */
-                gpdata->pointTypes[gpdata->numTypes++] = SEG_MOVETO;
-                current_type = SEG_LINETO;
-            } else {
-                gpdata->pointTypes[gpdata->numTypes++] = current_type;
-                current_type = SEG_LINETO;
-            }
-        } else {
-            if (current_type == SEG_UNKNOWN) { /* special case:
-                                                   very first point */
-                if (FT_CURVE_TAG(outline->tags[i+1]) == FT_CURVE_TAG_ON) {
-                    /* just skip first point. Adhoc heuristic? */
-                    continue;
-                } else {
-                    x = (x + F26Dot6ToFloat(outline->points[i+1].x))/2;
-                    y = (y - F26Dot6ToFloat(outline->points[i+1].y))/2;
-                    gpdata->pointTypes[gpdata->numTypes++] = SEG_MOVETO;
-                    current_type = SEG_LINETO;
-                }
-            } else if (FT_CURVE_TAG(outline->tags[i]) == FT_CURVE_TAG_CUBIC) {
-                /* Bit 1 is meaningful for 'off' points only.
-                   If set, it indicates a third-order Bezier arc control
-                   point; and a second-order control point if unset.  */
-                current_type = SEG_CUBICTO;
-            } else {
-                /* two successive conic "off" points forces the rasterizer
-                   to create (during the scan-line conversion process
-                   exclusively) a virtual "on" point amidst them, at their
-                   exact middle. This greatly facilitates the definition of
-                   successive conic Bezier arcs.  Moreover, it is the way
-                   outlines are described in the TrueType specification. */
-                if (current_type == SEG_QUADTO) {
-                    gpdata->pointCoords[gpdata->numCoords++] =
-                        F26Dot6ToFloat(outline->points[i].x +
-                        outline->points[i-1].x)/2;
-                    gpdata->pointCoords[gpdata->numCoords++] =
-                        - F26Dot6ToFloat(outline->points[i].y +
-                        outline->points[i-1].y)/2;
-                    gpdata->pointTypes[gpdata->numTypes++] = SEG_QUADTO;
-                }
-                current_type = SEG_QUADTO;
-            }
-        }
-        gpdata->pointCoords[gpdata->numCoords++] = x;
-        gpdata->pointCoords[gpdata->numCoords++] = y;
-        if (outline->contours[j] == i) { //end of contour
-            int start = j > 0 ? outline->contours[j-1]+1 : 0;
-            gpdata->pointTypes[gpdata->numTypes++] = current_type;
-            if (current_type == SEG_QUADTO &&
-            FT_CURVE_TAG(outline->tags[start]) != FT_CURVE_TAG_ON) {
-                gpdata->pointCoords[gpdata->numCoords++] =
-                            (F26Dot6ToFloat(outline->points[start].x) + x)/2;
-                gpdata->pointCoords[gpdata->numCoords++] =
-                            (-F26Dot6ToFloat(outline->points[start].y) + y)/2;
-            } else {
-                gpdata->pointCoords[gpdata->numCoords++] =
-                            F26Dot6ToFloat(outline->points[start].x);
-                gpdata->pointCoords[gpdata->numCoords++] =
-                            -F26Dot6ToFloat(outline->points[start].y);
-            }
-            gpdata->pointTypes[gpdata->numTypes++] = SEG_CLOSE;
-            current_type = SEG_UNKNOWN;
-            j++;
-        }
-    }
+    FT_Outline_Decompose(outline, &outline_funcs, gpdata);
+    if (gpdata->numCoords)
+        addSeg(gpdata, SEG_CLOSE);
 
     /* If set to 1, the outline will be filled using the even-odd fill rule */
     if (outline->flags & FT_OUTLINE_EVEN_ODD_FILL) {
--- a/jdk/src/java.desktop/share/native/liblcms/cmscam02.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmscam02.c	Fri Sep 19 13:47:19 2014 -0700
@@ -467,11 +467,12 @@
     CAM02COLOR clr;
     cmsCIECAM02* lpMod = (cmsCIECAM02*) hModel;
 
-    memset(&clr, 0, sizeof(clr));
     _cmsAssert(lpMod != NULL);
     _cmsAssert(pIn != NULL);
     _cmsAssert(pOut != NULL);
 
+    memset(&clr, 0, sizeof(clr));
+
     clr.XYZ[0] = pIn ->X;
     clr.XYZ[1] = pIn ->Y;
     clr.XYZ[2] = pIn ->Z;
@@ -492,11 +493,12 @@
     CAM02COLOR clr;
     cmsCIECAM02* lpMod = (cmsCIECAM02*) hModel;
 
-    memset(&clr, 0, sizeof(clr));
     _cmsAssert(lpMod != NULL);
     _cmsAssert(pIn != NULL);
     _cmsAssert(pOut != NULL);
 
+    memset(&clr, 0, sizeof(clr));
+
     clr.J = pIn -> J;
     clr.C = pIn -> C;
     clr.h = pIn -> h;
@@ -511,4 +513,3 @@
     pOut ->Y = clr.XYZ[1];
     pOut ->Z = clr.XYZ[2];
 }
-
--- a/jdk/src/java.desktop/share/native/liblcms/cmscgats.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmscgats.c	Fri Sep 19 13:47:19 2014 -0700
@@ -2179,9 +2179,9 @@
 
         if (cmsstrcasecmp(Fld, "SAMPLE_ID") == 0) {
 
-                    t -> SampleID = idField;
-
-        for (i=0; i < t -> nPatches; i++) {
+            t -> SampleID = idField;
+
+            for (i=0; i < t -> nPatches; i++) {
 
                 char *Data = GetData(it8, i, idField);
                 if (Data) {
@@ -2196,7 +2196,7 @@
                         SetData(it8, i, idField, Buffer);
 
                 }
-                }
+            }
 
         }
 
--- a/jdk/src/java.desktop/share/native/liblcms/cmscnvrt.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmscnvrt.c	Fri Sep 19 13:47:19 2014 -0700
@@ -137,15 +137,68 @@
 
 
 // A pointer to the begining of the list
-static cmsIntentsList *Intents = DefaultIntents;
+_cmsIntentsPluginChunkType _cmsIntentsPluginChunk = { NULL };
+
+// Duplicates the zone of memory used by the plug-in in the new context
+static
+void DupPluginIntentsList(struct _cmsContext_struct* ctx,
+                                               const struct _cmsContext_struct* src)
+{
+   _cmsIntentsPluginChunkType newHead = { NULL };
+   cmsIntentsList*  entry;
+   cmsIntentsList*  Anterior = NULL;
+   _cmsIntentsPluginChunkType* head = (_cmsIntentsPluginChunkType*) src->chunks[IntentPlugin];
+
+    // Walk the list copying all nodes
+   for (entry = head->Intents;
+        entry != NULL;
+        entry = entry ->Next) {
+
+            cmsIntentsList *newEntry = ( cmsIntentsList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(cmsIntentsList));
+
+            if (newEntry == NULL)
+                return;
+
+            // We want to keep the linked list order, so this is a little bit tricky
+            newEntry -> Next = NULL;
+            if (Anterior)
+                Anterior -> Next = newEntry;
+
+            Anterior = newEntry;
+
+            if (newHead.Intents == NULL)
+                newHead.Intents = newEntry;
+    }
+
+  ctx ->chunks[IntentPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsIntentsPluginChunkType));
+}
+
+void  _cmsAllocIntentsPluginChunk(struct _cmsContext_struct* ctx,
+                                         const struct _cmsContext_struct* src)
+{
+    if (src != NULL) {
+
+        // Copy all linked list
+        DupPluginIntentsList(ctx, src);
+    }
+    else {
+        static _cmsIntentsPluginChunkType IntentsPluginChunkType = { NULL };
+        ctx ->chunks[IntentPlugin] = _cmsSubAllocDup(ctx ->MemPool, &IntentsPluginChunkType, sizeof(_cmsIntentsPluginChunkType));
+    }
+}
+
 
 // Search the list for a suitable intent. Returns NULL if not found
 static
-cmsIntentsList* SearchIntent(cmsUInt32Number Intent)
+cmsIntentsList* SearchIntent(cmsContext ContextID, cmsUInt32Number Intent)
 {
+    _cmsIntentsPluginChunkType* ctx = ( _cmsIntentsPluginChunkType*) _cmsContextGetClientChunk(ContextID, IntentPlugin);
     cmsIntentsList* pt;
 
-    for (pt = Intents; pt != NULL; pt = pt -> Next)
+    for (pt = ctx -> Intents; pt != NULL; pt = pt -> Next)
+        if (pt ->Intent == Intent) return pt;
+
+    for (pt = DefaultIntents; pt != NULL; pt = pt -> Next)
         if (pt ->Intent == Intent) return pt;
 
     return NULL;
@@ -1031,7 +1084,7 @@
     // this case would present some issues if the custom intent tries to do things like
     // preserve primaries. This solution is not perfect, but works well on most cases.
 
-    Intent = SearchIntent(TheIntents[0]);
+    Intent = SearchIntent(ContextID, TheIntents[0]);
     if (Intent == NULL) {
         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported intent '%d'", TheIntents[0]);
         return NULL;
@@ -1046,12 +1099,14 @@
 // Get information about available intents. nMax is the maximum space for the supplied "Codes"
 // and "Descriptions" the function returns the total number of intents, which may be greater
 // than nMax, although the matrices are not populated beyond this level.
-cmsUInt32Number CMSEXPORT cmsGetSupportedIntents(cmsUInt32Number nMax, cmsUInt32Number* Codes, char** Descriptions)
+cmsUInt32Number CMSEXPORT cmsGetSupportedIntentsTHR(cmsContext ContextID, cmsUInt32Number nMax, cmsUInt32Number* Codes, char** Descriptions)
 {
+    _cmsIntentsPluginChunkType* ctx = ( _cmsIntentsPluginChunkType*) _cmsContextGetClientChunk(ContextID, IntentPlugin);
     cmsIntentsList* pt;
     cmsUInt32Number nIntents;
 
-    for (nIntents=0, pt = Intents; pt != NULL; pt = pt -> Next)
+
+    for (nIntents=0, pt = ctx->Intents; pt != NULL; pt = pt -> Next)
     {
         if (nIntents < nMax) {
             if (Codes != NULL)
@@ -1064,37 +1119,52 @@
         nIntents++;
     }
 
+    for (nIntents=0, pt = DefaultIntents; pt != NULL; pt = pt -> Next)
+    {
+        if (nIntents < nMax) {
+            if (Codes != NULL)
+                Codes[nIntents] = pt ->Intent;
+
+            if (Descriptions != NULL)
+                Descriptions[nIntents] = pt ->Description;
+        }
+
+        nIntents++;
+    }
     return nIntents;
 }
 
+cmsUInt32Number CMSEXPORT cmsGetSupportedIntents(cmsUInt32Number nMax, cmsUInt32Number* Codes, char** Descriptions)
+{
+    return cmsGetSupportedIntentsTHR(NULL, nMax, Codes, Descriptions);
+}
+
 // The plug-in registration. User can add new intents or override default routines
 cmsBool  _cmsRegisterRenderingIntentPlugin(cmsContext id, cmsPluginBase* Data)
 {
+    _cmsIntentsPluginChunkType* ctx = ( _cmsIntentsPluginChunkType*) _cmsContextGetClientChunk(id, IntentPlugin);
     cmsPluginRenderingIntent* Plugin = (cmsPluginRenderingIntent*) Data;
     cmsIntentsList* fl;
 
-    // Do we have to reset the intents?
+    // Do we have to reset the custom intents?
     if (Data == NULL) {
 
-       Intents = DefaultIntents;
-       return TRUE;
+        ctx->Intents = NULL;
+        return TRUE;
     }
 
-    fl = SearchIntent(Plugin ->Intent);
+    fl = (cmsIntentsList*) _cmsPluginMalloc(id, sizeof(cmsIntentsList));
+    if (fl == NULL) return FALSE;
 
-    if (fl == NULL) {
-        fl = (cmsIntentsList*) _cmsPluginMalloc(id, sizeof(cmsIntentsList));
-        if (fl == NULL) return FALSE;
-    }
 
     fl ->Intent  = Plugin ->Intent;
-    strncpy(fl ->Description, Plugin ->Description, 255);
-    fl ->Description[255] = 0;
+    strncpy(fl ->Description, Plugin ->Description, sizeof(fl ->Description)-1);
+    fl ->Description[sizeof(fl ->Description)-1] = 0;
 
     fl ->Link    = Plugin ->Link;
 
-    fl ->Next = Intents;
-    Intents = fl;
+    fl ->Next = ctx ->Intents;
+    ctx ->Intents = fl;
 
     return TRUE;
 }
--- a/jdk/src/java.desktop/share/native/liblcms/cmserr.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmserr.c	Fri Sep 19 13:47:19 2014 -0700
@@ -60,13 +60,14 @@
 // compare two strings ignoring case
 int CMSEXPORT cmsstrcasecmp(const char* s1, const char* s2)
 {
-         register const unsigned char *us1 = (const unsigned char *)s1,
-                                      *us2 = (const unsigned char *)s2;
+    register const unsigned char *us1 = (const unsigned char *)s1,
+                                 *us2 = (const unsigned char *)s2;
 
-        while (toupper(*us1) == toupper(*us2++))
-                if (*us1++ == '\0')
-                        return (0);
-        return (toupper(*us1) - toupper(*--us2));
+    while (toupper(*us1) == toupper(*us2++))
+        if (*us1++ == '\0')
+            return 0;
+
+    return (toupper(*us1) - toupper(*--us2));
 }
 
 // long int because C99 specifies ftell in such way (7.19.9.2)
@@ -91,9 +92,8 @@
 //
 // This is the interface to low-level memory management routines. By default a simple
 // wrapping to malloc/free/realloc is provided, although there is a limit on the max
-// amount of memoy that can be reclaimed. This is mostly as a safety feature to
-// prevent bogus or malintentionated code to allocate huge blocks that otherwise lcms
-// would never need.
+// amount of memoy that can be reclaimed. This is mostly as a safety feature to prevent
+// bogus or evil code to allocate huge blocks that otherwise lcms would never need.
 
 #define MAX_MEMORY_FOR_ALLOC  ((cmsUInt32Number)(1024U*1024U*512U))
 
@@ -103,7 +103,7 @@
 // required to be implemented: malloc, realloc and free, although the user may want to
 // replace the optional mallocZero, calloc and dup as well.
 
-cmsBool   _cmsRegisterMemHandlerPlugin(cmsPluginBase* Plugin);
+cmsBool   _cmsRegisterMemHandlerPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
 
 // *********************************************************************************
 
@@ -143,7 +143,7 @@
     cmsUNUSED_PARAMETER(ContextID);
 }
 
-// The default realloc function. Again it check for exploits. If Ptr is NULL,
+// The default realloc function. Again it checks for exploits. If Ptr is NULL,
 // realloc behaves the same way as malloc and allocates a new block of size bytes.
 static
 void* _cmsReallocDefaultFn(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
@@ -196,28 +196,73 @@
     return mem;
 }
 
-// Pointers to malloc and _cmsFree functions in current environment
-static void * (* MallocPtr)(cmsContext ContextID, cmsUInt32Number size)                     = _cmsMallocDefaultFn;
-static void * (* MallocZeroPtr)(cmsContext ContextID, cmsUInt32Number size)                 = _cmsMallocZeroDefaultFn;
-static void   (* FreePtr)(cmsContext ContextID, void *Ptr)                                  = _cmsFreeDefaultFn;
-static void * (* ReallocPtr)(cmsContext ContextID, void *Ptr, cmsUInt32Number NewSize)      = _cmsReallocDefaultFn;
-static void * (* CallocPtr)(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)= _cmsCallocDefaultFn;
-static void * (* DupPtr)(cmsContext ContextID, const void* Org, cmsUInt32Number size)       = _cmsDupDefaultFn;
+
+// Pointers to memory manager functions in Context0
+_cmsMemPluginChunkType _cmsMemPluginChunk = { _cmsMallocDefaultFn, _cmsMallocZeroDefaultFn, _cmsFreeDefaultFn,
+                                              _cmsReallocDefaultFn, _cmsCallocDefaultFn,    _cmsDupDefaultFn
+                                            };
+
+
+// Reset and duplicate memory manager
+void _cmsAllocMemPluginChunk(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src)
+{
+    _cmsAssert(ctx != NULL);
+
+    if (src != NULL) {
+
+        // Duplicate
+        ctx ->chunks[MemPlugin] = _cmsSubAllocDup(ctx ->MemPool, src ->chunks[MemPlugin], sizeof(_cmsMemPluginChunkType));
+    }
+    else {
+
+        // To reset it, we use the default allocators, which cannot be overriden
+        ctx ->chunks[MemPlugin] = &ctx ->DefaultMemoryManager;
+    }
+}
+
+// Auxiliar to fill memory management functions from plugin (or context 0 defaults)
+void _cmsInstallAllocFunctions(cmsPluginMemHandler* Plugin, _cmsMemPluginChunkType* ptr)
+{
+    if (Plugin == NULL) {
+
+        memcpy(ptr, &_cmsMemPluginChunk, sizeof(_cmsMemPluginChunk));
+    }
+    else {
+
+        ptr ->MallocPtr  = Plugin -> MallocPtr;
+        ptr ->FreePtr    = Plugin -> FreePtr;
+        ptr ->ReallocPtr = Plugin -> ReallocPtr;
+
+        // Make sure we revert to defaults
+        ptr ->MallocZeroPtr= _cmsMallocZeroDefaultFn;
+        ptr ->CallocPtr    = _cmsCallocDefaultFn;
+        ptr ->DupPtr       = _cmsDupDefaultFn;
+
+        if (Plugin ->MallocZeroPtr != NULL) ptr ->MallocZeroPtr = Plugin -> MallocZeroPtr;
+        if (Plugin ->CallocPtr != NULL)     ptr ->CallocPtr     = Plugin -> CallocPtr;
+        if (Plugin ->DupPtr != NULL)        ptr ->DupPtr        = Plugin -> DupPtr;
+
+    }
+}
+
 
 // Plug-in replacement entry
-cmsBool  _cmsRegisterMemHandlerPlugin(cmsPluginBase *Data)
+cmsBool  _cmsRegisterMemHandlerPlugin(cmsContext ContextID, cmsPluginBase *Data)
 {
     cmsPluginMemHandler* Plugin = (cmsPluginMemHandler*) Data;
+    _cmsMemPluginChunkType* ptr;
 
-    // NULL forces to reset to defaults
+    // NULL forces to reset to defaults. In this special case, the defaults are stored in the context structure.
+    // Remaining plug-ins does NOT have any copy in the context structure, but this is somehow special as the
+    // context internal data should be malloce'd by using those functions.
     if (Data == NULL) {
 
-        MallocPtr    = _cmsMallocDefaultFn;
-        MallocZeroPtr= _cmsMallocZeroDefaultFn;
-        FreePtr      = _cmsFreeDefaultFn;
-        ReallocPtr   = _cmsReallocDefaultFn;
-        CallocPtr    = _cmsCallocDefaultFn;
-        DupPtr       = _cmsDupDefaultFn;
+       struct _cmsContext_struct* ctx = ( struct _cmsContext_struct*) ContextID;
+
+       // Return to the default allocators
+        if (ContextID != NULL) {
+            ctx->chunks[MemPlugin] = (void*) &ctx->DefaultMemoryManager;
+        }
         return TRUE;
     }
 
@@ -227,51 +272,56 @@
         Plugin -> ReallocPtr == NULL) return FALSE;
 
     // Set replacement functions
-    MallocPtr  = Plugin -> MallocPtr;
-    FreePtr    = Plugin -> FreePtr;
-    ReallocPtr = Plugin -> ReallocPtr;
+    ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
+    if (ptr == NULL)
+        return FALSE;
 
-    if (Plugin ->MallocZeroPtr != NULL) MallocZeroPtr = Plugin ->MallocZeroPtr;
-    if (Plugin ->CallocPtr != NULL)     CallocPtr     = Plugin -> CallocPtr;
-    if (Plugin ->DupPtr != NULL)        DupPtr        = Plugin -> DupPtr;
-
+    _cmsInstallAllocFunctions(Plugin, ptr);
     return TRUE;
 }
 
 // Generic allocate
 void* CMSEXPORT _cmsMalloc(cmsContext ContextID, cmsUInt32Number size)
 {
-    return MallocPtr(ContextID, size);
+    _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
+    return ptr ->MallocPtr(ContextID, size);
 }
 
 // Generic allocate & zero
 void* CMSEXPORT _cmsMallocZero(cmsContext ContextID, cmsUInt32Number size)
 {
-    return MallocZeroPtr(ContextID, size);
+    _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
+    return ptr->MallocZeroPtr(ContextID, size);
 }
 
 // Generic calloc
 void* CMSEXPORT _cmsCalloc(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)
 {
-    return CallocPtr(ContextID, num, size);
+    _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
+    return ptr->CallocPtr(ContextID, num, size);
 }
 
 // Generic reallocate
 void* CMSEXPORT _cmsRealloc(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
 {
-    return ReallocPtr(ContextID, Ptr, size);
+    _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
+    return ptr->ReallocPtr(ContextID, Ptr, size);
 }
 
 // Generic free memory
 void CMSEXPORT _cmsFree(cmsContext ContextID, void* Ptr)
 {
-    if (Ptr != NULL) FreePtr(ContextID, Ptr);
+    if (Ptr != NULL) {
+        _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
+        ptr ->FreePtr(ContextID, Ptr);
+    }
 }
 
 // Generic block duplication
 void* CMSEXPORT _cmsDupMem(cmsContext ContextID, const void* Org, cmsUInt32Number size)
 {
-    return DupPtr(ContextID, Org, size);
+    _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
+    return ptr ->DupPtr(ContextID, Org, size);
 }
 
 // ********************************************************************************************
@@ -380,6 +430,26 @@
     return (void*) ptr;
 }
 
+// Duplicate in pool
+void* _cmsSubAllocDup(_cmsSubAllocator* s, const void *ptr, cmsUInt32Number size)
+{
+    void *NewPtr;
+
+    // Dup of null pointer is also NULL
+    if (ptr == NULL)
+        return NULL;
+
+    NewPtr = _cmsSubAlloc(s, size);
+
+    if (ptr != NULL && NewPtr != NULL) {
+        memcpy(NewPtr, ptr, size);
+    }
+
+    return NewPtr;
+}
+
+
+
 // Error logging ******************************************************************
 
 // There is no error handling at all. When a funtion fails, it returns proper value.
@@ -401,8 +471,26 @@
 // This is our default log error
 static void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text);
 
-// The current handler in actual environment
-static cmsLogErrorHandlerFunction LogErrorHandler   = DefaultLogErrorHandlerFunction;
+// Context0 storage, which is global
+_cmsLogErrorChunkType _cmsLogErrorChunk = { DefaultLogErrorHandlerFunction };
+
+// Allocates and inits error logger container for a given context. If src is NULL, only initializes the value
+// to the default. Otherwise, it duplicates the value. The interface is standard across all context clients
+void _cmsAllocLogErrorChunk(struct _cmsContext_struct* ctx,
+                            const struct _cmsContext_struct* src)
+{
+    static _cmsLogErrorChunkType LogErrorChunk = { DefaultLogErrorHandlerFunction };
+    void* from;
+
+     if (src != NULL) {
+        from = src ->chunks[Logger];
+    }
+    else {
+       from = &LogErrorChunk;
+    }
+
+    ctx ->chunks[Logger] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsLogErrorChunkType));
+}
 
 // The default error logger does nothing.
 static
@@ -416,13 +504,24 @@
      cmsUNUSED_PARAMETER(Text);
 }
 
-// Change log error
+// Change log error, context based
+void CMSEXPORT cmsSetLogErrorHandlerTHR(cmsContext ContextID, cmsLogErrorHandlerFunction Fn)
+{
+    _cmsLogErrorChunkType* lhg = (_cmsLogErrorChunkType*) _cmsContextGetClientChunk(ContextID, Logger);
+
+    if (lhg != NULL) {
+
+        if (Fn == NULL)
+            lhg -> LogErrorHandler = DefaultLogErrorHandlerFunction;
+        else
+            lhg -> LogErrorHandler = Fn;
+    }
+}
+
+// Change log error, legacy
 void CMSEXPORT cmsSetLogErrorHandler(cmsLogErrorHandlerFunction Fn)
 {
-    if (Fn == NULL)
-        LogErrorHandler = DefaultLogErrorHandlerFunction;
-    else
-        LogErrorHandler = Fn;
+    cmsSetLogErrorHandlerTHR(NULL, Fn);
 }
 
 // Log an error
@@ -431,13 +530,18 @@
 {
     va_list args;
     char Buffer[MAX_ERROR_MESSAGE_LEN];
+    _cmsLogErrorChunkType* lhg;
+
 
     va_start(args, ErrorText);
     vsnprintf(Buffer, MAX_ERROR_MESSAGE_LEN-1, ErrorText, args);
     va_end(args);
 
-    // Call handler
-    LogErrorHandler(ContextID, ErrorCode, Buffer);
+    // Check for the context, if specified go there. If not, go for the global
+    lhg = (_cmsLogErrorChunkType*) _cmsContextGetClientChunk(ContextID, Logger);
+    if (lhg ->LogErrorHandler) {
+        lhg ->LogErrorHandler(ContextID, ErrorCode, Buffer);
+    }
 }
 
 // Utility function to print signatures
@@ -455,3 +559,125 @@
     String[4] = 0;
 }
 
+//--------------------------------------------------------------------------------------------------
+
+
+static
+void* defMtxCreate(cmsContext id)
+{
+    _cmsMutex* ptr_mutex = (_cmsMutex*) _cmsMalloc(id, sizeof(_cmsMutex));
+    _cmsInitMutexPrimitive(ptr_mutex);
+    return (void*) ptr_mutex;
+}
+
+static
+void defMtxDestroy(cmsContext id, void* mtx)
+{
+    _cmsDestroyMutexPrimitive((_cmsMutex *) mtx);
+    _cmsFree(id, mtx);
+}
+
+static
+cmsBool defMtxLock(cmsContext id, void* mtx)
+{
+    cmsUNUSED_PARAMETER(id);
+    return _cmsLockPrimitive((_cmsMutex *) mtx) == 0;
+}
+
+static
+void defMtxUnlock(cmsContext id, void* mtx)
+{
+    cmsUNUSED_PARAMETER(id);
+    _cmsUnlockPrimitive((_cmsMutex *) mtx);
+}
+
+
+
+// Pointers to memory manager functions in Context0
+_cmsMutexPluginChunkType _cmsMutexPluginChunk = { defMtxCreate, defMtxDestroy, defMtxLock, defMtxUnlock };
+
+// Allocate and init mutex container.
+void _cmsAllocMutexPluginChunk(struct _cmsContext_struct* ctx,
+                                        const struct _cmsContext_struct* src)
+{
+    static _cmsMutexPluginChunkType MutexChunk = {defMtxCreate, defMtxDestroy, defMtxLock, defMtxUnlock };
+    void* from;
+
+     if (src != NULL) {
+        from = src ->chunks[MutexPlugin];
+    }
+    else {
+       from = &MutexChunk;
+    }
+
+    ctx ->chunks[MutexPlugin] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsMutexPluginChunkType));
+}
+
+// Register new ways to transform
+cmsBool  _cmsRegisterMutexPlugin(cmsContext ContextID, cmsPluginBase* Data)
+{
+    cmsPluginMutex* Plugin = (cmsPluginMutex*) Data;
+    _cmsMutexPluginChunkType* ctx = ( _cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
+
+    if (Data == NULL) {
+
+        // No lock routines
+        ctx->CreateMutexPtr = NULL;
+        ctx->DestroyMutexPtr = NULL;
+        ctx->LockMutexPtr = NULL;
+        ctx ->UnlockMutexPtr = NULL;
+        return TRUE;
+    }
+
+    // Factory callback is required
+    if (Plugin ->CreateMutexPtr == NULL || Plugin ->DestroyMutexPtr == NULL ||
+        Plugin ->LockMutexPtr == NULL || Plugin ->UnlockMutexPtr == NULL) return FALSE;
+
+
+    ctx->CreateMutexPtr  = Plugin->CreateMutexPtr;
+    ctx->DestroyMutexPtr = Plugin ->DestroyMutexPtr;
+    ctx ->LockMutexPtr   = Plugin ->LockMutexPtr;
+    ctx ->UnlockMutexPtr = Plugin ->UnlockMutexPtr;
+
+    // All is ok
+    return TRUE;
+}
+
+// Generic Mutex fns
+void* CMSEXPORT _cmsCreateMutex(cmsContext ContextID)
+{
+    _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
+
+    if (ptr ->CreateMutexPtr == NULL) return NULL;
+
+    return ptr ->CreateMutexPtr(ContextID);
+}
+
+void CMSEXPORT _cmsDestroyMutex(cmsContext ContextID, void* mtx)
+{
+    _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
+
+    if (ptr ->DestroyMutexPtr != NULL) {
+
+        ptr ->DestroyMutexPtr(ContextID, mtx);
+    }
+}
+
+cmsBool CMSEXPORT _cmsLockMutex(cmsContext ContextID, void* mtx)
+{
+    _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
+
+    if (ptr ->LockMutexPtr == NULL) return TRUE;
+
+    return ptr ->LockMutexPtr(ContextID, mtx);
+}
+
+void CMSEXPORT _cmsUnlockMutex(cmsContext ContextID, void* mtx)
+{
+    _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
+
+    if (ptr ->UnlockMutexPtr != NULL) {
+
+        ptr ->UnlockMutexPtr(ContextID, mtx);
+    }
+}
--- a/jdk/src/java.desktop/share/native/liblcms/cmsgamma.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsgamma.c	Fri Sep 19 13:47:19 2014 -0700
@@ -82,7 +82,6 @@
 
 } _cmsParametricCurvesCollection;
 
-
 // This is the default (built-in) evaluator
 static cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R);
 
@@ -95,22 +94,77 @@
     NULL                                // Next in chain
 };
 
+// Duplicates the zone of memory used by the plug-in in the new context
+static
+void DupPluginCurvesList(struct _cmsContext_struct* ctx,
+                                               const struct _cmsContext_struct* src)
+{
+   _cmsCurvesPluginChunkType newHead = { NULL };
+   _cmsParametricCurvesCollection*  entry;
+   _cmsParametricCurvesCollection*  Anterior = NULL;
+   _cmsCurvesPluginChunkType* head = (_cmsCurvesPluginChunkType*) src->chunks[CurvesPlugin];
+
+    _cmsAssert(head != NULL);
+
+    // Walk the list copying all nodes
+   for (entry = head->ParametricCurves;
+        entry != NULL;
+        entry = entry ->Next) {
+
+            _cmsParametricCurvesCollection *newEntry = ( _cmsParametricCurvesCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsParametricCurvesCollection));
+
+            if (newEntry == NULL)
+                return;
+
+            // We want to keep the linked list order, so this is a little bit tricky
+            newEntry -> Next = NULL;
+            if (Anterior)
+                Anterior -> Next = newEntry;
+
+            Anterior = newEntry;
+
+            if (newHead.ParametricCurves == NULL)
+                newHead.ParametricCurves = newEntry;
+    }
+
+  ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsCurvesPluginChunkType));
+}
+
+// The allocator have to follow the chain
+void _cmsAllocCurvesPluginChunk(struct _cmsContext_struct* ctx,
+                                const struct _cmsContext_struct* src)
+{
+    _cmsAssert(ctx != NULL);
+
+    if (src != NULL) {
+
+        // Copy all linked list
+       DupPluginCurvesList(ctx, src);
+    }
+    else {
+        static _cmsCurvesPluginChunkType CurvesPluginChunk = { NULL };
+        ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx ->MemPool, &CurvesPluginChunk, sizeof(_cmsCurvesPluginChunkType));
+    }
+}
+
+
 // The linked list head
-static _cmsParametricCurvesCollection* ParametricCurves = &DefaultCurves;
+_cmsCurvesPluginChunkType _cmsCurvesPluginChunk = { NULL };
 
 // As a way to install new parametric curves
-cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext id, cmsPluginBase* Data)
+cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext ContextID, cmsPluginBase* Data)
 {
+    _cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin);
     cmsPluginParametricCurves* Plugin = (cmsPluginParametricCurves*) Data;
     _cmsParametricCurvesCollection* fl;
 
     if (Data == NULL) {
 
-          ParametricCurves =  &DefaultCurves;
+          ctx -> ParametricCurves =  NULL;
           return TRUE;
     }
 
-    fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(id, sizeof(_cmsParametricCurvesCollection));
+    fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsParametricCurvesCollection));
     if (fl == NULL) return FALSE;
 
     // Copy the parameters
@@ -126,8 +180,8 @@
     memmove(fl->ParameterCount, Plugin ->ParameterCount,  fl->nFunctions * sizeof(cmsUInt32Number));
 
     // Keep linked list
-    fl ->Next = ParametricCurves;
-    ParametricCurves = fl;
+    fl ->Next = ctx->ParametricCurves;
+    ctx->ParametricCurves = fl;
 
     // All is ok
     return TRUE;
@@ -149,12 +203,24 @@
 
 // Search for the collection which contains a specific type
 static
-_cmsParametricCurvesCollection *GetParametricCurveByType(int Type, int* index)
+_cmsParametricCurvesCollection *GetParametricCurveByType(cmsContext ContextID, int Type, int* index)
 {
     _cmsParametricCurvesCollection* c;
     int Position;
+    _cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin);
 
-    for (c = ParametricCurves; c != NULL; c = c ->Next) {
+    for (c = ctx->ParametricCurves; c != NULL; c = c ->Next) {
+
+        Position = IsInSet(Type, c);
+
+        if (Position != -1) {
+            if (index != NULL)
+                *index = Position;
+            return c;
+        }
+    }
+    // If none found, revert for defaults
+    for (c = &DefaultCurves; c != NULL; c = c ->Next) {
 
         Position = IsInSet(Type, c);
 
@@ -251,7 +317,7 @@
                 p ->Segments[i].SampledPoints = NULL;
 
 
-            c = GetParametricCurveByType(Segments[i].Type, NULL);
+            c = GetParametricCurveByType(ContextID, Segments[i].Type, NULL);
             if (c != NULL)
                     p ->Evals[i] = c ->Evaluator;
         }
@@ -677,12 +743,12 @@
     cmsCurveSegment Seg0;
     int Pos = 0;
     cmsUInt32Number size;
-    _cmsParametricCurvesCollection* c = GetParametricCurveByType(Type, &Pos);
+    _cmsParametricCurvesCollection* c = GetParametricCurveByType(ContextID, Type, &Pos);
 
     _cmsAssert(Params != NULL);
 
     if (c == NULL) {
-         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type);
+        cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type);
         return NULL;
     }
 
@@ -872,7 +938,10 @@
     _cmsAssert(InCurve != NULL);
 
     // Try to reverse it analytically whatever possible
-    if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 && InCurve -> Segments[0].Type <= 5) {
+
+    if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 &&
+        /* InCurve -> Segments[0].Type <= 5 */
+        GetParametricCurveByType(InCurve ->InterpParams->ContextID, InCurve ->Segments[0].Type, NULL) != NULL) {
 
         return cmsBuildParametricToneCurve(InCurve ->InterpParams->ContextID,
                                        -(InCurve -> Segments[0].Type),
--- a/jdk/src/java.desktop/share/native/liblcms/cmsgmt.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsgmt.c	Fri Sep 19 13:47:19 2014 -0700
@@ -191,7 +191,7 @@
 
     out = ComputeKToLstar(ContextID, nPoints, 1,
                             Intents + (nProfiles - 1),
-                            hProfiles + (nProfiles - 1),
+                            &hProfiles [nProfiles - 1],
                             BPC + (nProfiles - 1),
                             AdaptationStates + (nProfiles - 1),
                             dwFlags);
--- a/jdk/src/java.desktop/share/native/liblcms/cmsintrp.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsintrp.c	Fri Sep 19 13:47:19 2014 -0700
@@ -62,31 +62,57 @@
 static cmsInterpFunction DefaultInterpolatorsFactory(cmsUInt32Number nInputChannels, cmsUInt32Number nOutputChannels, cmsUInt32Number dwFlags);
 
 // This is the default factory
-static cmsInterpFnFactory Interpolators = DefaultInterpolatorsFactory;
+_cmsInterpPluginChunkType _cmsInterpPluginChunk = { NULL };
+
+// The interpolation plug-in memory chunk allocator/dup
+void _cmsAllocInterpPluginChunk(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src)
+{
+    void* from;
+
+    _cmsAssert(ctx != NULL);
+
+    if (src != NULL) {
+        from = src ->chunks[InterpPlugin];
+    }
+    else {
+        static _cmsInterpPluginChunkType InterpPluginChunk = { NULL };
+
+        from = &InterpPluginChunk;
+    }
+
+    _cmsAssert(from != NULL);
+    ctx ->chunks[InterpPlugin] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsInterpPluginChunkType));
+}
 
 
 // Main plug-in entry
-cmsBool  _cmsRegisterInterpPlugin(cmsPluginBase* Data)
+cmsBool  _cmsRegisterInterpPlugin(cmsContext ContextID, cmsPluginBase* Data)
 {
     cmsPluginInterpolation* Plugin = (cmsPluginInterpolation*) Data;
+    _cmsInterpPluginChunkType* ptr = (_cmsInterpPluginChunkType*) _cmsContextGetClientChunk(ContextID, InterpPlugin);
 
     if (Data == NULL) {
 
-        Interpolators = DefaultInterpolatorsFactory;
+        ptr ->Interpolators = NULL;
         return TRUE;
     }
 
     // Set replacement functions
-    Interpolators = Plugin ->InterpolatorsFactory;
+    ptr ->Interpolators = Plugin ->InterpolatorsFactory;
     return TRUE;
 }
 
 
 // Set the interpolation method
-cmsBool _cmsSetInterpolationRoutine(cmsInterpParams* p)
+cmsBool _cmsSetInterpolationRoutine(cmsContext ContextID, cmsInterpParams* p)
 {
-    // Invoke factory, possibly in the Plug-in
-    p ->Interpolation = Interpolators(p -> nInputs, p ->nOutputs, p ->dwFlags);
+    _cmsInterpPluginChunkType* ptr = (_cmsInterpPluginChunkType*) _cmsContextGetClientChunk(ContextID, InterpPlugin);
+
+    p ->Interpolation.Lerp16 = NULL;
+
+   // Invoke factory, possibly in the Plug-in
+    if (ptr ->Interpolators != NULL)
+        p ->Interpolation = ptr->Interpolators(p -> nInputs, p ->nOutputs, p ->dwFlags);
 
     // If unsupported by the plug-in, go for the LittleCMS default.
     // If happens only if an extern plug-in is being used
@@ -97,6 +123,7 @@
     if (p ->Interpolation.Lerp16 == NULL) {
             return FALSE;
     }
+
     return TRUE;
 }
 
@@ -141,7 +168,7 @@
         p ->opta[i] = p ->opta[i-1] * nSamples[InputChan-i];
 
 
-    if (!_cmsSetInterpolationRoutine(p)) {
+    if (!_cmsSetInterpolationRoutine(ContextID, p)) {
          cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported interpolation (%d->%d channels)", InputChan, OutputChan);
         _cmsFree(ContextID, p);
         return NULL;
--- a/jdk/src/java.desktop/share/native/liblcms/cmsio0.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsio0.c	Fri Sep 19 13:47:19 2014 -0700
@@ -229,15 +229,14 @@
     if (ResData == NULL) return FALSE; // Housekeeping
 
     // Check for available space. Clip.
-    if (iohandler ->UsedSpace + size > ResData->Size) {
-        size = ResData ->Size - iohandler ->UsedSpace;
+    if (ResData->Pointer + size > ResData->Size) {
+        size = ResData ->Size - ResData->Pointer;
     }
 
     if (size == 0) return TRUE;     // Write zero bytes is ok, but does nothing
 
     memmove(ResData ->Block + ResData ->Pointer, Ptr, size);
     ResData ->Pointer += size;
-    iohandler->UsedSpace += size;
 
     if (ResData ->Pointer > iohandler->UsedSpace)
         iohandler->UsedSpace = ResData ->Pointer;
@@ -371,7 +370,7 @@
 static
 cmsUInt32Number FileTell(cmsIOHANDLER* iohandler)
 {
-    return ftell((FILE*)iohandler ->stream);
+    return (cmsUInt32Number) ftell((FILE*)iohandler ->stream);
 }
 
 // Writes data to stream, also keeps used space for further reference. Returns TRUE on success, FALSE on error
@@ -414,7 +413,7 @@
              cmsSignalError(ContextID, cmsERROR_FILE, "File '%s' not found", FileName);
             return NULL;
         }
-        iohandler -> ReportedSize = cmsfilelength(fm);
+        iohandler -> ReportedSize = (cmsUInt32Number) cmsfilelength(fm);
         break;
 
     case 'w':
@@ -461,7 +460,7 @@
     iohandler -> ContextID = ContextID;
     iohandler -> stream = (void*) Stream;
     iohandler -> UsedSpace = 0;
-    iohandler -> ReportedSize = cmsfilelength(Stream);
+    iohandler -> ReportedSize = (cmsUInt32Number) cmsfilelength(Stream);
     iohandler -> PhysicalFile[0] = 0;
 
     iohandler ->Read    = FileRead;
@@ -501,6 +500,9 @@
     // Set creation date/time
     memmove(&Icc ->Created, gmtime(&now), sizeof(Icc ->Created));
 
+    // Create a mutex if the user provided proper plugin. NULL otherwise
+    Icc ->UsrMutex = _cmsCreateMutex(ContextID);
+
     // Return the handle
     return (cmsHPROFILE) Icc;
 }
@@ -579,9 +581,39 @@
     return n;
 }
 
+// Deletes a tag entry
 
-// Create a new tag entry
+static
+void _cmsDeleteTagByPos(_cmsICCPROFILE* Icc, int i)
+{
+    _cmsAssert(Icc != NULL);
+    _cmsAssert(i >= 0);
 
+
+    if (Icc -> TagPtrs[i] != NULL) {
+
+        // Free previous version
+        if (Icc ->TagSaveAsRaw[i]) {
+            _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
+        }
+        else {
+            cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
+
+            if (TypeHandler != NULL) {
+
+                cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
+                LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameter
+                LocalTypeHandler.ICCVersion = Icc ->Version;
+                LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
+                Icc ->TagPtrs[i] = NULL;
+            }
+        }
+
+    }
+}
+
+
+// Creates a new tag entry
 static
 cmsBool _cmsNewTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, int* NewPos)
 {
@@ -589,15 +621,15 @@
 
     // Search for the tag
     i = _cmsSearchTag(Icc, sig, FALSE);
+    if (i >= 0) {
 
-    // Now let's do it easy. If the tag has been already written, that's an error
-    if (i >= 0) {
-        cmsSignalError(Icc ->ContextID, cmsERROR_ALREADY_DEFINED, "Tag '%x' already exists", sig);
-        return FALSE;
+        // Already exists? delete it
+        _cmsDeleteTagByPos(Icc, i);
+        *NewPos = i;
     }
     else  {
 
-        // New one
+        // No, make a new one
 
         if (Icc -> TagCount >= MAX_TABLE_TAG) {
             cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
@@ -979,7 +1011,7 @@
 
     // 4.2 -> 0x4200000
 
-    Icc -> Version = BaseToBase((cmsUInt32Number) floor(Version * 100.0), 10, 16) << 16;
+    Icc -> Version = BaseToBase((cmsUInt32Number) floor(Version * 100.0 + 0.5), 10, 16) << 16;
 }
 
 cmsFloat64Number CMSEXPORT cmsGetProfileVersion(cmsHPROFILE hProfile)
@@ -1011,6 +1043,32 @@
     return NULL;
 }
 
+// Create profile from IOhandler
+cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandler2THR(cmsContext ContextID, cmsIOHANDLER* io, cmsBool write)
+{
+    _cmsICCPROFILE* NewIcc;
+    cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
+
+    if (hEmpty == NULL) return NULL;
+
+    NewIcc = (_cmsICCPROFILE*) hEmpty;
+
+    NewIcc ->IOhandler = io;
+    if (write) {
+
+        NewIcc -> IsWrite = TRUE;
+        return hEmpty;
+    }
+
+    if (!_cmsReadHeader(NewIcc)) goto Error;
+    return hEmpty;
+
+Error:
+    cmsCloseProfile(hEmpty);
+    return NULL;
+}
+
+
 // Create profile from disk file
 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFileTHR(cmsContext ContextID, const char *lpFileName, const char *sAccess)
 {
@@ -1202,7 +1260,7 @@
         else {
 
             // Search for support on this tag
-            TagDescriptor = _cmsGetTagDescriptor(Icc -> TagNames[i]);
+            TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, Icc -> TagNames[i]);
             if (TagDescriptor == NULL) continue;                        // Unsupported, ignore it
 
             if (TagDescriptor ->DecideType != NULL) {
@@ -1214,7 +1272,7 @@
                 Type = TagDescriptor ->SupportedTypes[0];
             }
 
-            TypeHandler =  _cmsGetTagTypeHandler(Type);
+            TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
 
             if (TypeHandler == NULL) {
                 cmsSignalError(Icc ->ContextID, cmsERROR_INTERNAL, "(Internal) no handler for tag %x", Icc -> TagNames[i]);
@@ -1282,10 +1340,12 @@
 {
     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
     _cmsICCPROFILE Keep;
-    cmsIOHANDLER* PrevIO;
+    cmsIOHANDLER* PrevIO = NULL;
     cmsUInt32Number UsedSpace;
     cmsContext ContextID;
 
+    _cmsAssert(hProfile != NULL);
+
     memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
 
     ContextID = cmsGetProfileContextID(hProfile);
@@ -1294,18 +1354,19 @@
 
     // Pass #1 does compute offsets
 
-    if (!_cmsWriteHeader(Icc, 0)) return 0;
-    if (!SaveTags(Icc, &Keep)) return 0;
+    if (!_cmsWriteHeader(Icc, 0)) goto Error;
+    if (!SaveTags(Icc, &Keep)) goto Error;
 
     UsedSpace = PrevIO ->UsedSpace;
 
     // Pass #2 does save to iohandler
 
     if (io != NULL) {
+
         Icc ->IOhandler = io;
-        if (!SetLinks(Icc)) goto CleanUp;
-        if (!_cmsWriteHeader(Icc, UsedSpace)) goto CleanUp;
-        if (!SaveTags(Icc, &Keep)) goto CleanUp;
+        if (!SetLinks(Icc)) goto Error;
+        if (!_cmsWriteHeader(Icc, UsedSpace)) goto Error;
+        if (!SaveTags(Icc, &Keep)) goto Error;
     }
 
     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
@@ -1314,7 +1375,7 @@
     return UsedSpace;
 
 
-CleanUp:
+Error:
     cmsCloseIOhandler(PrevIO);
     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
     return 0;
@@ -1362,11 +1423,13 @@
     cmsIOHANDLER* io;
     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
+    _cmsAssert(BytesNeeded != NULL);
+
     // Should we just calculate the needed space?
     if (MemPtr == NULL) {
 
            *BytesNeeded =  cmsSaveProfileToIOhandler(hProfile, NULL);
-            return (*BytesNeeded == 0 ? FALSE : TRUE);
+            return (*BytesNeeded == 0) ? FALSE : TRUE;
     }
 
     // That is a real write operation
@@ -1419,6 +1482,8 @@
         rc &= cmsCloseIOhandler(Icc->IOhandler);
     }
 
+    _cmsDestroyMutex(Icc->ContextID, Icc->UsrMutex);
+
     _cmsFree(Icc ->ContextID, Icc);   // Free placeholder memory
 
     return rc;
@@ -1459,14 +1524,18 @@
     cmsUInt32Number ElemCount;
     int n;
 
+    if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return NULL;
+
     n = _cmsSearchTag(Icc, sig, TRUE);
-    if (n < 0) return NULL;                 // Not found, return NULL
+    if (n < 0) goto Error;               // Not found, return NULL
 
 
     // If the element is already in memory, return the pointer
     if (Icc -> TagPtrs[n]) {
 
-        if (Icc ->TagSaveAsRaw[n]) return NULL;  // We don't support read raw tags as cooked
+        if (Icc ->TagSaveAsRaw[n]) goto Error;  // We don't support read raw tags as cooked
+
+        _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
         return Icc -> TagPtrs[n];
     }
 
@@ -1476,23 +1545,32 @@
 
     // Seek to its location
     if (!io -> Seek(io, Offset))
-        return NULL;
+        goto Error;
 
     // Search for support on this tag
-    TagDescriptor = _cmsGetTagDescriptor(sig);
-    if (TagDescriptor == NULL) return NULL;     // Unsupported.
+    TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
+    if (TagDescriptor == NULL) {
+
+        char String[5];
+
+        _cmsTagSignature2String(String, sig);
+
+        // An unknown element was found.
+        cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown tag type '%s' found.", String);
+        goto Error;     // Unsupported.
+    }
 
     // if supported, get type and check if in list
     BaseType = _cmsReadTypeBase(io);
-    if (BaseType == 0) return NULL;
+    if (BaseType == 0) goto Error;
 
-    if (!IsTypeSupported(TagDescriptor, BaseType)) return NULL;
+    if (!IsTypeSupported(TagDescriptor, BaseType)) goto Error;
 
     TagSize  -= 8;                      // Alredy read by the type base logic
 
     // Get type handler
-    TypeHandler = _cmsGetTagTypeHandler(BaseType);
-    if (TypeHandler == NULL) return NULL;
+    TypeHandler = _cmsGetTagTypeHandler(Icc ->ContextID, BaseType);
+    if (TypeHandler == NULL) goto Error;
     LocalTypeHandler = *TypeHandler;
 
 
@@ -1511,7 +1589,7 @@
 
         _cmsTagSignature2String(String, sig);
         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Corrupted tag '%s'", String);
-        return NULL;
+        goto Error;
     }
 
     // This is a weird error that may be a symptom of something more serious, the number of
@@ -1527,7 +1605,14 @@
 
 
     // Return the data
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
     return Icc -> TagPtrs[n];
+
+
+    // Return error and unlock tha data
+Error:
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
+    return NULL;
 }
 
 
@@ -1561,49 +1646,26 @@
     cmsFloat64Number Version;
     char TypeString[5], SigString[5];
 
+    if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
 
+    // To delete tags.
     if (data == NULL) {
 
+         // Delete the tag
          i = _cmsSearchTag(Icc, sig, FALSE);
-         if (i >= 0)
+         if (i >= 0) {
+
+             // Use zero as a mark of deleted
+             _cmsDeleteTagByPos(Icc, i);
              Icc ->TagNames[i] = (cmsTagSignature) 0;
-         // Unsupported by now, reserved for future ampliations (delete)
-         return FALSE;
+             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
+             return TRUE;
+         }
+         // Didn't find the tag
+        goto Error;
     }
 
-    i = _cmsSearchTag(Icc, sig, FALSE);
-    if (i >=0) {
-
-        if (Icc -> TagPtrs[i] != NULL) {
-
-            // Already exists. Free previous version
-            if (Icc ->TagSaveAsRaw[i]) {
-                _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
-            }
-            else {
-                TypeHandler = Icc ->TagTypeHandlers[i];
-
-                if (TypeHandler != NULL) {
-
-                    LocalTypeHandler = *TypeHandler;
-                    LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameter
-                    LocalTypeHandler.ICCVersion = Icc ->Version;
-                    LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
-                }
-            }
-        }
-    }
-    else  {
-        // New one
-        i = Icc -> TagCount;
-
-        if (i >= MAX_TABLE_TAG) {
-            cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
-            return FALSE;
-        }
-
-        Icc -> TagCount++;
-    }
+    if (!_cmsNewTag(Icc, sig, &i)) goto Error;
 
     // This is not raw
     Icc ->TagSaveAsRaw[i] = FALSE;
@@ -1612,10 +1674,10 @@
     Icc ->TagLinked[i] = (cmsTagSignature) 0;
 
     // Get information about the TAG.
-    TagDescriptor = _cmsGetTagDescriptor(sig);
+    TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
     if (TagDescriptor == NULL){
          cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag '%x'", sig);
-        return FALSE;
+        goto Error;
     }
 
 
@@ -1633,7 +1695,6 @@
     }
     else {
 
-
         Type = TagDescriptor ->SupportedTypes[0];
     }
 
@@ -1644,18 +1705,18 @@
         _cmsTagSignature2String(SigString,  sig);
 
         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
-        return FALSE;
+        goto Error;
     }
 
     // Does we have a handler for this type?
-    TypeHandler =  _cmsGetTagTypeHandler(Type);
+    TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
     if (TypeHandler == NULL) {
 
         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
         _cmsTagSignature2String(SigString,  sig);
 
         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
-        return FALSE;           // Should never happen
+        goto Error;           // Should never happen
     }
 
 
@@ -1668,7 +1729,7 @@
     LocalTypeHandler = *TypeHandler;
     LocalTypeHandler.ContextID  = Icc ->ContextID;
     LocalTypeHandler.ICCVersion = Icc ->Version;
-    Icc ->TagPtrs[i]         = LocalTypeHandler.DupPtr(&LocalTypeHandler, data, TagDescriptor ->ElemCount);
+    Icc ->TagPtrs[i]            = LocalTypeHandler.DupPtr(&LocalTypeHandler, data, TagDescriptor ->ElemCount);
 
     if (Icc ->TagPtrs[i] == NULL)  {
 
@@ -1676,10 +1737,16 @@
         _cmsTagSignature2String(SigString,  sig);
         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Malformed struct in type '%s' for tag '%s'", TypeString, SigString);
 
-        return FALSE;
+        goto Error;
     }
 
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
     return TRUE;
+
+Error:
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
+    return FALSE;
+
 }
 
 // Read and write raw data. The only way those function would work and keep consistence with normal read and write
@@ -1700,9 +1767,11 @@
     cmsUInt32Number rc;
     cmsUInt32Number Offset, TagSize;
 
+    if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
+
     // Search for given tag in ICC profile directory
     i = _cmsSearchTag(Icc, sig, TRUE);
-    if (i < 0) return 0;                 // Not found, return 0
+    if (i < 0) goto Error;                 // Not found,
 
     // It is already read?
     if (Icc -> TagPtrs[i] == NULL) {
@@ -1717,12 +1786,14 @@
             if (BufferSize < TagSize)
                 TagSize = BufferSize;
 
-            if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) return 0;
-            if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) return 0;
+            if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) goto Error;
+            if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) goto Error;
 
+            _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
             return TagSize;
         }
 
+        _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
         return Icc ->TagSizes[i];
     }
 
@@ -1738,16 +1809,22 @@
 
             memmove(data, Icc ->TagPtrs[i], TagSize);
 
+            _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
             return TagSize;
         }
 
+        _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
         return Icc ->TagSizes[i];
     }
 
     // Already readed, or previously set by cmsWriteTag(). We need to serialize that
     // data to raw in order to maintain consistency.
+
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
     Object = cmsReadTag(hProfile, sig);
-    if (Object == NULL) return 0;
+    if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
+
+    if (Object == NULL) goto Error;
 
     // Now we need to serialize to a memory block: just use a memory iohandler
 
@@ -1756,17 +1833,18 @@
     } else{
         MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
     }
-    if (MemIO == NULL) return 0;
+    if (MemIO == NULL) goto Error;
 
     // Obtain type handling for the tag
     TypeHandler = Icc ->TagTypeHandlers[i];
-    TagDescriptor = _cmsGetTagDescriptor(sig);
+    TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
     if (TagDescriptor == NULL) {
         cmsCloseIOhandler(MemIO);
-        return 0;
+        goto Error;
     }
 
-    // FIXME: No handling for TypeHandler == NULL here?
+    if (TypeHandler == NULL) goto Error;
+
     // Serialize
     LocalTypeHandler = *TypeHandler;
     LocalTypeHandler.ContextID  = Icc ->ContextID;
@@ -1774,19 +1852,24 @@
 
     if (!_cmsWriteTypeBase(MemIO, TypeHandler ->Signature)) {
         cmsCloseIOhandler(MemIO);
-        return 0;
+        goto Error;
     }
 
     if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) {
         cmsCloseIOhandler(MemIO);
-        return 0;
+        goto Error;
     }
 
     // Get Size and close
     rc = MemIO ->Tell(MemIO);
     cmsCloseIOhandler(MemIO);      // Ignore return code this time
 
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
     return rc;
+
+Error:
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
+    return 0;
 }
 
 // Similar to the anterior. This function allows to write directly to the ICC profile any data, without
@@ -1798,7 +1881,12 @@
     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
     int i;
 
-    if (!_cmsNewTag(Icc, sig, &i)) return FALSE;
+    if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
+
+    if (!_cmsNewTag(Icc, sig, &i)) {
+        _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
+         return FALSE;
+    }
 
     // Mark the tag as being written as RAW
     Icc ->TagSaveAsRaw[i] = TRUE;
@@ -1809,6 +1897,7 @@
     Icc ->TagPtrs[i]  = _cmsDupMem(Icc ->ContextID, data, Size);
     Icc ->TagSizes[i] = Size;
 
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
     return TRUE;
 }
 
@@ -1818,7 +1907,12 @@
     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
     int i;
 
-    if (!_cmsNewTag(Icc, sig, &i)) return FALSE;
+     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
+
+    if (!_cmsNewTag(Icc, sig, &i)) {
+        _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
+        return FALSE;
+    }
 
     // Keep necessary information
     Icc ->TagSaveAsRaw[i] = FALSE;
@@ -1829,6 +1923,7 @@
     Icc ->TagSizes[i]   = 0;
     Icc ->TagOffsets[i] = 0;
 
+    _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
     return TRUE;
 }
 
--- a/jdk/src/java.desktop/share/native/liblcms/cmsio1.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsio1.c	Fri Sep 19 13:47:19 2014 -0700
@@ -334,7 +334,8 @@
 
 
 // Read and create a BRAND NEW MPE LUT from a given profile. All stuff dependent of version, etc
-// is adjusted here in order to create a LUT that takes care of all those details
+// is adjusted here in order to create a LUT that takes care of all those details.
+// We add intent = -1 as a way to read matrix shaper always, no matter of other LUT
 cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent)
 {
     cmsTagTypeSignature OriginalType;
@@ -364,49 +365,54 @@
         return Lut;
     }
 
-    if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
+    // This is an attempt to reuse this funtion to retrieve the matrix-shaper as pipeline no
+    // matter other LUT are present and have precedence. Intent = -1 means just this.
+    if (Intent != -1) {
 
-        // Floating point LUT are always V4, but the encoding range is no
-        // longer 0..1.0, so we need to add an stage depending on the color space
-         return _cmsReadFloatInputTag(hProfile, tagFloat);
-    }
+        if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 
-    // Revert to perceptual if no tag is found
-    if (!cmsIsTag(hProfile, tag16)) {
-        tag16 = Device2PCS16[0];
-    }
+            // Floating point LUT are always V4, but the encoding range is no
+            // longer 0..1.0, so we need to add an stage depending on the color space
+            return _cmsReadFloatInputTag(hProfile, tagFloat);
+        }
 
-    if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
+        // Revert to perceptual if no tag is found
+        if (!cmsIsTag(hProfile, tag16)) {
+            tag16 = Device2PCS16[0];
+        }
 
-        // Check profile version and LUT type. Do the necessary adjustments if needed
+        if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
 
-        // First read the tag
-        cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
-        if (Lut == NULL) return NULL;
+            // Check profile version and LUT type. Do the necessary adjustments if needed
 
-        // After reading it, we have now info about the original type
-        OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
+            // First read the tag
+            cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
+            if (Lut == NULL) return NULL;
 
-        // The profile owns the Lut, so we need to copy it
-        Lut = cmsPipelineDup(Lut);
+            // After reading it, we have now info about the original type
+            OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
 
-        // We need to adjust data only for Lab16 on output
-        if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
+            // The profile owns the Lut, so we need to copy it
+            Lut = cmsPipelineDup(Lut);
+
+            // We need to adjust data only for Lab16 on output
+            if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
+                return Lut;
+
+            // If the input is Lab, add also a conversion at the begin
+            if (cmsGetColorSpace(hProfile) == cmsSigLabData &&
+                !cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
+                goto Error;
+
+            // Add a matrix for conversion V2 to V4 Lab PCS
+            if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+                goto Error;
+
             return Lut;
-
-        // If the input is Lab, add also a conversion at the begin
-        if (cmsGetColorSpace(hProfile) == cmsSigLabData &&
-            !cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
-            goto Error;
-
-        // Add a matrix for conversion V2 to V4 Lab PCS
-        if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
-            goto Error;
-
-        return Lut;
 Error:
-        cmsPipelineFree(Lut);
-        return NULL;
+            cmsPipelineFree(Lut);
+            return NULL;
+        }
     }
 
     // Lut was not found, try to create a matrix-shaper
@@ -551,7 +557,7 @@
                 _cmsStageCLutData* CLUT = (_cmsStageCLutData*) Stage ->Data;
 
                 CLUT ->Params->dwFlags |= CMS_LERP_FLAGS_TRILINEAR;
-                _cmsSetInterpolationRoutine(CLUT ->Params);
+                _cmsSetInterpolationRoutine(Lut->ContextID, CLUT ->Params);
             }
     }
 }
@@ -609,54 +615,58 @@
     cmsTagSignature tagFloat = PCS2DeviceFloat[Intent];
     cmsContext ContextID     = cmsGetProfileContextID(hProfile);
 
-    if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 
-        // Floating point LUT are always V4
-        return _cmsReadFloatOutputTag(hProfile, tagFloat);
-    }
+    if (Intent != -1) {
 
-    // Revert to perceptual if no tag is found
-    if (!cmsIsTag(hProfile, tag16)) {
-        tag16 = PCS2Device16[0];
-    }
+        if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 
-    if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
+            // Floating point LUT are always V4
+            return _cmsReadFloatOutputTag(hProfile, tagFloat);
+        }
 
-        // Check profile version and LUT type. Do the necessary adjustments if needed
+        // Revert to perceptual if no tag is found
+        if (!cmsIsTag(hProfile, tag16)) {
+            tag16 = PCS2Device16[0];
+        }
 
-        // First read the tag
-        cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
-        if (Lut == NULL) return NULL;
+        if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
 
-        // After reading it, we have info about the original type
-        OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
+            // Check profile version and LUT type. Do the necessary adjustments if needed
 
-        // The profile owns the Lut, so we need to copy it
-        Lut = cmsPipelineDup(Lut);
-        if (Lut == NULL) return NULL;
+            // First read the tag
+            cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
+            if (Lut == NULL) return NULL;
 
-        // Now it is time for a controversial stuff. I found that for 3D LUTS using
-        // Lab used as indexer space,  trilinear interpolation should be used
-        if (cmsGetPCS(hProfile) == cmsSigLabData)
-            ChangeInterpolationToTrilinear(Lut);
+            // After reading it, we have info about the original type
+            OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
 
-        // We need to adjust data only for Lab and Lut16 type
-        if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
-            return Lut;
+            // The profile owns the Lut, so we need to copy it
+            Lut = cmsPipelineDup(Lut);
+            if (Lut == NULL) return NULL;
 
-        // Add a matrix for conversion V4 to V2 Lab PCS
-        if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
-            goto Error;
+            // Now it is time for a controversial stuff. I found that for 3D LUTS using
+            // Lab used as indexer space,  trilinear interpolation should be used
+            if (cmsGetPCS(hProfile) == cmsSigLabData)
+                ChangeInterpolationToTrilinear(Lut);
 
-        // If the output is Lab, add also a conversion at the end
-        if (cmsGetColorSpace(hProfile) == cmsSigLabData)
-            if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+            // We need to adjust data only for Lab and Lut16 type
+            if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
+                return Lut;
+
+            // Add a matrix for conversion V4 to V2 Lab PCS
+            if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
                 goto Error;
 
-        return Lut;
+            // If the output is Lab, add also a conversion at the end
+            if (cmsGetColorSpace(hProfile) == cmsSigLabData)
+                if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+                    goto Error;
+
+            return Lut;
 Error:
-        cmsPipelineFree(Lut);
-        return NULL;
+            cmsPipelineFree(Lut);
+            return NULL;
+        }
     }
 
     // Lut not found, try to create a matrix-shaper
@@ -782,7 +792,7 @@
 
     // Now it is time for a controversial stuff. I found that for 3D LUTS using
     // Lab used as indexer space,  trilinear interpolation should be used
-    if (cmsGetColorSpace(hProfile) == cmsSigLabData)
+    if (cmsGetPCS(hProfile) == cmsSigLabData)
         ChangeInterpolationToTrilinear(Lut);
 
     // After reading it, we have info about the original type
@@ -793,12 +803,12 @@
 
     // Here it is possible to get Lab on both sides
 
-    if (cmsGetPCS(hProfile) == cmsSigLabData) {
+    if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
         if(!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
             goto Error2;
     }
 
-    if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
+    if (cmsGetPCS(hProfile) == cmsSigLabData) {
         if(!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
             goto Error2;
     }
--- a/jdk/src/java.desktop/share/native/liblcms/cmsopt.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsopt.c	Fri Sep 19 13:47:19 2014 -0700
@@ -542,11 +542,13 @@
 
             cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);
             if (InversePostLin == NULL) {
-                WhiteOut[i] = 0;
-                continue;
+                WhiteOut[i] = WhitePointOut[i];
+
+            } else {
+
+                WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);
+                cmsFreeToneCurve(InversePostLin);
             }
-            WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);
-            cmsFreeToneCurve(InversePostLin);
         }
     }
     else {
@@ -1666,44 +1668,102 @@
 };
 
 // The linked list head
-static _cmsOptimizationCollection* OptimizationCollection = DefaultOptimization;
+_cmsOptimizationPluginChunkType _cmsOptimizationPluginChunk = { NULL };
+
+
+// Duplicates the zone of memory used by the plug-in in the new context
+static
+void DupPluginOptimizationList(struct _cmsContext_struct* ctx,
+                               const struct _cmsContext_struct* src)
+{
+   _cmsOptimizationPluginChunkType newHead = { NULL };
+   _cmsOptimizationCollection*  entry;
+   _cmsOptimizationCollection*  Anterior = NULL;
+   _cmsOptimizationPluginChunkType* head = (_cmsOptimizationPluginChunkType*) src->chunks[OptimizationPlugin];
+
+    _cmsAssert(ctx != NULL);
+    _cmsAssert(head != NULL);
+
+    // Walk the list copying all nodes
+   for (entry = head->OptimizationCollection;
+        entry != NULL;
+        entry = entry ->Next) {
+
+            _cmsOptimizationCollection *newEntry = ( _cmsOptimizationCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsOptimizationCollection));
+
+            if (newEntry == NULL)
+                return;
+
+            // We want to keep the linked list order, so this is a little bit tricky
+            newEntry -> Next = NULL;
+            if (Anterior)
+                Anterior -> Next = newEntry;
+
+            Anterior = newEntry;
+
+            if (newHead.OptimizationCollection == NULL)
+                newHead.OptimizationCollection = newEntry;
+    }
+
+  ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsOptimizationPluginChunkType));
+}
+
+void  _cmsAllocOptimizationPluginChunk(struct _cmsContext_struct* ctx,
+                                         const struct _cmsContext_struct* src)
+{
+  if (src != NULL) {
+
+        // Copy all linked list
+       DupPluginOptimizationList(ctx, src);
+    }
+    else {
+        static _cmsOptimizationPluginChunkType OptimizationPluginChunkType = { NULL };
+        ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx ->MemPool, &OptimizationPluginChunkType, sizeof(_cmsOptimizationPluginChunkType));
+    }
+}
+
 
 // Register new ways to optimize
-cmsBool  _cmsRegisterOptimizationPlugin(cmsContext id, cmsPluginBase* Data)
+cmsBool  _cmsRegisterOptimizationPlugin(cmsContext ContextID, cmsPluginBase* Data)
 {
     cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;
+    _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);
     _cmsOptimizationCollection* fl;
 
     if (Data == NULL) {
 
-        OptimizationCollection = DefaultOptimization;
+        ctx->OptimizationCollection = NULL;
         return TRUE;
     }
 
     // Optimizer callback is required
     if (Plugin ->OptimizePtr == NULL) return FALSE;
 
-    fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(id, sizeof(_cmsOptimizationCollection));
+    fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsOptimizationCollection));
     if (fl == NULL) return FALSE;
 
     // Copy the parameters
     fl ->OptimizePtr = Plugin ->OptimizePtr;
 
     // Keep linked list
-    fl ->Next = OptimizationCollection;
-    OptimizationCollection = fl;
+    fl ->Next = ctx->OptimizationCollection;
+
+    // Set the head
+    ctx ->OptimizationCollection = fl;
 
     // All is ok
     return TRUE;
 }
 
 // The entry point for LUT optimization
-cmsBool _cmsOptimizePipeline(cmsPipeline**    PtrLut,
+cmsBool _cmsOptimizePipeline(cmsContext ContextID,
+                             cmsPipeline**    PtrLut,
                              int              Intent,
                              cmsUInt32Number* InputFormat,
                              cmsUInt32Number* OutputFormat,
                              cmsUInt32Number* dwFlags)
 {
+    _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);
     _cmsOptimizationCollection* Opts;
     cmsBool AnySuccess = FALSE;
 
@@ -1733,8 +1793,8 @@
     if (*dwFlags & cmsFLAGS_NOOPTIMIZE)
         return FALSE;
 
-    // Try built-in optimizations and plug-in
-    for (Opts = OptimizationCollection;
+    // Try plug-in optimizations
+    for (Opts = ctx->OptimizationCollection;
          Opts != NULL;
          Opts = Opts ->Next) {
 
@@ -1745,6 +1805,17 @@
             }
     }
 
+   // Try built-in optimizations
+    for (Opts = DefaultOptimization;
+         Opts != NULL;
+         Opts = Opts ->Next) {
+
+            if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
+
+                return TRUE;
+            }
+    }
+
     // Only simple optimizations succeeded
     return AnySuccess;
 }
--- a/jdk/src/java.desktop/share/native/liblcms/cmspack.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmspack.c	Fri Sep 19 13:47:19 2014 -0700
@@ -883,6 +883,42 @@
     }
 }
 
+// This is a conversion of XYZ float to 16 bits
+static
+cmsUInt8Number* UnrollXYZFloatTo16(register _cmsTRANSFORM* info,
+                                   register cmsUInt16Number wIn[],
+                                   register cmsUInt8Number* accum,
+                                   register cmsUInt32Number Stride)
+{
+    if (T_PLANAR(info -> InputFormat)) {
+
+        cmsFloat32Number* Pt = (cmsFloat32Number*) accum;
+        cmsCIEXYZ XYZ;
+
+        XYZ.X = Pt[0];
+        XYZ.Y = Pt[Stride];
+        XYZ.Z = Pt[Stride*2];
+        cmsFloat2XYZEncoded(wIn, &XYZ);
+
+        return accum + sizeof(cmsFloat32Number);
+
+    }
+
+    else {
+        cmsFloat32Number* Pt = (cmsFloat32Number*) accum;
+        cmsCIEXYZ XYZ;
+
+        XYZ.X = Pt[0];
+        XYZ.Y = Pt[1];
+        XYZ.Z = Pt[2];
+        cmsFloat2XYZEncoded(wIn, &XYZ);
+
+        accum += 3 * sizeof(cmsFloat32Number) + T_EXTRA(info ->InputFormat) * sizeof(cmsFloat32Number);
+
+        return accum;
+    }
+}
+
 // Check if space is marked as ink
 cmsINLINE cmsBool IsInkSpace(cmsUInt32Number Type)
 {
@@ -2334,6 +2370,39 @@
 }
 
 static
+cmsUInt8Number* PackXYZFloatFrom16(register _cmsTRANSFORM* Info,
+                                   register cmsUInt16Number wOut[],
+                                   register cmsUInt8Number* output,
+                                   register cmsUInt32Number Stride)
+{
+    if (T_PLANAR(Info -> OutputFormat)) {
+
+        cmsCIEXYZ XYZ;
+        cmsFloat32Number* Out = (cmsFloat32Number*) output;
+        cmsXYZEncoded2Float(&XYZ, wOut);
+
+        Out[0]        = (cmsFloat32Number) XYZ.X;
+        Out[Stride]   = (cmsFloat32Number) XYZ.Y;
+        Out[Stride*2] = (cmsFloat32Number) XYZ.Z;
+
+        return output + sizeof(cmsFloat32Number);
+
+    }
+    else {
+
+        cmsCIEXYZ XYZ;
+        cmsFloat32Number* Out = (cmsFloat32Number*) output;
+        cmsXYZEncoded2Float(&XYZ, wOut);
+
+        Out[0] = (cmsFloat32Number) XYZ.X;
+        Out[1] = (cmsFloat32Number) XYZ.Y;
+        Out[2] = (cmsFloat32Number) XYZ.Z;
+
+        return output + (3 * sizeof(cmsFloat32Number) + T_EXTRA(Info ->OutputFormat) * sizeof(cmsFloat32Number));
+    }
+}
+
+static
 cmsUInt8Number* PackDoubleFrom16(register _cmsTRANSFORM* info,
                                 register cmsUInt16Number wOut[],
                                 register cmsUInt8Number* output,
@@ -2893,6 +2962,7 @@
     { TYPE_Lab_DBL,                                 ANYPLANAR|ANYEXTRA,   UnrollLabDoubleTo16},
     { TYPE_XYZ_DBL,                                 ANYPLANAR|ANYEXTRA,   UnrollXYZDoubleTo16},
     { TYPE_Lab_FLT,                                 ANYPLANAR|ANYEXTRA,   UnrollLabFloatTo16},
+    { TYPE_XYZ_FLT,                                 ANYPLANAR|ANYEXTRA,   UnrollXYZFloatTo16},
     { TYPE_GRAY_DBL,                                                 0,   UnrollDouble1Chan},
     { FLOAT_SH(1)|BYTES_SH(0), ANYCHANNELS|ANYPLANAR|ANYSWAPFIRST|ANYFLAVOR|
                                              ANYSWAP|ANYEXTRA|ANYSPACE,   UnrollDoubleTo16},
@@ -3027,6 +3097,7 @@
     { TYPE_XYZ_DBL,                                      ANYPLANAR|ANYEXTRA,  PackXYZDoubleFrom16},
 
     { TYPE_Lab_FLT,                                      ANYPLANAR|ANYEXTRA,  PackLabFloatFrom16},
+    { TYPE_XYZ_FLT,                                      ANYPLANAR|ANYEXTRA,  PackXYZFloatFrom16},
 
     { FLOAT_SH(1)|BYTES_SH(0),      ANYFLAVOR|ANYSWAPFIRST|ANYSWAP|
                                     ANYCHANNELS|ANYPLANAR|ANYEXTRA|ANYSPACE,  PackDoubleFrom16},
@@ -3182,40 +3253,98 @@
 
 } cmsFormattersFactoryList;
 
-static cmsFormattersFactoryList* FactoryList = NULL;
+_cmsFormattersPluginChunkType _cmsFormattersPluginChunk = { NULL };
+
+
+// Duplicates the zone of memory used by the plug-in in the new context
+static
+void DupFormatterFactoryList(struct _cmsContext_struct* ctx,
+                                               const struct _cmsContext_struct* src)
+{
+   _cmsFormattersPluginChunkType newHead = { NULL };
+   cmsFormattersFactoryList*  entry;
+   cmsFormattersFactoryList*  Anterior = NULL;
+   _cmsFormattersPluginChunkType* head = (_cmsFormattersPluginChunkType*) src->chunks[FormattersPlugin];
+
+     _cmsAssert(head != NULL);
+
+   // Walk the list copying all nodes
+   for (entry = head->FactoryList;
+       entry != NULL;
+       entry = entry ->Next) {
+
+           cmsFormattersFactoryList *newEntry = ( cmsFormattersFactoryList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(cmsFormattersFactoryList));
+
+           if (newEntry == NULL)
+               return;
+
+           // We want to keep the linked list order, so this is a little bit tricky
+           newEntry -> Next = NULL;
+           if (Anterior)
+               Anterior -> Next = newEntry;
+
+           Anterior = newEntry;
+
+           if (newHead.FactoryList == NULL)
+               newHead.FactoryList = newEntry;
+   }
+
+   ctx ->chunks[FormattersPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsFormattersPluginChunkType));
+}
+
+// The interpolation plug-in memory chunk allocator/dup
+void _cmsAllocFormattersPluginChunk(struct _cmsContext_struct* ctx,
+                                    const struct _cmsContext_struct* src)
+{
+      _cmsAssert(ctx != NULL);
+
+     if (src != NULL) {
+
+         // Duplicate the LIST
+         DupFormatterFactoryList(ctx, src);
+     }
+     else {
+          static _cmsFormattersPluginChunkType FormattersPluginChunk = { NULL };
+          ctx ->chunks[FormattersPlugin] = _cmsSubAllocDup(ctx ->MemPool, &FormattersPluginChunk, sizeof(_cmsFormattersPluginChunkType));
+     }
+}
+
 
 
 // Formatters management
-cmsBool  _cmsRegisterFormattersPlugin(cmsContext id, cmsPluginBase* Data)
+cmsBool  _cmsRegisterFormattersPlugin(cmsContext ContextID, cmsPluginBase* Data)
 {
+    _cmsFormattersPluginChunkType* ctx = ( _cmsFormattersPluginChunkType*) _cmsContextGetClientChunk(ContextID, FormattersPlugin);
     cmsPluginFormatters* Plugin = (cmsPluginFormatters*) Data;
     cmsFormattersFactoryList* fl ;
 
-    // Reset
+    // Reset to built-in defaults
     if (Data == NULL) {
 
-          FactoryList = NULL;
+          ctx ->FactoryList = NULL;
           return TRUE;
     }
 
-    fl = (cmsFormattersFactoryList*) _cmsPluginMalloc(id, sizeof(cmsFormattersFactoryList));
+    fl = (cmsFormattersFactoryList*) _cmsPluginMalloc(ContextID, sizeof(cmsFormattersFactoryList));
     if (fl == NULL) return FALSE;
 
     fl ->Factory    = Plugin ->FormattersFactory;
 
-    fl ->Next = FactoryList;
-    FactoryList = fl;
+    fl ->Next = ctx -> FactoryList;
+    ctx ->FactoryList = fl;
 
     return TRUE;
 }
 
-cmsFormatter _cmsGetFormatter(cmsUInt32Number Type,         // Specific type, i.e. TYPE_RGB_8
+cmsFormatter _cmsGetFormatter(cmsContext ContextID,
+                             cmsUInt32Number Type,         // Specific type, i.e. TYPE_RGB_8
                              cmsFormatterDirection Dir,
                              cmsUInt32Number dwFlags)
 {
+    _cmsFormattersPluginChunkType* ctx = ( _cmsFormattersPluginChunkType*) _cmsContextGetClientChunk(ContextID, FormattersPlugin);
     cmsFormattersFactoryList* f;
 
-    for (f = FactoryList; f != NULL; f = f ->Next) {
+    for (f =ctx->FactoryList; f != NULL; f = f ->Next) {
 
         cmsFormatter fn = f ->Factory(Type, Dir, dwFlags);
         if (fn.Fmt16 != NULL) return fn;
--- a/jdk/src/java.desktop/share/native/liblcms/cmsplugin.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsplugin.c	Fri Sep 19 13:47:19 2014 -0700
@@ -544,22 +544,31 @@
 
 // Plugin memory management -------------------------------------------------------------------------------------------------
 
-static _cmsSubAllocator* PluginPool = NULL;
+// Specialized malloc for plug-ins, that is freed upon exit.
+void* _cmsPluginMalloc(cmsContext ContextID, cmsUInt32Number size)
+{
+    struct _cmsContext_struct* ctx = _cmsGetContext(ContextID);
 
-// Specialized malloc for plug-ins, that is freed upon exit.
-void* _cmsPluginMalloc(cmsContext id, cmsUInt32Number size)
-{
-    if (PluginPool == NULL)
-        PluginPool = _cmsCreateSubAlloc(id, 4*1024);
+    if (ctx ->MemPool == NULL) {
 
-    return _cmsSubAlloc(PluginPool, size);
+        if (ContextID == NULL) {
+
+            ctx->MemPool = _cmsCreateSubAlloc(0, 2*1024);
+        }
+        else {
+            cmsSignalError(ContextID, cmsERROR_CORRUPTION_DETECTED, "NULL memory pool on context");
+            return NULL;
+        }
+    }
+
+    return _cmsSubAlloc(ctx->MemPool, size);
 }
 
 
 // Main plug-in dispatcher
 cmsBool CMSEXPORT cmsPlugin(void* Plug_in)
 {
-  return cmsPluginTHR(NULL, Plug_in);
+    return cmsPluginTHR(NULL, Plug_in);
 }
 
 cmsBool CMSEXPORT cmsPluginTHR(cmsContext id, void* Plug_in)
@@ -571,12 +580,12 @@
          Plugin = Plugin -> Next) {
 
             if (Plugin -> Magic != cmsPluginMagicNumber) {
-                cmsSignalError(0, cmsERROR_UNKNOWN_EXTENSION, "Unrecognized plugin");
+                cmsSignalError(id, cmsERROR_UNKNOWN_EXTENSION, "Unrecognized plugin");
                 return FALSE;
             }
 
             if (Plugin ->ExpectedVersion > LCMS_VERSION) {
-                cmsSignalError(0, cmsERROR_UNKNOWN_EXTENSION, "plugin needs Little CMS %d, current  version is %d",
+                cmsSignalError(id, cmsERROR_UNKNOWN_EXTENSION, "plugin needs Little CMS %d, current version is %d",
                     Plugin ->ExpectedVersion, LCMS_VERSION);
                 return FALSE;
             }
@@ -584,11 +593,11 @@
             switch (Plugin -> Type) {
 
                 case cmsPluginMemHandlerSig:
-                    if (!_cmsRegisterMemHandlerPlugin(Plugin)) return FALSE;
+                    if (!_cmsRegisterMemHandlerPlugin(id, Plugin)) return FALSE;
                     break;
 
                 case cmsPluginInterpolationSig:
-                    if (!_cmsRegisterInterpPlugin(Plugin)) return FALSE;
+                    if (!_cmsRegisterInterpPlugin(id, Plugin)) return FALSE;
                     break;
 
                 case cmsPluginTagTypeSig:
@@ -623,8 +632,12 @@
                     if (!_cmsRegisterTransformPlugin(id, Plugin)) return FALSE;
                     break;
 
+                case cmsPluginMutexSig:
+                    if (!_cmsRegisterMutexPlugin(id, Plugin)) return FALSE;
+                    break;
+
                 default:
-                    cmsSignalError(0, cmsERROR_UNKNOWN_EXTENSION, "Unrecognized plugin type '%X'", Plugin -> Type);
+                    cmsSignalError(id, cmsERROR_UNKNOWN_EXTENSION, "Unrecognized plugin type '%X'", Plugin -> Type);
                     return FALSE;
             }
     }
@@ -637,19 +650,337 @@
 // Revert all plug-ins to default
 void CMSEXPORT cmsUnregisterPlugins(void)
 {
-    _cmsRegisterMemHandlerPlugin(NULL);
-    _cmsRegisterInterpPlugin(NULL);
-    _cmsRegisterTagTypePlugin(NULL, NULL);
-    _cmsRegisterTagPlugin(NULL, NULL);
-    _cmsRegisterFormattersPlugin(NULL, NULL);
-    _cmsRegisterRenderingIntentPlugin(NULL, NULL);
-    _cmsRegisterParametricCurvesPlugin(NULL, NULL);
-    _cmsRegisterMultiProcessElementPlugin(NULL, NULL);
-    _cmsRegisterOptimizationPlugin(NULL, NULL);
-    _cmsRegisterTransformPlugin(NULL, NULL);
+    cmsUnregisterPluginsTHR(NULL);
+}
 
-    if (PluginPool != NULL)
-        _cmsSubAllocDestroy(PluginPool);
 
-    PluginPool = NULL;
+// The Global storage for system context. This is the one and only global variable
+// pointers structure. All global vars are referenced here.
+static struct _cmsContext_struct globalContext = {
+
+    NULL,                              // Not in the linked list
+    NULL,                              // No suballocator
+    {
+        NULL,                          //  UserPtr,
+        &_cmsLogErrorChunk,            //  Logger,
+        &_cmsAlarmCodesChunk,          //  AlarmCodes,
+        &_cmsAdaptationStateChunk,     //  AdaptationState,
+        &_cmsMemPluginChunk,           //  MemPlugin,
+        &_cmsInterpPluginChunk,        //  InterpPlugin,
+        &_cmsCurvesPluginChunk,        //  CurvesPlugin,
+        &_cmsFormattersPluginChunk,    //  FormattersPlugin,
+        &_cmsTagTypePluginChunk,       //  TagTypePlugin,
+        &_cmsTagPluginChunk,           //  TagPlugin,
+        &_cmsIntentsPluginChunk,       //  IntentPlugin,
+        &_cmsMPETypePluginChunk,       //  MPEPlugin,
+        &_cmsOptimizationPluginChunk,  //  OptimizationPlugin,
+        &_cmsTransformPluginChunk,     //  TransformPlugin,
+        &_cmsMutexPluginChunk          //  MutexPlugin
+    },
+
+    { NULL, NULL, NULL, NULL, NULL, NULL } // The default memory allocator is not used for context 0
+};
+
+
+// The context pool (linked list head)
+static _cmsMutex _cmsContextPoolHeadMutex = CMS_MUTEX_INITIALIZER;
+static struct _cmsContext_struct* _cmsContextPoolHead = NULL;
+
+// Internal, get associated pointer, with guessing. Never returns NULL.
+struct _cmsContext_struct* _cmsGetContext(cmsContext ContextID)
+{
+    struct _cmsContext_struct* id = (struct _cmsContext_struct*) ContextID;
+    struct _cmsContext_struct* ctx;
+
+
+    // On 0, use global settings
+    if (id == NULL)
+        return &globalContext;
+
+    // Search
+    for (ctx = _cmsContextPoolHead;
+         ctx != NULL;
+         ctx = ctx ->Next) {
+
+            // Found it?
+            if (id == ctx)
+                return ctx; // New-style context,
+    }
+
+    return &globalContext;
 }
+
+
+// Internal: get the memory area associanted with each context client
+// Returns the block assigned to the specific zone.
+void* _cmsContextGetClientChunk(cmsContext ContextID, _cmsMemoryClient mc)
+{
+    struct _cmsContext_struct* ctx;
+    void *ptr;
+
+    if (mc < 0 || mc >= MemoryClientMax) {
+        cmsSignalError(ContextID, cmsERROR_RANGE, "Bad context client");
+        return NULL;
+    }
+
+    ctx = _cmsGetContext(ContextID);
+    ptr = ctx ->chunks[mc];
+
+    if (ptr != NULL)
+        return ptr;
+
+    // A null ptr means no special settings for that context, and this
+    // reverts to Context0 globals
+    return globalContext.chunks[mc];
+}
+
+
+// This function returns the given context its default pristine state,
+// as no plug-ins were declared. There is no way to unregister a single
+// plug-in, as a single call to cmsPluginTHR() function may register
+// many different plug-ins simultaneously, then there is no way to
+// identify which plug-in to unregister.
+void CMSEXPORT cmsUnregisterPluginsTHR(cmsContext ContextID)
+{
+    _cmsRegisterMemHandlerPlugin(ContextID, NULL);
+    _cmsRegisterInterpPlugin(ContextID, NULL);
+    _cmsRegisterTagTypePlugin(ContextID, NULL);
+    _cmsRegisterTagPlugin(ContextID, NULL);
+    _cmsRegisterFormattersPlugin(ContextID, NULL);
+    _cmsRegisterRenderingIntentPlugin(ContextID, NULL);
+    _cmsRegisterParametricCurvesPlugin(ContextID, NULL);
+    _cmsRegisterMultiProcessElementPlugin(ContextID, NULL);
+    _cmsRegisterOptimizationPlugin(ContextID, NULL);
+    _cmsRegisterTransformPlugin(ContextID, NULL);
+    _cmsRegisterMutexPlugin(ContextID, NULL);
+}
+
+
+// Returns the memory manager plug-in, if any, from the Plug-in bundle
+static
+cmsPluginMemHandler* _cmsFindMemoryPlugin(void* PluginBundle)
+{
+    cmsPluginBase* Plugin;
+
+    for (Plugin = (cmsPluginBase*) PluginBundle;
+        Plugin != NULL;
+        Plugin = Plugin -> Next) {
+
+            if (Plugin -> Magic == cmsPluginMagicNumber &&
+                Plugin -> ExpectedVersion <= LCMS_VERSION &&
+                Plugin -> Type == cmsPluginMemHandlerSig) {
+
+                    // Found!
+                    return (cmsPluginMemHandler*) Plugin;
+            }
+    }
+
+    // Nope, revert to defaults
+    return NULL;
+}
+
+
+// Creates a new context with optional associated plug-ins. Caller may also specify an optional pointer to user-defined
+// data that will be forwarded to plug-ins and logger.
+cmsContext CMSEXPORT cmsCreateContext(void* Plugin, void* UserData)
+{
+    struct _cmsContext_struct* ctx;
+    struct _cmsContext_struct  fakeContext;
+
+    _cmsInstallAllocFunctions(_cmsFindMemoryPlugin(Plugin), &fakeContext.DefaultMemoryManager);
+
+    fakeContext.chunks[UserPtr]     = UserData;
+    fakeContext.chunks[MemPlugin]   = &fakeContext.DefaultMemoryManager;
+
+    // Create the context structure.
+    ctx = (struct _cmsContext_struct*) _cmsMalloc(&fakeContext, sizeof(struct _cmsContext_struct));
+    if (ctx == NULL)
+        return NULL;     // Something very wrong happened!
+
+    // Init the structure and the memory manager
+    memset(ctx, 0, sizeof(struct _cmsContext_struct));
+
+    // Keep memory manager
+    memcpy(&ctx->DefaultMemoryManager, &fakeContext.DefaultMemoryManager, sizeof(_cmsMemPluginChunk));
+
+    // Maintain the linked list (with proper locking)
+    _cmsEnterCriticalSectionPrimitive(&_cmsContextPoolHeadMutex);
+       ctx ->Next = _cmsContextPoolHead;
+       _cmsContextPoolHead = ctx;
+    _cmsLeaveCriticalSectionPrimitive(&_cmsContextPoolHeadMutex);
+
+    ctx ->chunks[UserPtr]     = UserData;
+    ctx ->chunks[MemPlugin]   = &ctx->DefaultMemoryManager;
+
+    // Now we can allocate the pool by using default memory manager
+    ctx ->MemPool = _cmsCreateSubAlloc(ctx, 22 * sizeof(void*));  // default size about 32 pointers
+    if (ctx ->MemPool == NULL) {
+
+         cmsDeleteContext(ctx);
+        return NULL;
+    }
+
+    _cmsAllocLogErrorChunk(ctx, NULL);
+    _cmsAllocAlarmCodesChunk(ctx, NULL);
+    _cmsAllocAdaptationStateChunk(ctx, NULL);
+    _cmsAllocMemPluginChunk(ctx, NULL);
+    _cmsAllocInterpPluginChunk(ctx, NULL);
+    _cmsAllocCurvesPluginChunk(ctx, NULL);
+    _cmsAllocFormattersPluginChunk(ctx, NULL);
+    _cmsAllocTagTypePluginChunk(ctx, NULL);
+    _cmsAllocMPETypePluginChunk(ctx, NULL);
+    _cmsAllocTagPluginChunk(ctx, NULL);
+    _cmsAllocIntentsPluginChunk(ctx, NULL);
+    _cmsAllocOptimizationPluginChunk(ctx, NULL);
+    _cmsAllocTransformPluginChunk(ctx, NULL);
+    _cmsAllocMutexPluginChunk(ctx, NULL);
+
+    // Setup the plug-ins
+    if (!cmsPluginTHR(ctx, Plugin)) {
+
+        cmsDeleteContext(ctx);
+        return NULL;
+    }
+
+    return (cmsContext) ctx;
+}
+
+// Duplicates a context with all associated plug-ins.
+// Caller may specify an optional pointer to user-defined
+// data that will be forwarded to plug-ins and logger.
+cmsContext CMSEXPORT cmsDupContext(cmsContext ContextID, void* NewUserData)
+{
+    int i;
+    struct _cmsContext_struct* ctx;
+    const struct _cmsContext_struct* src = _cmsGetContext(ContextID);
+
+    void* userData = (NewUserData != NULL) ? NewUserData : src -> chunks[UserPtr];
+
+
+    ctx = (struct _cmsContext_struct*) _cmsMalloc(ContextID, sizeof(struct _cmsContext_struct));
+    if (ctx == NULL)
+        return NULL;     // Something very wrong happened
+
+    // Setup default memory allocators
+    memcpy(&ctx->DefaultMemoryManager, &src->DefaultMemoryManager, sizeof(ctx->DefaultMemoryManager));
+
+    // Maintain the linked list
+    _cmsEnterCriticalSectionPrimitive(&_cmsContextPoolHeadMutex);
+       ctx ->Next = _cmsContextPoolHead;
+       _cmsContextPoolHead = ctx;
+    _cmsLeaveCriticalSectionPrimitive(&_cmsContextPoolHeadMutex);
+
+    ctx ->chunks[UserPtr]    = userData;
+    ctx ->chunks[MemPlugin]  = &ctx->DefaultMemoryManager;
+
+    ctx ->MemPool = _cmsCreateSubAlloc(ctx, 22 * sizeof(void*));
+    if (ctx ->MemPool == NULL) {
+
+         cmsDeleteContext(ctx);
+        return NULL;
+    }
+
+    // Allocate all required chunks.
+    _cmsAllocLogErrorChunk(ctx, src);
+    _cmsAllocAlarmCodesChunk(ctx, src);
+    _cmsAllocAdaptationStateChunk(ctx, src);
+    _cmsAllocMemPluginChunk(ctx, src);
+    _cmsAllocInterpPluginChunk(ctx, src);
+    _cmsAllocCurvesPluginChunk(ctx, src);
+    _cmsAllocFormattersPluginChunk(ctx, src);
+    _cmsAllocTagTypePluginChunk(ctx, src);
+    _cmsAllocMPETypePluginChunk(ctx, src);
+    _cmsAllocTagPluginChunk(ctx, src);
+    _cmsAllocIntentsPluginChunk(ctx, src);
+    _cmsAllocOptimizationPluginChunk(ctx, src);
+    _cmsAllocTransformPluginChunk(ctx, src);
+    _cmsAllocMutexPluginChunk(ctx, src);
+
+    // Make sure no one failed
+    for (i=Logger; i < MemoryClientMax; i++) {
+
+        if (src ->chunks[i] == NULL) {
+            cmsDeleteContext((cmsContext) ctx);
+            return NULL;
+        }
+    }
+
+    return (cmsContext) ctx;
+}
+
+
+
+static
+struct _cmsContext_struct* FindPrev(struct _cmsContext_struct* id)
+{
+    struct _cmsContext_struct* prev;
+
+    // Search for previous
+    for (prev = _cmsContextPoolHead;
+             prev != NULL;
+             prev = prev ->Next)
+    {
+        if (prev ->Next == id)
+            return prev;
+    }
+
+    return NULL;  // List is empty or only one element!
+}
+
+// Frees any resources associated with the given context,
+// and destroys the context placeholder.
+// The ContextID can no longer be used in any THR operation.
+void CMSEXPORT cmsDeleteContext(cmsContext ContextID)
+{
+    if (ContextID != NULL) {
+
+        struct _cmsContext_struct* ctx = (struct _cmsContext_struct*) ContextID;
+        struct _cmsContext_struct  fakeContext;
+        struct _cmsContext_struct* prev;
+
+        memcpy(&fakeContext.DefaultMemoryManager, &ctx->DefaultMemoryManager, sizeof(ctx->DefaultMemoryManager));
+
+        fakeContext.chunks[UserPtr]     = ctx ->chunks[UserPtr];
+        fakeContext.chunks[MemPlugin]   = &fakeContext.DefaultMemoryManager;
+
+        // Get rid of plugins
+        cmsUnregisterPluginsTHR(ContextID);
+
+        // Since all memory is allocated in the private pool, all what we need to do is destroy the pool
+        if (ctx -> MemPool != NULL)
+              _cmsSubAllocDestroy(ctx ->MemPool);
+        ctx -> MemPool = NULL;
+
+        // Maintain list
+        _cmsEnterCriticalSectionPrimitive(&_cmsContextPoolHeadMutex);
+        if (_cmsContextPoolHead == ctx) {
+
+            _cmsContextPoolHead = ctx->Next;
+        }
+        else {
+
+            // Search for previous
+            for (prev = _cmsContextPoolHead;
+                prev != NULL;
+                prev = prev ->Next)
+            {
+                if (prev -> Next == ctx) {
+                    prev -> Next = ctx ->Next;
+                    break;
+                }
+            }
+        }
+        _cmsLeaveCriticalSectionPrimitive(&_cmsContextPoolHeadMutex);
+
+        // free the memory block itself
+        _cmsFree(&fakeContext, ctx);
+    }
+}
+
+// Returns the user data associated to the given ContextID, or NULL if no user data was attached on context creation
+void* CMSEXPORT cmsGetContextUserData(cmsContext ContextID)
+{
+    return _cmsContextGetClientChunk(ContextID, UserPtr);
+}
+
+
--- a/jdk/src/java.desktop/share/native/liblcms/cmsps2.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsps2.c	Fri Sep 19 13:47:19 2014 -0700
@@ -942,7 +942,7 @@
             if (DeviceLink == NULL) return 0;
 
             dwFlags |= cmsFLAGS_FORCE_CLUT;
-            _cmsOptimizePipeline(&DeviceLink, Intent, &InputFormat, &OutFrm, &dwFlags);
+            _cmsOptimizePipeline(m->ContextID, &DeviceLink, Intent, &InputFormat, &OutFrm, &dwFlags);
 
             rc = EmitCIEBasedDEF(m, DeviceLink, Intent, &BlackPointAdaptedToD50);
             cmsPipelineFree(DeviceLink);
@@ -1359,7 +1359,7 @@
 
     // We need a CLUT
     dwFlags |= cmsFLAGS_FORCE_CLUT;
-    _cmsOptimizePipeline(&DeviceLink, RelativeEncodingIntent, &InFrm, &OutputFormat, &dwFlags);
+    _cmsOptimizePipeline(m->ContextID, &DeviceLink, RelativeEncodingIntent, &InFrm, &OutputFormat, &dwFlags);
 
     _cmsIOPrintf(m, "<<\n");
     _cmsIOPrintf(m, "/ColorRenderingType 1\n");
--- a/jdk/src/java.desktop/share/native/liblcms/cmstypes.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmstypes.c	Fri Sep 19 13:47:19 2014 -0700
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2011 Marti Maria Saguer
+//  Copyright (c) 1998-2014 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"),
@@ -61,7 +61,7 @@
 // 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
 // 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 multiprofile
+// and the third one is very specific: allows to extend the number of elements in the multiprocessing
 // elements special type.
 //--------------------------------------------------------------------------------------------------
 
@@ -89,54 +89,49 @@
 // Helper macro to define a MPE handler. Callbacks do have a fixed naming convention
 #define TYPE_MPE_HANDLER(t, x)  { (t), READ_FN(x), WRITE_FN(x), GenericMPEdup, GenericMPEfree, NULL, 0 }
 
-// Register a new type handler. This routine is shared between normal types and MPE
+// Register a new type handler. This routine is shared between normal types and MPE. LinkedList points to the optional list head
 static
-cmsBool RegisterTypesPlugin(cmsContext id, cmsPluginBase* Data, _cmsTagTypeLinkedList* LinkedList, cmsUInt32Number DefaultListCount)
+cmsBool RegisterTypesPlugin(cmsContext id, cmsPluginBase* Data, _cmsMemoryClient pos)
 {
     cmsPluginTagType* Plugin = (cmsPluginTagType*) Data;
-    _cmsTagTypeLinkedList *pt, *Anterior = NULL;
+    _cmsTagTypePluginChunkType* ctx = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(id, pos);
+    _cmsTagTypeLinkedList *pt;
 
     // Calling the function with NULL as plug-in would unregister the plug in.
     if (Data == NULL) {
 
-        LinkedList[DefaultListCount-1].Next = NULL;
+        // There is no need to set free the memory, as pool is destroyed as a whole.
+        ctx ->TagTypes = NULL;
         return TRUE;
     }
 
-    pt = Anterior = LinkedList;
-    while (pt != NULL) {
-
-        if (Plugin->Handler.Signature == pt -> Handler.Signature) {
-            pt ->Handler = Plugin ->Handler;    // Replace old behaviour.
-            // Note that since no memory is allocated, unregister does not
-            // reset this action.
-            return TRUE;
-        }
-
-        Anterior = pt;
-        pt = pt ->Next;
-    }
-
-    // Registering happens in plug-in memory pool
+    // Registering happens in plug-in memory pool.
     pt = (_cmsTagTypeLinkedList*) _cmsPluginMalloc(id, sizeof(_cmsTagTypeLinkedList));
     if (pt == NULL) return FALSE;
 
     pt ->Handler   = Plugin ->Handler;
-    pt ->Next      = NULL;
-
-    if (Anterior)
-        Anterior -> Next = pt;
+    pt ->Next      = ctx ->TagTypes;
+
+    ctx ->TagTypes = pt;
 
     return TRUE;
 }
 
-// Return handler for a given type or NULL if not found. Shared between normal types and MPE
+// Return handler for a given type or NULL if not found. Shared between normal types and MPE. It first tries the additons
+// made by plug-ins and then the built-in defaults.
 static
-cmsTagTypeHandler* GetHandler(cmsTagTypeSignature sig, _cmsTagTypeLinkedList* LinkedList)
+cmsTagTypeHandler* GetHandler(cmsTagTypeSignature sig, _cmsTagTypeLinkedList* PluginLinkedList, _cmsTagTypeLinkedList* DefaultLinkedList)
 {
     _cmsTagTypeLinkedList* pt;
 
-    for (pt = LinkedList;
+    for (pt = PluginLinkedList;
+         pt != NULL;
+         pt = pt ->Next) {
+
+            if (sig == pt -> Handler.Signature) return &pt ->Handler;
+    }
+
+    for (pt = DefaultLinkedList;
          pt != NULL;
          pt = pt ->Next) {
 
@@ -163,6 +158,7 @@
     return TRUE;
 }
 
+// Auxiliar to read an array of wchar_t
 static
 cmsBool _cmsReadWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, wchar_t* Array)
 {
@@ -777,6 +773,8 @@
 
     // Create memory
     Text = (char*) _cmsMalloc(self ->ContextID, size);
+    if (Text == NULL) return FALSE;
+
     cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text, size);
 
     // Write it, including separator
@@ -1783,7 +1781,6 @@
     if (!_cmsReadUInt8Number(io, NULL)) goto Error;
 
     // Do some checking
-
     if (InputChannels > cmsMAXCHANNELS)  goto Error;
     if (OutputChannels > cmsMAXCHANNELS) goto Error;
 
@@ -1824,9 +1821,16 @@
         if (T  == NULL) goto Error;
 
         Temp = (cmsUInt8Number*) _cmsMalloc(self ->ContextID, nTabSize);
-        if (Temp == NULL) goto Error;
-
-        if (io ->Read(io, Temp, nTabSize, 1) != 1) goto Error;
+        if (Temp == NULL) {
+            _cmsFree(self ->ContextID, T);
+            goto Error;
+        }
+
+        if (io ->Read(io, Temp, nTabSize, 1) != 1) {
+            _cmsFree(self ->ContextID, T);
+            _cmsFree(self ->ContextID, Temp);
+            goto Error;
+        }
 
         for (i = 0; i < nTabSize; i++) {
 
@@ -2371,27 +2375,30 @@
     // Precision can be 1 or 2 bytes
     if (Precision == 1) {
 
-       cmsUInt8Number  v;
+        cmsUInt8Number  v;
 
         for (i=0; i < Data ->nEntries; i++) {
 
-                if (io ->Read(io, &v, sizeof(cmsUInt8Number), 1) != 1) return NULL;
-                Data ->Tab.T[i] = FROM_8_TO_16(v);
+            if (io ->Read(io, &v, sizeof(cmsUInt8Number), 1) != 1) return NULL;
+            Data ->Tab.T[i] = FROM_8_TO_16(v);
         }
 
     }
     else
         if (Precision == 2) {
 
-            if (!_cmsReadUInt16Array(io, Data->nEntries, Data ->Tab.T)) return NULL;
-    }
-    else {
-        cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown precision of '%d'", Precision);
-        return NULL;
-    }
-
-
-    return CLUT;
+            if (!_cmsReadUInt16Array(io, Data->nEntries, Data ->Tab.T)) {
+                cmsStageFree(CLUT);
+                return NULL;
+            }
+        }
+        else {
+            cmsStageFree(CLUT);
+            cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown precision of '%d'", Precision);
+            return NULL;
+        }
+
+        return CLUT;
 }
 
 static
@@ -4374,7 +4381,7 @@
 {TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigCLutElemType,         MPEclut),        NULL },
 };
 
-#define DEFAULT_MPE_TYPE_COUNT  (sizeof(SupportedMPEtypes) / sizeof(_cmsTagTypeLinkedList))
+_cmsTagTypePluginChunkType _cmsMPETypePluginChunk = { NULL };
 
 static
 cmsBool ReadMPEElem(struct _cms_typehandler_struct* self,
@@ -4387,6 +4394,8 @@
     cmsTagTypeHandler* TypeHandler;
     cmsUInt32Number nItems;
     cmsPipeline *NewLUT = (cmsPipeline *) Cargo;
+    _cmsTagTypePluginChunkType* MPETypePluginChunk  = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(self->ContextID, MPEPlugin);
+
 
     // Take signature and channels for each element.
     if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) return FALSE;
@@ -4395,7 +4404,7 @@
     if (!_cmsReadUInt32Number(io, NULL)) return FALSE;
 
     // Read diverse MPE types
-    TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, SupportedMPEtypes);
+    TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, MPETypePluginChunk ->TagTypes, SupportedMPEtypes);
     if (TypeHandler == NULL)  {
 
         char String[5];
@@ -4472,6 +4481,7 @@
     cmsPipeline* Lut = (cmsPipeline*) Ptr;
     cmsStage* Elem = Lut ->Elements;
     cmsTagTypeHandler* TypeHandler;
+    _cmsTagTypePluginChunkType* MPETypePluginChunk  = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(self->ContextID, MPEPlugin);
 
     BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
 
@@ -4505,7 +4515,7 @@
 
         ElementSig = Elem ->Type;
 
-        TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, SupportedMPEtypes);
+        TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, MPETypePluginChunk->TagTypes, SupportedMPEtypes);
         if (TypeHandler == NULL)  {
 
                 char String[5];
@@ -5125,7 +5135,7 @@
         }
         else {
 
-        rc = cmsDictAddEntry(hDict, NameWCS, ValueWCS, DisplayNameMLU, DisplayValueMLU);
+            rc = cmsDictAddEntry(hDict, NameWCS, ValueWCS, DisplayNameMLU, DisplayValueMLU);
         }
 
         if (NameWCS != NULL) _cmsFree(self ->ContextID, NameWCS);
@@ -5282,24 +5292,95 @@
 {TYPE_HANDLER(cmsSigVcgtType,                  vcgt),                NULL }
 };
 
-#define DEFAULT_TAG_TYPE_COUNT  (sizeof(SupportedTagTypes) / sizeof(_cmsTagTypeLinkedList))
+
+_cmsTagTypePluginChunkType _cmsTagTypePluginChunk = { NULL };
+
+
+
+// Duplicates the zone of memory used by the plug-in in the new context
+static
+void DupTagTypeList(struct _cmsContext_struct* ctx,
+                    const struct _cmsContext_struct* src,
+                    int loc)
+{
+   _cmsTagTypePluginChunkType newHead = { NULL };
+   _cmsTagTypeLinkedList*  entry;
+   _cmsTagTypeLinkedList*  Anterior = NULL;
+   _cmsTagTypePluginChunkType* head = (_cmsTagTypePluginChunkType*) src->chunks[loc];
+
+   // Walk the list copying all nodes
+   for (entry = head->TagTypes;
+       entry != NULL;
+       entry = entry ->Next) {
+
+           _cmsTagTypeLinkedList *newEntry = ( _cmsTagTypeLinkedList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsTagTypeLinkedList));
+
+           if (newEntry == NULL)
+               return;
+
+           // We want to keep the linked list order, so this is a little bit tricky
+           newEntry -> Next = NULL;
+           if (Anterior)
+               Anterior -> Next = newEntry;
+
+           Anterior = newEntry;
+
+           if (newHead.TagTypes == NULL)
+               newHead.TagTypes = newEntry;
+   }
+
+   ctx ->chunks[loc] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTagTypePluginChunkType));
+}
+
+
+void _cmsAllocTagTypePluginChunk(struct _cmsContext_struct* ctx,
+                                 const struct _cmsContext_struct* src)
+{
+    if (src != NULL) {
+
+        // Duplicate the LIST
+        DupTagTypeList(ctx, src, TagTypePlugin);
+    }
+    else {
+        static _cmsTagTypePluginChunkType TagTypePluginChunk = { NULL };
+        ctx ->chunks[TagTypePlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagTypePluginChunk, sizeof(_cmsTagTypePluginChunkType));
+    }
+}
+
+void _cmsAllocMPETypePluginChunk(struct _cmsContext_struct* ctx,
+                               const struct _cmsContext_struct* src)
+{
+    if (src != NULL) {
+
+        // Duplicate the LIST
+        DupTagTypeList(ctx, src, MPEPlugin);
+    }
+    else {
+        static _cmsTagTypePluginChunkType TagTypePluginChunk = { NULL };
+        ctx ->chunks[MPEPlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagTypePluginChunk, sizeof(_cmsTagTypePluginChunkType));
+    }
+
+}
+
 
 // Both kind of plug-ins share same structure
 cmsBool  _cmsRegisterTagTypePlugin(cmsContext id, cmsPluginBase* Data)
 {
-    return RegisterTypesPlugin(id, Data, SupportedTagTypes, DEFAULT_TAG_TYPE_COUNT);
+    return RegisterTypesPlugin(id, Data, TagTypePlugin);
 }
 
 cmsBool  _cmsRegisterMultiProcessElementPlugin(cmsContext id, cmsPluginBase* Data)
 {
-    return RegisterTypesPlugin(id, Data, SupportedMPEtypes, DEFAULT_MPE_TYPE_COUNT);
+    return RegisterTypesPlugin(id, Data,MPEPlugin);
 }
 
 
 // Wrapper for tag types
-cmsTagTypeHandler* _cmsGetTagTypeHandler(cmsTagTypeSignature sig)
-{
-    return GetHandler(sig, SupportedTagTypes);
+cmsTagTypeHandler* _cmsGetTagTypeHandler(cmsContext ContextID, cmsTagTypeSignature sig)
+{
+    _cmsTagTypePluginChunkType* ctx = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(ContextID, TagTypePlugin);
+
+    return GetHandler(sig, ctx->TagTypes, SupportedTagTypes);
 }
 
 // ********************************************************************************
@@ -5414,48 +5495,94 @@
     cmsSigDeviceSettingsTag   ==> Deprecated, useless
 */
 
-#define DEFAULT_TAG_COUNT  (sizeof(SupportedTags) / sizeof(_cmsTagLinkedList))
+
+_cmsTagPluginChunkType _cmsTagPluginChunk = { NULL };
+
+
+// Duplicates the zone of memory used by the plug-in in the new context
+static
+void DupTagList(struct _cmsContext_struct* ctx,
+                    const struct _cmsContext_struct* src)
+{
+   _cmsTagPluginChunkType newHead = { NULL };
+   _cmsTagLinkedList*  entry;
+   _cmsTagLinkedList*  Anterior = NULL;
+   _cmsTagPluginChunkType* head = (_cmsTagPluginChunkType*) src->chunks[TagPlugin];
+
+   // Walk the list copying all nodes
+   for (entry = head->Tag;
+       entry != NULL;
+       entry = entry ->Next) {
+
+           _cmsTagLinkedList *newEntry = ( _cmsTagLinkedList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsTagLinkedList));
+
+           if (newEntry == NULL)
+               return;
+
+           // We want to keep the linked list order, so this is a little bit tricky
+           newEntry -> Next = NULL;
+           if (Anterior)
+               Anterior -> Next = newEntry;
+
+           Anterior = newEntry;
+
+           if (newHead.Tag == NULL)
+               newHead.Tag = newEntry;
+   }
+
+   ctx ->chunks[TagPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTagPluginChunkType));
+}
+
+void _cmsAllocTagPluginChunk(struct _cmsContext_struct* ctx,
+                                 const struct _cmsContext_struct* src)
+{
+    if (src != NULL) {
+
+        DupTagList(ctx, src);
+    }
+    else {
+        static _cmsTagPluginChunkType TagPluginChunk = { NULL };
+        ctx ->chunks[TagPlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagPluginChunk, sizeof(_cmsTagPluginChunkType));
+    }
+
+}
 
 cmsBool  _cmsRegisterTagPlugin(cmsContext id, cmsPluginBase* Data)
 {
     cmsPluginTag* Plugin = (cmsPluginTag*) Data;
-    _cmsTagLinkedList *pt, *Anterior;
-
+    _cmsTagLinkedList *pt;
+    _cmsTagPluginChunkType* TagPluginChunk = ( _cmsTagPluginChunkType*) _cmsContextGetClientChunk(id, TagPlugin);
 
     if (Data == NULL) {
 
-        SupportedTags[DEFAULT_TAG_COUNT-1].Next = NULL;
+        TagPluginChunk->Tag = NULL;
         return TRUE;
     }
 
-    pt = Anterior = SupportedTags;
-    while (pt != NULL) {
-
-        if (Plugin->Signature == pt -> Signature) {
-            pt ->Descriptor = Plugin ->Descriptor;  // Replace old behaviour
-            return TRUE;
-        }
-
-        Anterior = pt;
-        pt = pt ->Next;
-    }
-
     pt = (_cmsTagLinkedList*) _cmsPluginMalloc(id, sizeof(_cmsTagLinkedList));
     if (pt == NULL) return FALSE;
 
     pt ->Signature  = Plugin ->Signature;
     pt ->Descriptor = Plugin ->Descriptor;
-    pt ->Next       = NULL;
-
-    if (Anterior != NULL) Anterior -> Next = pt;
+    pt ->Next       = TagPluginChunk ->Tag;
+
+    TagPluginChunk ->Tag = pt;
 
     return TRUE;
 }
 
 // Return a descriptor for a given tag or NULL
-cmsTagDescriptor* _cmsGetTagDescriptor(cmsTagSignature sig)
+cmsTagDescriptor* _cmsGetTagDescriptor(cmsContext ContextID, cmsTagSignature sig)
 {
     _cmsTagLinkedList* pt;
+    _cmsTagPluginChunkType* TagPluginChunk = ( _cmsTagPluginChunkType*) _cmsContextGetClientChunk(ContextID, TagPlugin);
+
+    for (pt = TagPluginChunk->Tag;
+             pt != NULL;
+             pt = pt ->Next) {
+
+                if (sig == pt -> Signature) return &pt ->Descriptor;
+    }
 
     for (pt = SupportedTags;
             pt != NULL;
--- a/jdk/src/java.desktop/share/native/liblcms/cmsvirt.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsvirt.c	Fri Sep 19 13:47:19 2014 -0700
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2011 Marti Maria Saguer
+//  Copyright (c) 1998-2014 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"),
@@ -1019,7 +1019,7 @@
 
 static const cmsAllowedLUT AllowedLUTTypes[] = {
 
-    { FALSE, 0,              cmsSigLut16Type,    4,  { cmsSigMatrixElemType,  cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType}},
+    { FALSE, 0,              cmsSigLut16Type,    4,  { cmsSigMatrixElemType,   cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType}},
     { FALSE, 0,              cmsSigLut16Type,    3,  { cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType}},
     { FALSE, 0,              cmsSigLut16Type,    2,  { cmsSigCurveSetElemType, cmsSigCLutElemType}},
     { TRUE , 0,              cmsSigLutAtoBType,  1,  { cmsSigCurveSetElemType }},
@@ -1150,7 +1150,7 @@
     if (AllowedLUT == NULL) {
 
         // Try to optimize
-        _cmsOptimizePipeline(&LUT, xform ->RenderingIntent, &FrmIn, &FrmOut, &dwFlags);
+        _cmsOptimizePipeline(ContextID, &LUT, xform ->RenderingIntent, &FrmIn, &FrmOut, &dwFlags);
         AllowedLUT = FindCombination(LUT, Version >= 4.0, DestinationTag);
 
     }
@@ -1159,7 +1159,7 @@
     if (AllowedLUT == NULL) {
 
         dwFlags |= cmsFLAGS_FORCE_CLUT;
-        _cmsOptimizePipeline(&LUT, xform ->RenderingIntent, &FrmIn, &FrmOut, &dwFlags);
+        _cmsOptimizePipeline(ContextID, &LUT, xform ->RenderingIntent, &FrmIn, &FrmOut, &dwFlags);
 
         // Put identity curves if needed
         if (cmsPipelineGetPtrToFirstStage(LUT) ->Type != cmsSigCurveSetElemType)
--- a/jdk/src/java.desktop/share/native/liblcms/cmswtpnt.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmswtpnt.c	Fri Sep 19 13:47:19 2014 -0700
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2012 Marti Maria Saguer
+//  Copyright (c) 1998-2014 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"),
--- a/jdk/src/java.desktop/share/native/liblcms/cmsxform.c	Fri Sep 19 08:19:04 2014 -0400
+++ b/jdk/src/java.desktop/share/native/liblcms/cmsxform.c	Fri Sep 19 13:47:19 2014 -0700
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2011 Marti Maria Saguer
+//  Copyright (c) 1998-2014 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"),
@@ -58,44 +58,120 @@
 // Transformations stuff
 // -----------------------------------------------------------------------
 
-// Alarm codes for 16-bit transformations, because the fixed range of containers there are
-// no values left to mark out of gamut. volatile is C99 per 6.2.5
-static volatile cmsUInt16Number Alarm[cmsMAXCHANNELS] = { 0x7F00, 0x7F00, 0x7F00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
-static volatile cmsFloat64Number GlobalAdaptationState = 1;
+#define DEFAULT_OBSERVER_ADAPTATION_STATE 1.0
+
+// The Context0 observer adaptation state.
+_cmsAdaptationStateChunkType _cmsAdaptationStateChunk = { DEFAULT_OBSERVER_ADAPTATION_STATE };
+
+// Init and duplicate observer adaptation state
+void _cmsAllocAdaptationStateChunk(struct _cmsContext_struct* ctx,
+                                   const struct _cmsContext_struct* src)
+{
+    static _cmsAdaptationStateChunkType AdaptationStateChunk = { DEFAULT_OBSERVER_ADAPTATION_STATE };
+    void* from;
+
+    if (src != NULL) {
+        from = src ->chunks[AdaptationStateContext];
+    }
+    else {
+       from = &AdaptationStateChunk;
+    }
+
+    ctx ->chunks[AdaptationStateContext] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsAdaptationStateChunkType));
+}
+
+
+// Sets adaptation state for absolute colorimetric intent in the given context.  Adaptation state applies on all
+// but cmsCreateExtendedTransformTHR().  Little CMS can handle incomplete adaptation states.
+cmsFloat64Number CMSEXPORT cmsSetAdaptationStateTHR(cmsContext ContextID, cmsFloat64Number d)
+{
+    cmsFloat64Number prev;
+    _cmsAdaptationStateChunkType* ptr = (_cmsAdaptationStateChunkType*) _cmsContextGetClientChunk(ContextID, AdaptationStateContext);
+
+    // Get previous value for return
+    prev = ptr ->AdaptationState;
+
+    // Set the value if d is positive or zero
+    if (d >= 0.0) {
+
+        ptr ->AdaptationState = d;
+    }
+
+    // Always return previous value
+    return prev;
+}
+
 
 // The adaptation state may be defaulted by this function. If you don't like it, use the extended transform routine
 cmsFloat64Number CMSEXPORT cmsSetAdaptationState(cmsFloat64Number d)
 {
-    cmsFloat64Number OldVal = GlobalAdaptationState;
-
-    if (d >= 0)
-        GlobalAdaptationState = d;
-
-    return OldVal;
+    return cmsSetAdaptationStateTHR(NULL, d);
 }
 
-// Alarm codes are always global
-void CMSEXPORT cmsSetAlarmCodes(cmsUInt16Number NewAlarm[cmsMAXCHANNELS])
+// -----------------------------------------------------------------------
+
+// Alarm codes for 16-bit transformations, because the fixed range of containers there are
+// no values left to mark out of gamut.
+
+#define DEFAULT_ALARM_CODES_VALUE {0x7F00, 0x7F00, 0x7F00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+
+_cmsAlarmCodesChunkType _cmsAlarmCodesChunk = { DEFAULT_ALARM_CODES_VALUE };
+
+// Sets the codes used to mark out-out-gamut on Proofing transforms for a given context. Values are meant to be
+// encoded in 16 bits.
+void CMSEXPORT cmsSetAlarmCodesTHR(cmsContext ContextID, const cmsUInt16Number AlarmCodesP[cmsMAXCHANNELS])
 {
-    int i;
+    _cmsAlarmCodesChunkType* ContextAlarmCodes = (_cmsAlarmCodesChunkType*) _cmsContextGetClientChunk(ContextID, AlarmCodesContext);
 
+    _cmsAssert(ContextAlarmCodes != NULL); // Can't happen
+
+    memcpy(ContextAlarmCodes->AlarmCodes, AlarmCodesP, sizeof(ContextAlarmCodes->AlarmCodes));
+}
+
+// Gets the current codes used to mark out-out-gamut on Proofing transforms for the given context.
+// Values are meant to be encoded in 16 bits.
+void CMSEXPORT cmsGetAlarmCodesTHR(cmsContext ContextID, cmsUInt16Number AlarmCodesP[cmsMAXCHANNELS])
+{
+    _cmsAlarmCodesChunkType* ContextAlarmCodes = (_cmsAlarmCodesChunkType*) _cmsContextGetClientChunk(ContextID, AlarmCodesContext);
+
+    _cmsAssert(ContextAlarmCodes != NULL); // Can't happen
+
+    memcpy(AlarmCodesP, ContextAlarmCodes->AlarmCodes, sizeof(ContextAlarmCodes->AlarmCodes));
+}
+
+void CMSEXPORT cmsSetAlarmCodes(const cmsUInt16Number NewAlarm[cmsMAXCHANNELS])
+{
     _cmsAssert(NewAlarm != NULL);
 
-    for (i=0; i < cmsMAXCHANNELS; i++)
-        Alarm[i] = NewAlarm[i];
+    cmsSetAlarmCodesTHR(NULL, NewAlarm);
 }
 
-// You can get the codes cas well
 void CMSEXPORT cmsGetAlarmCodes(cmsUInt16Number OldAlarm[cmsMAXCHANNELS])
 {
-    int i;
+    _cmsAssert(OldAlarm != NULL);
+    cmsGetAlarmCodesTHR(NULL, OldAlarm);
+}
 
-    _cmsAssert(OldAlarm != NULL);
 
-    for (i=0; i < cmsMAXCHANNELS; i++)
-        OldAlarm[i] = Alarm[i];
+// Init and duplicate alarm codes
+void _cmsAllocAlarmCodesChunk(struct _cmsContext_struct* ctx,
+                              const struct _cmsContext_struct* src)
+{
+    static _cmsAlarmCodesChunkType AlarmCodesChunk = { DEFAULT_ALARM_CODES_VALUE };
+    void* from;
+
+    if (src != NULL) {
+        from = src ->chunks[AlarmCodesContext];
+    }
+    else {
+       from = &AlarmCodesChunk;
+    }
+
+    ctx ->chunks[AlarmCodesContext] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsAlarmCodesChunkType));
 }
 
+// -----------------------------------------------------------------------
+
 // Get rid of transform resources
 void CMSEXPORT cmsDeleteTransform(cmsHTRANSFORM hTransform)
 {
@@ -202,6 +278,30 @@
     }
 }
 
+
+static
+void NullFloatXFORM(_cmsTRANSFORM* p,
+                    const void* in,
+                    void* out,
+                    cmsUInt32Number Size,
+                    cmsUInt32Number Stride)
+{
+    cmsUInt8Number* accum;
+    cmsUInt8Number* output;
+    cmsFloat32Number fIn[cmsMAXCHANNELS];
+    cmsUInt32Number i, n;
+
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;
+
+    for (i=0; i < n; i++) {
+
+        accum  = p -> FromInputFloat(p, fIn, accum, Stride);
+        output = p -> ToOutputFloat(p, fIn, output, Stride);
+    }
+}
+
 // 16 bit precision -----------------------------------------------------------------------------------------------------------
 
 // Null transformation, only applies formatters. No caché
@@ -252,7 +352,7 @@
 }
 
 
-// Auxiliar: Handle precalculated gamut check
+// Auxiliar: 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[],
@@ -264,9 +364,12 @@
     if (wOutOfGamut >= 1) {
 
         cmsUInt16Number i;
+        _cmsAlarmCodesChunkType* ContextAlarmCodes = (_cmsAlarmCodesChunkType*) _cmsContextGetClientChunk(p->ContextID, AlarmCodesContext);
 
-        for (i=0; i < p ->Lut->OutputChannels; i++)
-            wOut[i] = Alarm[i];
+        for (i=0; i < p ->Lut->OutputChannels; i++) {
+
+            wOut[i] = ContextAlarmCodes ->AlarmCodes[i];
+        }
     }
     else
         p ->Lut ->Eval16Fn(wIn, wOut, p -> Lut->Data);
@@ -393,34 +496,86 @@
 } _cmsTransformCollection;
 
 // The linked list head
-static _cmsTransformCollection* TransformCollection = NULL;
+_cmsTransformPluginChunkType _cmsTransformPluginChunk = { NULL };
+
+
+// Duplicates the zone of memory used by the plug-in in the new context
+static
+void DupPluginTransformList(struct _cmsContext_struct* ctx,
+                                               const struct _cmsContext_struct* src)
+{
+   _cmsTransformPluginChunkType newHead = { NULL };
+   _cmsTransformCollection*  entry;
+   _cmsTransformCollection*  Anterior = NULL;
+   _cmsTransformPluginChunkType* head = (_cmsTransformPluginChunkType*) src->chunks[TransformPlugin];
+
+    // Walk the list copying all nodes
+   for (entry = head->TransformCollection;
+        entry != NULL;
+        entry = entry ->Next) {
+
+            _cmsTransformCollection *newEntry = ( _cmsTransformCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsTransformCollection));
+
+            if (newEntry == NULL)
+                return;
+
+            // We want to keep the linked list order, so this is a little bit tricky
+            newEntry -> Next = NULL;
+            if (Anterior)
+                Anterior -> Next = newEntry;
+
+            Anterior = newEntry;
+
+            if (newHead.TransformCollection == NULL)
+                newHead.TransformCollection = newEntry;
+    }
+
+  ctx ->chunks[TransformPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTransformPluginChunkType));
+}
+
+void _cmsAllocTransformPluginChunk(struct _cmsContext_struct* ctx,
+                                        const struct _cmsContext_struct* src)
+{
+    if (src != NULL) {
+
+        // Copy all linked list
+        DupPluginTransformList(ctx, src);
+    }
+    else {
+        static _cmsTransformPluginChunkType TransformPluginChunkType = { NULL };
+        ctx ->chunks[TransformPlugin] = _cmsSubAllocDup(ctx ->MemPool, &TransformPluginChunkType, sizeof(_cmsTransformPluginChunkType));
+    }
+}
+
+
 
 // Register new ways to transform
-cmsBool  _cmsRegisterTransformPlugin(cmsContext id, cmsPluginBase* Data)
+cmsBool  _cmsRegisterTransformPlugin(cmsContext ContextID, cmsPluginBase* Data)
 {
     cmsPluginTransform* Plugin = (cmsPluginTransform*) Data;
     _cmsTransformCollection* fl;
+    _cmsTransformPluginChunkType* ctx = ( _cmsTransformPluginChunkType*) _cmsContextGetClientChunk(ContextID,TransformPlugin);
 
-      if (Data == NULL) {
+    if (Data == NULL) {
 
         // Free the chain. Memory is safely freed at exit
-        TransformCollection = NULL;
+        ctx->TransformCollection = NULL;
         return TRUE;
     }
 
     // Factory callback is required
-   if (Plugin ->Factory == NULL) return FALSE;
+    if (Plugin ->Factory == NULL) return FALSE;
 
 
-    fl = (_cmsTransformCollection*) _cmsPluginMalloc(id, sizeof(_cmsTransformCollection));
+    fl = (_cmsTransformCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsTransformCollection));
     if (fl == NULL) return FALSE;
 
-      // Copy the parameters
+    // Copy the parameters
     fl ->Factory = Plugin ->Factory;
 
     // Keep linked list
-    fl ->Next = TransformCollection;
-    TransformCollection = fl;
+    fl ->Next = ctx->TransformCollection;
+    ctx->TransformCollection = fl;
 
     // All is ok
     return TRUE;
@@ -463,6 +618,7 @@
 _cmsTRANSFORM* AllocEmptyTransform(cmsContext ContextID, cmsPipeline* lut,
                                                cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
 {
+     _cmsTransformPluginChunkType* ctx = ( _cmsTransformPluginChunkType*) _cmsContextGetClientChunk(ContextID, TransformPlugin);
      _cmsTransformCollection* Plugin;
 
     // Allocate needed memory
@@ -473,7 +629,7 @@