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 #13196

Merged
merged 27 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
670b06c
Add support for posix_madvise to Java 21 MMapDirectory
uschindler Mar 21, 2024
1ca24fe
Cleanup and retrieve page size on linux; TODO: the constant seems sys…
uschindler Mar 21, 2024
7cec218
fix bug in warning
uschindler Mar 21, 2024
9a6faca
Remove page size retrieval again and use a safe boundary (2 MiB)
uschindler Mar 21, 2024
4d9a442
fix logger name
uschindler Mar 21, 2024
d311b97
static final MH
ChrisHegarty Mar 21, 2024
5873d7c
Add IOContext.randomAccess (#3)
ChrisHegarty Mar 21, 2024
9ed1da7
Revert "static final MH"
uschindler Mar 22, 2024
242e5e9
Make merge context always win
uschindler Mar 22, 2024
a729f02
Cleanup code and move IOContext mapping to Posix, as the constants we…
uschindler Mar 22, 2024
1e4c5c3
Set randomAccess=true on LOAD. (#4)
jpountz Mar 22, 2024
c9e5ae4
Another run at static final
ChrisHegarty Mar 22, 2024
3dcf7c9
Remove NoopNativeAccess and use an Optional
uschindler Mar 22, 2024
6b19c3a
Merge branch 'dev/posix_madvise' of https://github.com/uschindler/luc…
uschindler Mar 22, 2024
135a8d2
Merge remote-tracking branch 'uwe/dev/posix_madvise' into dev/posix_m…
ChrisHegarty Mar 22, 2024
0d0aeb1
optional
ChrisHegarty Mar 22, 2024
4430a76
javadoc
ChrisHegarty Mar 22, 2024
5c97ca0
remove logger and uppercase MH
ChrisHegarty Mar 22, 2024
20fd5a1
Add getter on MMapDirectory to make madvise status queryable
uschindler Mar 22, 2024
e6485b8
Merge branch 'dev/posix_madvise' of https://github.com/uschindler/luc…
uschindler Mar 22, 2024
cab9014
add minimal test with input IOContext.RANDOM to ensure basic code pat…
ChrisHegarty Mar 22, 2024
1bdad0f
typo
ChrisHegarty Mar 22, 2024
86bfdc6
Add more Javadocs, improve instructions when native access is misisng…
uschindler Mar 22, 2024
648f578
fix typo
uschindler Mar 22, 2024
265c82b
Merge branch 'main' into dev/posix_madvise
ChrisHegarty Mar 23, 2024
94073e1
Merge branch 'main' of https://gitbox.apache.org/repos/asf/lucene int…
uschindler Mar 25, 2024
3919323
add CHANGES.txt
uschindler Mar 25, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,20 @@
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.OptionalInt;
import org.apache.lucene.store.IOContext.Context;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.Unwrappable;

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

private final 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 +53,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 @@ -66,12 +74,22 @@ private final MemorySegment[] map(
Arena arena,
String resourceDescription,
FileChannel fc,
IOContext context,
int chunkSizePower,
boolean preload,
long length)
throws IOException {
if ((length >>> chunkSizePower) >= Integer.MAX_VALUE)
if ((length >>> chunkSizePower) >= Integer.MAX_VALUE) {
throw new IllegalArgumentException("File too big for chunk size: " + resourceDescription);
}

final OptionalInt advice;
if (chunkSizePower < 21) {
// if chunk size is too small (2 MiB), disable madvise support (incorrect alignment):
advice = OptionalInt.empty();
} else {
advice = mapContextToMadvise(context);
}

final long chunkSize = 1L << chunkSizePower;

Expand All @@ -92,10 +110,19 @@ private final MemorySegment[] map(
}
if (preload) {
segment.load();
} else if (segSize > 0L && advice.isPresent()) { // not when preloading!
nativeAccess.madvise(segment, advice.getAsInt());
}
segments[segNr] = segment;
startOffset += segSize;
}
return segments;
}

private OptionalInt mapContextToMadvise(IOContext context) {
if (context.readOnce || context.context == Context.MERGE) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should move the Context.MERGE check to be the first one, because when you merge segments you certainly always want to read the files with sequential advise (although the actual access may be random to a certain degree), because POSIX_MADV_SEQUENTIAL tells in its documentation: "Hence, pages in this region can be aggressively read ahead, and may be freed soon after they are accessed."

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved the check for MERGE context to beginning in 242e5e9. This makes it always win. The reason for that is: We often set MERGE context, but the other settings keep their defaults (like random access). So when merging is first, we always bail out and advise kernel: "may be freed soon after they are accessed"

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when you merge segments you certainly always want to read the files with sequential advise

I've not yet checked, but is Context.MERGE set when merging HNSW graphs? (which would favour random access)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HNSW merging is fine because the first thing that merging does it to write all vectors to a temporary file. And then it builds the graph on top of this temporary file. So it's ok for the input segments to read sequentially, and we could update the merging logic to open this temporary file with IOContext.RANDOM since it's the one that will have a random access pattern.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect. That is exactly what I was looking for.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, so the current code looks fine.

One thing, I am doubting: If we delete a file, will the kernel free all those pages asap? If yes, why do we do the whole "sequentical" handling for merges at all?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may add another abstract method to NativeAcess that is called when we close a file. On Linux we could there give some instructions like "forget everything".

return OptionalInt.of(NativeAccess.POSIX_MADV_SEQUENTIAL);
}
ChrisHegarty marked this conversation as resolved.
Show resolved Hide resolved
return OptionalInt.empty();
}
}
69 changes: 69 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,69 @@
/*
* 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.Locale;
import java.util.logging.Logger;
import org.apache.lucene.util.Constants;

@SuppressWarnings("preview")
abstract class NativeAccess {
private static final Logger LOG = Logger.getLogger(NativeAccess.class.getName());

// these constants were extracted from glibc and macos header files - luckily they are the same:

/** No further special treatment. */
public static final int POSIX_MADV_NORMAL = 0;

/** Expect random page references. */
public static final int POSIX_MADV_RANDOM = 1;

/** Expect sequential page references. */
public static final int POSIX_MADV_SEQUENTIAL = 2;

/** Will need these pages. */
public static final int POSIX_MADV_WILLNEED = 3;

/** Don't need these pages. */
public static final int POSIX_MADV_DONTNEED = 4;

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

/**
* Return the NativeAccess instance for this platform. At moment we only support Linux and MacOS
*/
public static NativeAccess getImplementation() {
if (Constants.LINUX || Constants.MAC_OS_X) {
ChrisHegarty marked this conversation as resolved.
Show resolved Hide resolved
try {
return new PosixNativeAccess();
} catch (UnsupportedOperationException uoe) {
LOG.warning(uoe.getMessage());
} catch (IllegalCallerException ice) {
LOG.warning(
String.format(
Locale.ENGLISH,
"Lucene has no access to native functions (%s). To enable access to native functions, "
+ "pass the following on command line: --enable-native-access=org.apache.lucene.core",
ice.getMessage()));
}
}
return new NoopNativeAccess();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* 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.lang.foreign.MemorySegment;

@SuppressWarnings("preview")
final class NoopNativeAccess extends NativeAccess {

@Override
public void madvise(MemorySegment segment, int advice) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* 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.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
import java.util.logging.Logger;

@SuppressWarnings("preview")
final class PosixNativeAccess extends NativeAccess {

private static final Logger LOG = Logger.getLogger(PosixNativeAccess.class.getName());

private final MethodHandle mh$posix_madvise;
ChrisHegarty marked this conversation as resolved.
Show resolved Hide resolved

public PosixNativeAccess() {
final Linker linker = Linker.nativeLinker();
final SymbolLookup stdlib = linker.defaultLookup();
this.mh$posix_madvise =
findFunction(
linker,
stdlib,
"posix_madvise",
FunctionDescriptor.of(
ValueLayout.JAVA_INT,
ValueLayout.ADDRESS,
ValueLayout.JAVA_LONG,
ValueLayout.JAVA_INT));
LOG.info("posix_madvise() available on this platform");
}

private static MethodHandle findFunction(
Linker linker, SymbolLookup lookup, String name, FunctionDescriptor desc) {
final MemorySegment symbol =
lookup
.find(name)
.orElseThrow(
() ->
new UnsupportedOperationException(
"Platform has no symbol for '" + name + "' in libc."));
return linker.downcallHandle(symbol, desc);
ChrisHegarty marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
public void madvise(MemorySegment segment, int advice) throws IOException {
final int ret;
try {
ret = (int) mh$posix_madvise.invokeExact(segment, segment.byteSize(), advice);
} catch (Throwable th) {
throw new AssertionError(th);
}
if (ret != 0) {
throw new IOException(
String.format(
Locale.ENGLISH,
"Call to posix_madvise with address=0x%08X and byteSize=%d failed with return code %d.",
segment.address(),
segment.byteSize(),
ret));
}
}
}