Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for posix_madvise to Java 21 MMapDirectory (backport) #13213

Merged
merged 3 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions gradle/testing/defaults-tests.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ allprojects {
if (rootProject.vectorIncubatorJavaVersions.contains(rootProject.runtimeJavaVersion)) {
jvmArgs '--add-modules', 'jdk.incubator.vector'
}

if (rootProject.runtimeJavaVersion >= JavaVersion.VERSION_21) {
jvmArgs '--enable-native-access=' + (project.path == ':lucene:core' ? 'ALL-UNNAMED' : 'org.apache.lucene.core')
}

def loggingConfigFile = layout.projectDirectory.file("${resources}/logging.properties")
def tempDir = layout.projectDirectory.dir(testsTmpDir.toString())
Expand Down
5 changes: 5 additions & 0 deletions lucene/CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ New Features
* GITHUB#12915: Add new token filters for Japanese sutegana (捨て仮名). This introduces JapaneseHiraganaUppercaseFilter
and JapaneseKatakanaUppercaseFilter. (Dai Sugimori)

* GITHUB#13196: Add support for posix_madvise to MMapDirectory: If running on Linux/macOS and Java 21
or later, MMapDirectory uses IOContext to pass suitable MADV flags to kernel of operating system.
This may improve paging logic especially when large segments are merged under memory pressure.
(Uwe Schindler, Chris Hegarty, Robert Muir, Adrien Grand)

Improvements
---------------------

Expand Down
37 changes: 30 additions & 7 deletions lucene/core/src/java/org/apache/lucene/store/IOContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,32 @@ public enum Context {
/** This flag indicates that the file will be opened, then fully read sequentially then closed. */
public final boolean readOnce;

/**
* This flag indicates that the file will be accessed randomly. If this flag is set, then readOnce
* will be false.
*/
public final boolean randomAccess;

/**
* This flag is used for files that are a small fraction of the total index size and are expected
* to be heavily accessed in random-access fashion. Some {@link Directory} implementations may
* choose to load such files into physical memory (e.g. Java heap) as a way to provide stronger
* guarantees on query latency.
* guarantees on query latency. If this flag is set, then {@link #randomAccess} will be true.
*/
public final boolean load;

public static final IOContext DEFAULT = new IOContext(Context.DEFAULT);

public static final IOContext READONCE = new IOContext(true, false);
public static final IOContext READONCE = new IOContext(true, false, false);

public static final IOContext READ = new IOContext(false, false, false);

public static final IOContext READ = new IOContext(false, false);
public static final IOContext LOAD = new IOContext(false, true, true);

public static final IOContext LOAD = new IOContext(false, true);
public static final IOContext RANDOM = new IOContext(false, false, true);

public IOContext() {
this(false, false);
this(false, false, false);
}

public IOContext(FlushInfo flushInfo) {
Expand All @@ -72,18 +80,26 @@ public IOContext(FlushInfo flushInfo) {
this.mergeInfo = null;
this.readOnce = false;
this.load = false;
this.randomAccess = false;
this.flushInfo = flushInfo;
}

public IOContext(Context context) {
this(context, null);
}

private IOContext(boolean readOnce, boolean load) {
private IOContext(boolean readOnce, boolean load, boolean randomAccess) {
if (readOnce && randomAccess) {
throw new IllegalArgumentException("cannot be both readOnce and randomAccess");
}
if (load && randomAccess == false) {
throw new IllegalArgumentException("cannot be load but not randomAccess");
}
this.context = Context.READ;
this.mergeInfo = null;
this.readOnce = readOnce;
this.load = load;
this.randomAccess = randomAccess;
this.flushInfo = null;
}

Expand All @@ -98,6 +114,7 @@ private IOContext(Context context, MergeInfo mergeInfo) {
this.context = context;
this.readOnce = false;
this.load = false;
this.randomAccess = false;
this.mergeInfo = mergeInfo;
this.flushInfo = null;
}
Expand All @@ -115,12 +132,13 @@ public IOContext(IOContext ctxt, boolean readOnce) {
this.mergeInfo = ctxt.mergeInfo;
this.flushInfo = ctxt.flushInfo;
this.readOnce = readOnce;
this.randomAccess = ctxt.randomAccess;
this.load = false;
}

@Override
public int hashCode() {
return Objects.hash(context, flushInfo, mergeInfo, readOnce, load);
return Objects.hash(context, flushInfo, mergeInfo, readOnce, load, randomAccess);
}

@Override
Expand All @@ -134,6 +152,7 @@ public boolean equals(Object obj) {
if (!Objects.equals(mergeInfo, other.mergeInfo)) return false;
if (readOnce != other.readOnce) return false;
if (load != other.load) return false;
if (randomAccess != other.randomAccess) return false;
return true;
}

Expand All @@ -147,6 +166,10 @@ public String toString() {
+ flushInfo
+ ", readOnce="
+ readOnce
+ ", load="
+ load
+ ", randomAccess="
+ randomAccess
+ "]";
}
}
23 changes: 20 additions & 3 deletions lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,16 @@
* <li>{@code permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";}
* </ul>
*
* <p>On exactly <b>Java 19 / 20 / 21</b> this class will use the modern {@code MemorySegment} API
* which allows to safely unmap (if you discover any problems with this preview API, you can disable
* it by using system property {@link #ENABLE_MEMORY_SEGMENTS_SYSPROP}).
* <p>Starting with <b>Java 19</b> this class will use the modern {@code MemorySegment} API which
* allows to safely unmap (if you discover any problems with this preview API, you can disable it by
* using system property {@link #ENABLE_MEMORY_SEGMENTS_SYSPROP}).
*
* <p>Starting with <b>Java 21</b> on some platforms like Linux and MacOS X, this class will invoke
* the syscall {@code madvise()} to advise how OS kernel should handle paging after opening a file.
* For this to work, Java code must be able to call native code. If this is not allowed, a warning
* is logged. To enable native access for Lucene in a modularized application, pass {@code
* --enable-native-access=org.apache.lucene.core} to the Java command line. If Lucene is running in
* a classpath-based application, use {@code --enable-native-access=ALL-UNNAMED}.
*
* <p><b>NOTE:</b> Accessing this class either directly or indirectly from a thread while it's
* interrupted can close the underlying channel immediately if at the same time the thread is
Expand Down Expand Up @@ -345,6 +352,8 @@ IndexInput openInput(Path path, IOContext context, int chunkSizePower, boolean p

String getUnmapNotSupportedReason();

boolean supportsMadvise();

default IOException convertMapFailedIOException(
IOException ioe, String resourceDescription, long bufSize) {
final String originalMessage;
Expand Down Expand Up @@ -441,6 +450,14 @@ private static MMapIndexInputProvider lookupProvider() {
return new MappedByteBufferIndexInputProvider();
}

/**
* Returns true, if MMapDirectory uses the platform's {@code madvise()} syscall to advise how OS
* kernel should handle paging after opening a file.
*/
public static boolean supportsMadvise() {
return PROVIDER.supportsMadvise();
}

static {
PROVIDER = doPrivileged(MMapDirectory::lookupProvider);
DEFAULT_MAX_CHUNK_SIZE = PROVIDER.getDefaultMaxChunkSize();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ public String getUnmapNotSupportedReason() {
return unmapNotSupportedReason;
}

@Override
public boolean supportsMadvise() {
return false;
}

/** Maps a file into a set of buffers */
final ByteBuffer[] map(
String resourceDescription, FileChannel fc, int chunkSizePower, boolean preload, long length)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ public String getUnmapNotSupportedReason() {
return null;
}

@Override
public boolean supportsMadvise() {
return false;
}

private final MemorySegment[] map(
MemorySession session,
String resourceDescription,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ public String getUnmapNotSupportedReason() {
return null;
}

@Override
public boolean supportsMadvise() {
return false;
}

private final MemorySegment[] map(
Arena arena,
String resourceDescription,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,18 @@
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
import java.util.logging.Logger;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.Unwrappable;

@SuppressWarnings("preview")
final class MemorySegmentIndexInputProvider implements MMapDirectory.MMapIndexInputProvider {

private final Optional<NativeAccess> nativeAccess;

public MemorySegmentIndexInputProvider() {
this.nativeAccess = NativeAccess.getImplementation();
var log = Logger.getLogger(getClass().getName());
log.info(
"Using MemorySegmentIndexInput with Java 21 or later; to disable start with -D"
Expand All @@ -54,7 +58,7 @@ public IndexInput openInput(Path path, IOContext context, int chunkSizePower, bo
MemorySegmentIndexInput.newInstance(
resourceDescription,
arena,
map(arena, resourceDescription, fc, chunkSizePower, preload, fileSize),
map(arena, resourceDescription, fc, context, chunkSizePower, preload, fileSize),
fileSize,
chunkSizePower);
success = true;
Expand All @@ -81,10 +85,16 @@ public String getUnmapNotSupportedReason() {
return null;
}

@Override
public boolean supportsMadvise() {
return nativeAccess.isPresent();
}

private final MemorySegment[] map(
Arena arena,
String resourceDescription,
FileChannel fc,
IOContext context,
int chunkSizePower,
boolean preload,
long length)
Expand All @@ -109,8 +119,12 @@ private final MemorySegment[] map(
} catch (IOException ioe) {
throw convertMapFailedIOException(ioe, resourceDescription, segSize);
}
// if preload apply it without madvise.
// if chunk size is too small (2 MiB), disable madvise support (incorrect alignment)
if (preload) {
segment.load();
} else if (nativeAccess.isPresent() && chunkSizePower >= 21) {
nativeAccess.get().madvise(segment, context);
}
segments[segNr] = segment;
startOffset += segSize;
Expand Down
39 changes: 39 additions & 0 deletions lucene/core/src/java21/org/apache/lucene/store/NativeAccess.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.store;

import java.io.IOException;
import java.lang.foreign.MemorySegment;
import java.util.Optional;
import org.apache.lucene.util.Constants;

@SuppressWarnings("preview")
abstract class NativeAccess {

/** Invoke the {@code madvise} call for the given {@link MemorySegment}. */
public abstract void madvise(MemorySegment segment, IOContext context) throws IOException;

/**
* Return the NativeAccess instance for this platform. At moment we only support Linux and MacOS
*/
public static Optional<NativeAccess> getImplementation() {
if (Constants.LINUX || Constants.MAC_OS_X) {
return PosixNativeAccess.getInstance();
}
return Optional.empty();
}
}
Loading
Loading