Skip to content

Commit

Permalink
Add support for posix_madvise to Java 21 MMapDirectory (#13196)
Browse files Browse the repository at this point in the history
  • Loading branch information
uschindler authored Mar 25, 2024
1 parent f4db67f commit a4055da
Show file tree
Hide file tree
Showing 8 changed files with 293 additions and 8 deletions.
2 changes: 2 additions & 0 deletions gradle/testing/defaults-tests.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ allprojects {
if (rootProject.vectorIncubatorJavaVersions.contains(rootProject.runtimeJavaVersion)) {
jvmArgs '--add-modules', 'jdk.incubator.vector'
}

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 @@ -197,6 +197,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
+ "]";
}
}
17 changes: 17 additions & 0 deletions lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@
* of box with some compilation tricks. For more information about the foreign memory API read
* documentation of the {@link java.lang.foreign} package.
*
* <p>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
* blocked on IO. The channel will remain closed and subsequent access to {@link MMapDirectory} will
Expand Down Expand Up @@ -204,6 +211,8 @@ IndexInput openInput(Path path, IOContext context, int chunkSizePower, boolean p

long getDefaultMaxChunkSize();

boolean supportsMadvise();

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

/**
* 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 = lookupProvider();
DEFAULT_MAX_CHUNK_SIZE = PROVIDER.getDefaultMaxChunkSize();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,19 @@
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
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;

MemorySegmentIndexInputProvider() {
this.nativeAccess = NativeAccess.getImplementation();
}

@Override
public IndexInput openInput(Path path, IOContext context, int chunkSizePower, boolean preload)
throws IOException {
Expand All @@ -45,7 +52,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 @@ -62,10 +69,16 @@ public long getDefaultMaxChunkSize() {
return Constants.JRE_IS_64BIT ? (1L << 34) : (1L << 28);
}

@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 @@ -90,8 +103,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

0 comments on commit a4055da

Please sign in to comment.