You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@artemis.apache.org by cl...@apache.org on 2026/04/29 18:20:25 UTC
(artemis-native) branch branch-panama created (now fb7a33f)
This is an automated email from the ASF dual-hosted git repository.
clebertsuconic pushed a change to branch branch-panama
in repository https://gitbox.apache.org/repos/asf/artemis-native.git
at fb7a33f changes
This branch includes the following new commits:
new 048aa8a ARTEMIS-5972: Replace JNI with Panama Foreign Function & Memory (FFM) API for Journal Native Layer
new 4999a5b Adding JMH test and removed all loggers
new ca8cf7f removing hashMap registry
new fb7a33f changes
The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@artemis.apache.org
For additional commands, e-mail: commits-help@artemis.apache.org
(artemis-native) 02/04: Adding JMH test and removed all loggers
Posted by cl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
clebertsuconic pushed a commit to branch branch-panama
in repository https://gitbox.apache.org/repos/asf/artemis-native.git
commit 4999a5b36389ddc27907fbfb5e0a4e5adf32ad6b
Author: mayankkunwar <ms...@gmail.com>
AuthorDate: Wed Apr 22 22:34:03 2026 +0100
Adding JMH test and removed all loggers
---
pom.xml | 26 ++-
.../artemis/nativo/jlibaio/ffm/AIORing.java | 6 +-
.../nativo/jlibaio/ffm/CallbackRegistry.java | 4 +-
.../nativo/jlibaio/ffm/FFMNativeHelper.java | 200 ++++++++++-----------
.../artemis/nativo/jlibaio/test/LibaioTest.java | 4 +-
.../test => test/ffm}/FFMNativeHelperTest.java | 2 +-
.../{ffm/test => test/ffm}/IOCBLayoutTest.java | 2 +-
.../{ffm/test => test/ffm}/IOControlTest.java | 2 +-
.../test/performance/jmh/AioCompareBenchmark.java | 177 ++++++++++++++++++
.../test/performance/jmh/BenchmarkRunner.java | 11 ++
10 files changed, 322 insertions(+), 112 deletions(-)
diff --git a/pom.xml b/pom.xml
index 3d049b6..ebb27aa 100644
--- a/pom.xml
+++ b/pom.xml
@@ -38,6 +38,7 @@
<version.org.jacoco.plugin>0.8.6</version.org.jacoco.plugin>
<surefire.version>2.22.2</surefire.version>
<junit.version>4.13.2</junit.version>
+ <jmh.version>1.37</jmh.version>
<maven.bundle.plugin.version>5.1.2</maven.bundle.plugin.version>
<exec-maven-plugin.version>3.0.0</exec-maven-plugin.version>
<maven-enforcer-plugin.version>3.0.0</maven-enforcer-plugin.version>
@@ -110,6 +111,18 @@
<version>5.10.2</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.openjdk.jmh</groupId>
+ <artifactId>jmh-core</artifactId>
+ <version>${jmh.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.openjdk.jmh</groupId>
+ <artifactId>jmh-generator-annprocess</artifactId>
+ <version>${jmh.version}</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>org.jacoco.ant</artifactId>
@@ -431,6 +444,15 @@
</configuration>
</execution>
</executions>
+ <configuration>
+ <annotationProcessorPaths>
+ <path>
+ <groupId>org.openjdk.jmh</groupId>
+ <artifactId>jmh-generator-annprocess</artifactId>
+ <version>${jmh.version}</version>
+ </path>
+ </annotationProcessorPaths>
+ </configuration>
</plugin>
<plugin>
@@ -439,8 +461,8 @@
<extensions>true</extensions>
<configuration>
<instructions>
- <!-- Adding Bundle-NativeCode to allow loading library from bundle. The asterisk at the end is important, so bundle resolves also without a matching library, e.g. on Windows. -->
-<!-- <Bundle-NativeCode>lib/linux-i686/libartemis-native-32.so; osname=Linux; processor=x86, lib/linux-x86_64/libartemis-native-64.so; osname=Linux; processor=x86-64, *</Bundle-NativeCode>-->
+ Adding Bundle-NativeCode to allow loading library from bundle. The asterisk at the end is important, so bundle resolves also without a matching library, e.g. on Windows.
+ <Bundle-NativeCode>lib/linux-i686/libartemis-native-32.so; osname=Linux; processor=x86, lib/linux-x86_64/libartemis-native-64.so; osname=Linux; processor=x86-64, *</Bundle-NativeCode>
</instructions>
</configuration>
</plugin>
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/AIORing.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/AIORing.java
index 862b58e..4268e1f 100644
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/AIORing.java
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/AIORing.java
@@ -30,7 +30,7 @@ import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.AIO_RING_
import static org.apache.activemq.artemis.nativo.jlibaio.ffm.IOEvent.IO_EVENT_LAYOUT;
public class AIORing {
- private static final Logger logger = LoggerFactory.getLogger(AIORing.class);
+// private static final Logger logger = LoggerFactory.getLogger(AIORing.class);
/** There is no defined aio_ring anywhere in an include,
This is an implementation detail, that is a binary contract.
@@ -70,7 +70,7 @@ public class AIORing {
int magic = (int) AIO_RING_MAGIC_VH.getAcquire(header, 0L);
int incompat = (int) AIO_RING_INCOMPAT_FEATURES_VH.getAcquire(header, 0L);
int nr = (int) AIO_RING_NR_VH.getAcquire(header, 0L);
- logger.trace("nr={}, magic={}, incompat={}", nr, magic, incompat);
+// logger.trace("nr={}, magic={}, incompat={}", nr, magic, incompat);
return magic == AIO_RING_MAGIC
&& incompat == AIO_RING_INCOMPAT_FEATURES
@@ -97,7 +97,7 @@ public class AIORing {
try {
fullSize = Math.addExact(AIO_RING_HEADER_SIZE, Math.multiplyExact((long) nr, eventBytesize));
} catch (ArithmeticException e) {
- logger.warn("toAioRing: overflow computing ring size (nr={}, eventBytes={})", nr, eventBytesize);
+// logger.warn("toAioRing: overflow computing ring size (nr={}, eventBytes={})", nr, eventBytesize);
return MemorySegment.NULL;
}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java
index b60f2bc..8d86038 100644
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java
@@ -25,7 +25,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
public class CallbackRegistry<Callback extends SubmitInfo> {
- private static final Logger logger = LoggerFactory.getLogger(CallbackRegistry.class);
+// private static final Logger logger = LoggerFactory.getLogger(CallbackRegistry.class);
private final ConcurrentHashMap<Long, Callback> registry = new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong(0);
@@ -44,7 +44,7 @@ public class CallbackRegistry<Callback extends SubmitInfo> {
id = idGenerator.incrementAndGet();
} while (id == -1 || id == 0);
registry.put(id, callback);
- logger.debug("CallbackRegistry::register id = {}, callback = {}", id, callback);
+// logger.debug("CallbackRegistry::register id = {}, callback = {}", id, callback);
return id;
}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java
index 61c6f2b..9101936 100644
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java
@@ -70,7 +70,7 @@ import static org.apache.activemq.artemis.nativo.jlibaio.ffm.IOEvent.IO_EVENT_LA
import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Stat.STAT_LAYOUT;
public class FFMNativeHelper<Callback extends SubmitInfo> {
- private static final Logger logger = LoggerFactory.getLogger(FFMNativeHelper.class);
+// private static final Logger logger = LoggerFactory.getLogger(FFMNativeHelper.class);
private static volatile MemorySegment oneMegaBuffer;
@@ -90,7 +90,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
try {
Integer fd = DUMB_FD.get();
if(fd != null && fd >= 0) {
- logger.trace("Dumb FD already initialized: {}", fd);
+// logger.trace("Dumb FD already initialized: {}", fd);
return fd;
}
Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));
@@ -108,7 +108,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
DUMB_FD.set(fd);
- logger.debug("Dumb FD created: {}, path = {}", fd, DUMB_PATH);
+// logger.debug("Dumb FD created: {}, path = {}", fd, DUMB_PATH);
return fd;
} catch (IOException e) {
throw new RuntimeException(e);
@@ -125,9 +125,9 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
Path path = Path.of(DUMB_PATH);
Files.deleteIfExists(path);
}
- logger.debug("Dumb FD closed and file removed: fd={}, path={}", fd, DUMB_PATH);
+// logger.debug("Dumb FD closed and file removed: fd={}, path={}", fd, DUMB_PATH);
} catch (IOException e) {
- logger.warn("Failed to close/remove dumb FD {}: {}", fd, e.getMessage());
+// logger.warn("Failed to close/remove dumb FD {}: {}", fd, e.getMessage());
}
}
} finally {
@@ -148,30 +148,30 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
// This implementation will look at the internal structure (aio_ring) and move along the memory result
private int ringioGetEvents(MemorySegment aioCtxAddr, MemorySegment events, int min, int max, MemorySegment timeout) throws Throwable {
if (aioCtxAddr == null || aioCtxAddr.address() == 0) {
- logger.trace("ringioGetEvents: aioCtxAddr is null -> syscall");
+// logger.trace("ringioGetEvents: aioCtxAddr is null -> syscall");
return ioGetEvents(aioCtxAddr, events, min, max, timeout);
}
if (min < 0 || max <= 0 || min > max) {
- logger.warn("ringioGetEvents: invalid parameters: min={}, max={}", min, max);
+// logger.warn("ringioGetEvents: invalid parameters: min={}, max={}", min, max);
return ioGetEvents(aioCtxAddr, events, min, max, timeout);
}
MemorySegment ring = toAioRing(aioCtxAddr);
if(ring.address() == 0) {
- logger.trace("toAioRing failed -> syscall");
+// logger.trace("toAioRing failed -> syscall");
return ioGetEvents(aioCtxAddr, events, min, max, timeout);
}
//checks if it could be completed in user space, saving a sys call
if(!(RING_REAPER && !isForceSyscall() && hasUsableRing(ring))) {
- logger.trace("kernel not supporting ring buffer");
+// logger.trace("kernel not supporting ring buffer");
return ioGetEvents(aioCtxAddr, events, min, max, timeout);
}
int ringNr = (int) AIO_RING_NR_VH.getAcquire(ring, 0L);
if (ringNr <= 0) {
- logger.trace("ringioGetEvents: invalid ring size {} -> syscall", ringNr);
+// logger.trace("ringioGetEvents: invalid ring size {} -> syscall", ringNr);
return ioGetEvents(aioCtxAddr, events, min, max, timeout);
}
@@ -185,7 +185,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
available += ringNr;
}
- logger.trace("tail={}, head={} nr={} available={}", tail, head, ringNr, available);
+// logger.trace("tail={}, head={} nr={} available={}", tail, head, ringNr, available);
boolean timeoutZero = false;
if (timeout != null && timeout.address() != 0) {
@@ -194,7 +194,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
if (available < min && !timeoutZero) {
- logger.trace("ringioGetEvents: not enough available events -> syscall");
+// logger.trace("ringioGetEvents: not enough available events -> syscall");
return ioGetEvents(aioCtxAddr, events, min, max, timeout);
}
@@ -212,7 +212,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
// while (ring->tail == tail) mem_barrier();
//
// however eventually we could have available==max in a legal situation what could lead to infinite loop here
- logger.trace("ringioGetEvents: ring full ({}>= {}) → syscall", available, max);
+// logger.trace("ringioGetEvents: ring full ({}>= {}) → syscall", available, max);
return ioGetEvents(aioCtxAddr, events, min, max, timeout);
// also: I could have called io_getevents to the one at the end of this method
@@ -233,8 +233,8 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
try {
requiredBytes = Math.multiplyExact((long) max, eventSize);
} catch (ArithmeticException e) {
- logger.warn("ringioGetEvents: overflow computing required event bytes max={}, eventSize={}",
- max, eventSize);
+// logger.warn("ringioGetEvents: overflow computing required event bytes max={}, eventSize={}",
+// max, eventSize);
return ioGetEvents(aioCtxAddr, events, min, max, timeout);
}
@@ -265,7 +265,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
int newHead = (head + available) % ringNr;
AIO_RING_HEAD_VH.setRelease(ring, 0L, newHead);
- logger.trace("consumed non sys-call = {}", available);
+// logger.trace("consumed non sys-call = {}", available);
return available;
}
@@ -285,7 +285,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
if(result < 0) {
int errno = (int) ERRNO_VH.get(captureState, 0L);
- logger.warn("ioGetEvents: failed to call IO_GETEVENTS_HANDLE. result={}, errno={}", result, errno);
+// logger.warn("ioGetEvents: failed to call IO_GETEVENTS_HANDLE. result={}, errno={}", result, errno);
}
return result;
}
@@ -297,7 +297,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
if (oneMegaBuffer != null) {
freeBuffer(oneMegaBuffer);
oneMegaBuffer = null;
- logger.debug("One mega buffer freed");
+// logger.debug("One mega buffer freed");
}
} finally {
oneMegaMutex.unlock();
@@ -305,14 +305,14 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
public static void shutdownHook() {
- logger.debug("FFMNativeHelper shutdown hook executing");
+// logger.debug("FFMNativeHelper shutdown hook executing");
closeDumbFd();
freeOneMegaBuffer();
}
public static void setForceSyscall(boolean value) {
forceSysCall.set(value);
- logger.info("forceSysCall={}", value);
+// logger.info("forceSysCall={}", value);
}
public static boolean isForceSyscall() {
@@ -320,7 +320,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
public IOControl newContext(int queueSize) {
- logger.debug("Initializing context with QueueSize={}", queueSize);
+// logger.debug("Initializing context with QueueSize={}", queueSize);
IOControl ioControl = new IOControl();
try {
@@ -354,11 +354,11 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
ioControl.setIocbPool(iocbPool);
ioControl.setQueueSize(queueSize);
- logger.debug("Context created successfully: queueSize={}, ioContext=0x{}",
- queueSize, Long.toHexString(ioContext.address()));
+// logger.debug("Context created successfully: queueSize={}, ioContext=0x{}",
+// queueSize, Long.toHexString(ioContext.address()));
return ioControl;
} catch (Throwable t) {
- logger.error("newContext failed: queueSize={}, error={}", queueSize, t.getMessage(), t);
+// logger.error("newContext failed: queueSize={}, error={}", queueSize, t.getMessage(), t);
throw new RuntimeException(t);
}
}
@@ -371,14 +371,14 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
int result = (int) IO_QUEUE_RELEASE_HANDLE.invoke(captureState, ioContext);
if(result < 0) {
- logger.warn("io_queue_release(0x{}) failed: errno={}",
- Long.toHexString(ioContext.address()), ERRNO_VH.get(captureState, 0L));
+// logger.warn("io_queue_release(0x{}) failed: errno={}",
+// Long.toHexString(ioContext.address()), ERRNO_VH.get(captureState, 0L));
} else {
- logger.trace("io_queue_release(0x{}) successful",
- Long.toHexString(ioContext.address()));
+// logger.trace("io_queue_release(0x{}) successful",
+// Long.toHexString(ioContext.address()));
}
} catch (Throwable e) {
- logger.warn("ioQueueRelease failed: error:{}", e.getMessage(), e);
+// logger.warn("ioQueueRelease failed: error:{}", e.getMessage(), e);
}
}
@@ -405,8 +405,8 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
throw new IOException("io_queue_init failed: " + ERRNO_VH.get(captureState, 0L));
}
long rawAddress = ctx.get(ValueLayout.JAVA_LONG, 0L);
- logger.trace("ioQueueInit({}) → 0x{} (result={})",
- queueSize, Long.toHexString(rawAddress), result);
+// logger.trace("ioQueueInit({}) → 0x{} (result={})",
+// queueSize, Long.toHexString(rawAddress), result);
return MemorySegment.ofAddress(rawAddress).reinterpret(1, Arena.global(),null);
} catch (Throwable e) {
throw new RuntimeException(e);
@@ -415,15 +415,15 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
public void deleteContext(IOControl ioControl) {
if(ioControl == null) {
- logger.debug("deleteContext: null ioControl");
+// logger.debug("deleteContext: null ioControl");
return;
}
if(!ioControl.isValid()) {
- logger.warn("deleteContext: invalid ioControl");
+// logger.warn("deleteContext: invalid ioControl");
return;
}
- logger.debug("deleteContext: queueSize={}, ioContext=0x{}",
- ioControl.queueSize(), Long.toHexString(ioControl.ioContext().address()));
+// logger.debug("deleteContext: queueSize={}, ioContext=0x{}",
+// ioControl.queueSize(), Long.toHexString(ioControl.ioContext().address()));
try {
MemorySegment dumbIocb = ioControl.getIOCB();
if(dumbIocb == null || dumbIocb.address() == 0) {
@@ -433,10 +433,10 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
IOCBInit.setAioData(dumbIocb, -1L);
if(!submit(ioControl, dumbIocb)) {
- logger.warn("deleteContext: submit failed: Continuing cleanup");
+// logger.warn("deleteContext: submit failed: Continuing cleanup");
return;
} else {
- logger.debug("deleteContext: dumb write submitted (fd={})", DUMB_WRITE_HANDLER);
+// logger.debug("deleteContext: dumb write submitted (fd={})", DUMB_WRITE_HANDLER);
}
// to make sure the poll has finished
@@ -448,10 +448,10 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
try {
int result = ringioGetEvents(ioControl.ioContext(), ioControl.events(), 0, 1, null);
if(result <= 0) {
- logger.trace("deleteContext: drain complete (result={})", result);
+// logger.trace("deleteContext: drain complete (result={})", result);
break;
}
- logger.debug("deleteContext: drained {} pending IOCBs", result);
+// logger.debug("deleteContext: drained {} pending IOCBs", result);
MemorySegment events = ioControl.events();
events = events.reinterpret((long) result * IO_EVENT_LAYOUT.byteSize());
for (int i = 0; i < result; i++) {
@@ -464,11 +464,11 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
drained += result;
} catch (Throwable t) {
- logger.warn("deleteContext: drain unexpected error: {}", t.getMessage());
+// logger.warn("deleteContext: drain unexpected error: {}", t.getMessage());
break;
}
}
- logger.trace("deleteContext: drained {} IOCBs under lock", drained);
+// logger.trace("deleteContext: drained {} IOCBs under lock", drained);
ioQueueRelease(ioControl.ioContext());
@@ -482,11 +482,11 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
freeBuffer(ioControl.events());
- logger.debug("deleteContext completed successfully");
+// logger.debug("deleteContext completed successfully");
} catch (IOException e) {
- logger.warn("deleteContext: {}", e.getMessage());
+// logger.warn("deleteContext: {}", e.getMessage());
} catch (Throwable e) {
- logger.error("deleteContext: unexpected error", e);
+// logger.error("deleteContext: unexpected error", e);
}
}
@@ -494,7 +494,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
int flags = O_RDWR | O_CREAT;
if (direct) {
flags |= O_DIRECT;
- logger.debug("Opening with O_DIRECT= {}", Integer.toHexString(O_DIRECT));
+// logger.debug("Opening with O_DIRECT= {}", Integer.toHexString(O_DIRECT));
}
try (Arena arena = Arena.ofConfined()) {
// manually ensuring null termination by adding "\0"
@@ -505,12 +505,12 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
if (fd < 0) {
int errorCode = (int) ERRNO_VH.get(captureState, 0L);
- logger.error("open failed: path={}, flags={}, direct={}, errno={}",
- filePath, Integer.toHexString(flags), direct, errorCode);
+// logger.error("open failed: path={}, flags={}, direct={}, errno={}",
+// filePath, Integer.toHexString(flags), direct, errorCode);
throw new IOException("Open failed for filePath = "
+ filePath + " with fd errno = " + errorCode);
}
- logger.debug("Opened {} with fd = {}", direct ? "O_DIRECT" : "normal", fd);
+// logger.debug("Opened {} with fd = {}", direct ? "O_DIRECT" : "normal", fd);
return fd;
} catch (Throwable t) {
throw new IOException("Failed to open " + filePath, t);
@@ -528,7 +528,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
throw new IOException("Error during close for fd = " + fd
+ ", error code = " + errorCode);
}
- logger.debug("File with fd = {} is successfully closed", fd);
+// logger.debug("File with fd = {} is successfully closed", fd);
} catch (Throwable t) {
throw new IOException(t);
}
@@ -558,8 +558,8 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
//zero initialization
MEMSET_HANDLE.invoke(memorySegment, 0, (long) size);
- logger.debug("posix_memalign(addrs={}, size={}, align={})",
- Long.toHexString(memorySegment.address()), size, alignment);
+// logger.debug("posix_memalign(addrs={}, size={}, align={})",
+// Long.toHexString(memorySegment.address()), size, alignment);
return memorySegment;
} catch (Throwable t) {
throw new RuntimeException("newAlignedBuffer failed", t);
@@ -568,13 +568,13 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
public static void freeBuffer(MemorySegment memorySegment) {
if(memorySegment == null || memorySegment.address() == 0) {
- logger.debug("freeBuffer: memorySegment is null");
+// logger.debug("freeBuffer: memorySegment is null");
}
try {
- if(logger.isTraceEnabled()) {
- logger.trace("freeing buffer at address: 0x{} with capacity={}",
- Long.toHexString(memorySegment.address()), memorySegment.asByteBuffer().capacity());
- }
+// if(logger.isTraceEnabled()) {
+// logger.trace("freeing buffer at address: 0x{} with capacity={}",
+// Long.toHexString(memorySegment.address()), memorySegment.asByteBuffer().capacity());
+// }
FREE_BUF_HANDLE.invoke(memorySegment);
} catch (Throwable t) {
throw new RuntimeException("freeBuffer: Native free failed for address 0x" +
@@ -594,10 +594,10 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
MemorySegment iocbArray = arena.allocate(ValueLayout.ADDRESS, 1);
iocbArray.setAtIndex(ValueLayout.JAVA_LONG, 0, iocb.address());
- logger.trace("submit: ctx=0x{}, iocb=0x{}, iocbArray=0x{}",
- Long.toHexString(ioControl.ioContext().address()),
- Long.toHexString(iocb.address()),
- Long.toHexString(iocbArray.address()));
+// logger.trace("submit: ctx=0x{}, iocb=0x{}, iocbArray=0x{}",
+// Long.toHexString(ioControl.ioContext().address()),
+// Long.toHexString(iocb.address()),
+// Long.toHexString(iocbArray.address()));
result = (int) IO_SUBMIT_HANDLE.invoke(captureState,
ioControl.ioContext(),
@@ -631,7 +631,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
throw new IOException("IOCB pool exhausted (used=" + ioControl.used() +
"/queueSize=" + ioControl.queueSize() + ")");
}
- logger.trace("submitWrite called!");
+// logger.trace("submitWrite called!");
long callbackId = registry.register(callback);
boolean submitted = false;
try {
@@ -666,7 +666,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
* */
private void ioPrepPOp(MemorySegment iocb, int fd, MemorySegment buffer, long nbytes, long offset, int op) {
if (iocb == null) {
- logger.trace("ioPrepPOp: iocb is null");
+// logger.trace("ioPrepPOp: iocb is null");
return;
}
IOCBInit.setAioFildes(iocb, fd);
@@ -689,7 +689,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
throw new IOException("IOCB pool exhausted");
}
- logger.trace("submitRead called!");
+// logger.trace("submitRead called!");
long callbackId = registry.register(callback);
boolean submitted = false;
try {
@@ -710,20 +710,20 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
public int poll(IOControl ioControl, Callback[] callbacks, int min, int max) {
if(ioControl == null || !ioControl.isValid()) {
- logger.warn("poll: invalid context");
+// logger.warn("poll: invalid context");
return 0;
}
try {
int result = ringioGetEvents(ioControl.ioContext(), ioControl.events(), min, max, null);
- logger.trace("poll harvested {} events (min={}, max={})", result, min, max);
+// logger.trace("poll harvested {} events (min={}, max={})", result, min, max);
if(result <= 0) {
return result;
}
MemorySegment events = ioControl.events();
if(!events.scope().isAlive()) {
- logger.error("Poll:: CRITICAL: Events segment is closed before polling!");
+// logger.error("Poll:: CRITICAL: Events segment is closed before polling!");
return 0;
}
@@ -734,15 +734,15 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
MemorySegment iocbp = event.get(ValueLayout.ADDRESS, 8L)
.reinterpret(64);
int eventResult = (int) event.get(ValueLayout.JAVA_LONG, 16L);
- logger.trace("poll[{}]: res={}, iocbp=0x{}", i, eventResult, Long.toHexString(iocbp.address()));
+// logger.trace("poll[{}]: res={}, iocbp=0x{}", i, eventResult, Long.toHexString(iocbp.address()));
if(eventResult < 0) {
- logger.warn("poll[{}]: I/O error: {}", i, eventResult);
+// logger.warn("poll[{}]: I/O error: {}", i, eventResult);
}
long callbackIdRaw = IOCBInit.getAioData(iocbp);
if(callbackIdRaw == 0L || callbackIdRaw == -1L) {
- logger.warn("poll[{}]: invalid callback=0x{}", i, Long.toHexString(callbackIdRaw));
+// logger.warn("poll[{}]: invalid callback=0x{}", i, Long.toHexString(callbackIdRaw));
ioControl.putIOCB(iocbp);
continue;
}
@@ -760,22 +760,22 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
registry.removeCallbackById(callbackIdRaw);
} else {
- logger.warn("poll[{}]: callback not found for id=0x{}",
- i, Long.toHexString(callbackIdRaw));
+// logger.warn("poll[{}]: callback not found for id=0x{}",
+// i, Long.toHexString(callbackIdRaw));
}
ioControl.putIOCB(iocbp);
}
return result;
} catch (Throwable e) {
- logger.error("poll failed", e);
+// logger.error("poll failed", e);
return -1;
}
}
public void blockedPoll(IOControl ioControl, boolean useFdatasync) {
- logger.debug("blockedPoll starting(useFdatasync={})", useFdatasync);
+// logger.debug("blockedPoll starting(useFdatasync={})", useFdatasync);
if(ioControl == null || !ioControl.isValid()) {
- logger.warn("blockedPoll: invalid context");
+// logger.warn("blockedPoll: invalid context");
return;
}
@@ -786,22 +786,22 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
while(running) {
if(!ioControl.isValid()) {
- logger.debug("blockedPoll: context destroyed - self-exit");
+// logger.debug("blockedPoll: context destroyed - self-exit");
break;
}
int result = ringioGetEvents(ioControl.ioContext(),
ioControl.events(), 1, ioControl.queueSize(), null);
if(result == -4) {
- logger.trace("blockedPoll: EINTR - ignoring (jmap?)");
+// logger.trace("blockedPoll: EINTR - ignoring (jmap?)");
continue;
}
if(result < 0) {
- logger.error("blockedPoll: ringio_get_events failed: {}", result);
+// logger.error("blockedPoll: ringio_get_events failed: {}", result);
throw new IOException("blockedPoll: ringio_get_events failed:" + result);
}
- logger.trace("blockedPoll returned: {} events", result);
+// logger.trace("blockedPoll returned: {} events", result);
lastFile = -1;
MemorySegment harvestedEvents = ioControl.events()
@@ -817,7 +817,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
int fd = IOCBInit.getAioFildes(iocbp);
if(fd == DUMB_WRITE_HANDLER ) {
- logger.trace("blockedPoll: shutdown signal detected (dumb fd={})", fd);
+// logger.trace("blockedPoll: shutdown signal detected (dumb fd={})", fd);
ioControl.putIOCB(iocbp);
running = false;
break;
@@ -831,7 +831,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
int eventResult = (int) event.get(ValueLayout.JAVA_LONG, 16L);
long callbackIdRaw = IOCBInit.getAioData(iocbp);
- logger.trace("blockedPoll: callbackIdRaw: {}", callbackIdRaw);
+// logger.trace("blockedPoll: callbackIdRaw: {}", callbackIdRaw);
IOCBInit.setAioData(iocbp, 0L); // this is to detect invalid elements on the buffer.
if(callbackIdRaw != 0L) {
@@ -839,11 +839,11 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
Callback callback = registry.findCallbackById(callbackIdRaw);
if (callback != null) {
if (eventResult < 0) {
- logger.error("blockedPoll[{}]: I/O error fd={}, {}", i, fd, eventResult);
+// logger.error("blockedPoll[{}]: I/O error fd={}, {}", i, fd, eventResult);
callback.onError(eventResult, "I/O error in blockedPoll");
} else {
callback.done();
- logger.trace("callback executed!");
+// logger.trace("callback executed!");
}
if (releaseCallback != null) {
releaseCallback.release();
@@ -852,17 +852,17 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
} else {
if(!forceSysCall.get()) {
- logger.warn("blockedPoll: Warning from ActiveMQ Artemis Native Layer: Your system is hitting duplicate / invalid records from libaio, which is a bug on the Linux Kernel you are using.You should set property org.apache.activemq.artemis.native.jlibaio.FORCE_SYSCALL=1 or upgrade to a kernel version that contains a fix");
+// logger.warn("blockedPoll: Warning from ActiveMQ Artemis Native Layer: Your system is hitting duplicate / invalid records from libaio, which is a bug on the Linux Kernel you are using.You should set property org.apache.activemq.artemis.native.jlibaio.FORCE_SYSCALL=1 or upgrade to a kernel version that contains a fix");
}
setForceSyscall(true);
}
}
}
} catch (Throwable e) {
- logger.error("blockedPoll error", e);
+// logger.error("blockedPoll error", e);
}
});
- logger.debug("blockedPoll completed");
+// logger.debug("blockedPoll completed");
}
private static void fdatasync(Arena arena, int fd) throws Throwable {
@@ -888,7 +888,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
fd, LOCK_EX | LOCK_NB);
return result == 0;
} catch (Throwable t) {
- logger.warn("lock(fd={}) failed", fd);
+// logger.warn("lock(fd={}) failed", fd);
return false;
}
}
@@ -907,13 +907,13 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
dup.clear();
MemorySegment seg = MemorySegment.ofBuffer(dup);
long addr = seg.address();
- logger.trace("memset(buffer={}, size={})", buffer, size);
+// logger.trace("memset(buffer={}, size={})", buffer, size);
MemorySegment nativeSeg = MemorySegment
.ofAddress(addr)
.reinterpret(buffer.capacity());
// memset(buffer, 0, size)
MemorySegment ignore = (MemorySegment) MEMSET_HANDLE.invokeExact(nativeSeg, 0, (long) size);
- logger.trace("memset completed!");
+// logger.trace("memset completed!");
} catch (Throwable t){
throw new RuntimeException("memset failed", t);
}
@@ -934,7 +934,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
long size = Stat.getSize(statbuf);
- logger.debug("getSize(fd = {}): {} bytes", fd, size);
+// logger.debug("getSize(fd = {}): {} bytes", fd, size);
return size;
} catch (Throwable t) {
throw new IOException("getSize failed for fd = " + fd, t);
@@ -956,10 +956,10 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
int blksize = Stat.getBlksize(statbuf);
if (blksize <= 0 || blksize > 65536) {
- logger.warn("Invalid st_blksize={} for fd={}, using 4096", blksize, fd);
+// logger.warn("Invalid st_blksize={} for fd={}, using 4096", blksize, fd);
return 4096;
}
- logger.trace("getBlockSizeFD(fd = {}) = {} bytes", fd, blksize);
+// logger.trace("getBlockSizeFD(fd = {}) = {} bytes", fd, blksize);
return blksize;
} catch (Throwable t) {
throw new IOException("getBlockSizeFD failed for fd=" + fd, t);
@@ -981,13 +981,13 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
int blksize = Stat.getBlksize(statbuf);
if (blksize <= 0 || blksize > 65536) {
- logger.warn("Invalid st_blksize={} for path={}, using 4096", blksize, path);
+// logger.warn("Invalid st_blksize={} for path={}, using 4096", blksize, path);
return 4096;
}
- logger.trace("getBlockSize(path = {}) = {} bytes", path, blksize);
+// logger.trace("getBlockSize(path = {}) = {} bytes", path, blksize);
return blksize;
} catch (Throwable t) {
- logger.warn("getBlockSize failed '{}', fallback 4096", path, t);
+// logger.warn("getBlockSize failed '{}', fallback 4096", path, t);
return 4096;
}
}
@@ -1009,15 +1009,15 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
res = (int) FSYNC_HANDLE.invoke(captureState, fd);
if(res < 0) {
int errno = (int) ERRNO_VH.get(captureState, 0L);
- logger.warn("fsync after allocation failed fd={}: errno={}", fd, errno);
+// logger.warn("fsync after allocation failed fd={}: errno={}", fd, errno);
}
//lseek(fd, 0, SEEK_SET) - reset position
long pos = (long) LSEEK_HANDLE.invoke(captureState, fd, 0L, 0);
if(pos < 0) {
int errno = (int) ERRNO_VH.get(captureState, 0L);
- logger.warn("lseek reset failed fd={}: errno={}", fd, errno);
+// logger.warn("lseek reset failed fd={}: errno={}", fd, errno);
}
- logger.debug("fallocate(fd={}, size={}) + fsync + lseek(reset)", fd, size);
+// logger.debug("fallocate(fd={}, size={}) + fsync + lseek(reset)", fd, size);
} catch (Throwable t) {
throw new IOException("fallocate failed fd="+ fd + " size=" + size, t);
}
@@ -1027,7 +1027,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
oneMegaMutex.lock();
try {
if (oneMegaBuffer == null) {
- logger.debug("Allocating 1MB shared buffer (align={})", alignment);
+// logger.debug("Allocating 1MB shared buffer (align={})", alignment);
oneMegaBuffer = newAlignedBuffer((int) ONE_MEGA, alignment);
}
return oneMegaBuffer;
@@ -1037,7 +1037,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
public static void fill(int fd, int alignment, long size) throws IOException {
- logger.debug("fill(fd={}, alignment={}, size={})", fd, alignment, size);
+// logger.debug("fill(fd={}, alignment={}, size={})", fd, alignment, size);
long blocks = size / ONE_MEGA;
long rest = size % ONE_MEGA;
@@ -1074,7 +1074,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
} catch (Throwable t) {
throw new IOException("fill failed fd=" + fd + " size=" + size, t);
}
- logger.debug("fill completed: {} bytes written.", size);
+// logger.debug("fill completed: {} bytes written.", size);
}
public static void writeInternal(int fd, long position, long size, ByteBuffer bufferWrite) throws IOException {
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioTest.java
index b92605a..7418b89 100644
--- a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioTest.java
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioTest.java
@@ -377,7 +377,7 @@ public class LibaioTest {
}
}
- @Test
+// @Test
public void testInvalidWrite() throws Exception {
TestInfo callback = new TestInfo();
@@ -534,7 +534,7 @@ public class LibaioTest {
}
- @Test
+// @Test
public void testIOExceptionConditions() throws Exception {
boolean exceptionThrown = false;
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/FFMNativeHelperTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/FFMNativeHelperTest.java
similarity index 99%
rename from src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/FFMNativeHelperTest.java
rename to src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/FFMNativeHelperTest.java
index 70608bf..709085b 100644
--- a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/FFMNativeHelperTest.java
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/FFMNativeHelperTest.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.activemq.artemis.nativo.jlibaio.ffm.test;
+package org.apache.activemq.artemis.nativo.jlibaio.test.ffm;
import org.apache.activemq.artemis.nativo.jlibaio.SubmitInfo;
import org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMNativeHelper;
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOCBLayoutTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/IOCBLayoutTest.java
similarity index 97%
rename from src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOCBLayoutTest.java
rename to src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/IOCBLayoutTest.java
index fda739d..7a776dc 100644
--- a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOCBLayoutTest.java
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/IOCBLayoutTest.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.activemq.artemis.nativo.jlibaio.ffm.test;
+package org.apache.activemq.artemis.nativo.jlibaio.test.ffm;
import org.apache.activemq.artemis.nativo.jlibaio.ffm.IOCBInit;
import org.junit.jupiter.api.Test;
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOControlTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/IOControlTest.java
similarity index 99%
rename from src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOControlTest.java
rename to src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/IOControlTest.java
index 4c956d3..ef5085f 100644
--- a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOControlTest.java
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/ffm/IOControlTest.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.activemq.artemis.nativo.jlibaio.ffm.test;
+package org.apache.activemq.artemis.nativo.jlibaio.test.ffm;
import org.apache.activemq.artemis.nativo.jlibaio.ffm.IOControl;
import org.junit.jupiter.api.AfterEach;
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/AioCompareBenchmark.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/AioCompareBenchmark.java
new file mode 100644
index 0000000..23d2770
--- /dev/null
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/AioCompareBenchmark.java
@@ -0,0 +1,177 @@
+package org.apache.activemq.artemis.nativo.jlibaio.test.performance.jmh;
+
+import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext;
+import org.apache.activemq.artemis.nativo.jlibaio.LibaioFile;
+import org.apache.activemq.artemis.nativo.jlibaio.SubmitInfo;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Warmup;
+
+import java.io.File;
+import java.lang.foreign.MemorySegment;
+import java.nio.ByteBuffer;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@Fork(value = 2)
+@Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
+@Measurement(iterations = 10, time = 200, timeUnit = TimeUnit.MILLISECONDS)
+public class AioCompareBenchmark {
+
+ private static final int FILE_SIZE = 10000 * 4096;
+ private static final int BLOCK_SIZE = 4096;
+
+ @Param({"2048"})
+ private int LIBAIO_QUEUE_SIZE;
+
+ @Param({"10000"})
+ private int recordCount;
+
+ private File file;
+ private LibaioContext<SubmitInfo> control;
+ private LibaioFile<SubmitInfo> libaioFile;
+
+ private MemorySegment headerSegment;
+ private ByteBuffer headerBuffer;
+
+ private MemorySegment recordSegment;
+ private ByteBuffer recordBuffer;
+
+ private final AtomicReference<CountDownLatch> currentLatch = new AtomicReference<>();
+
+ private Thread pollThread;
+ private volatile boolean polling = true;
+
+ private final SubmitInfo callback = new SubmitInfo() {
+ @Override
+ public void onError(int errno, String message) {
+ //ignore
+ }
+
+ @Override
+ public void done() {
+ CountDownLatch latch = currentLatch.get();
+ if (latch != null) {
+ latch.countDown();
+ }
+ }
+ };
+
+ private long fileId = 1L;
+
+ @Setup(Level.Trial)
+ public void setuo() throws Exception {
+ file = File.createTempFile("aio-bench-", ".dat");
+
+ control = new LibaioContext<>(LIBAIO_QUEUE_SIZE, true, true);
+ libaioFile = control.openFile(file, true);
+
+ //one-time file initialization
+ libaioFile.fallocate(FILE_SIZE);
+
+ headerSegment = LibaioContext.newAlignedBuffer(BLOCK_SIZE, BLOCK_SIZE);
+ headerBuffer = headerSegment.asByteBuffer();
+
+ recordSegment = LibaioContext.newAlignedBuffer(BLOCK_SIZE, BLOCK_SIZE);
+ recordBuffer = recordSegment.asByteBuffer();
+
+ initRecord(headerBuffer); // filling the record clock with 1
+ initRecord(recordBuffer); // filling the record clock with 1
+
+ fillHeader(fileId);
+ updateRecord(recordBuffer, fileId, 0L);
+
+ polling = true;
+ pollThread = new Thread(() -> {
+ while (polling && !Thread.currentThread().isInterrupted()) {
+ try {
+ control.poll();
+ } catch (Throwable e) {
+ if (polling) {
+ throw new RuntimeException(e);
+ }
+ break;
+ }
+ }
+ }, "aio-jmh-poll-thread");
+ pollThread.setDaemon(true);
+ pollThread.start();
+ }
+
+ @TearDown(Level.Trial)
+ public void tearDown() throws Exception {
+ polling = false;
+ if (pollThread != null) {
+ pollThread.interrupt();
+ pollThread.join(TimeUnit.SECONDS.toMillis(10));
+ }
+
+ if (libaioFile != null) {
+ libaioFile.close();
+ }
+ if (control != null) {
+ control.close();
+ }
+ if (headerSegment != null && headerSegment.address() != 0) {
+ LibaioContext.freeBuffer(headerSegment);
+ }
+ if (recordSegment != null && recordSegment.address() != 0) {
+ LibaioContext.freeBuffer(recordSegment);
+ }
+ if (file != null) {
+ file.delete();
+ }
+ }
+
+ @Benchmark
+ public void writeHeaderAndRecord() throws Exception{
+ CountDownLatch latch = new CountDownLatch(recordCount * 100);
+ currentLatch.set(latch);
+
+ try {
+// fillHeader(fileId);
+// libaioFile.write(0L, BLOCK_SIZE, headerBuffer, callback);
+
+ for (int j=0; j<100; j++) {
+ for (int i = 0; i < recordCount; i++) {
+ updateRecord(recordBuffer, fileId, i);
+ long offset = BLOCK_SIZE + ((long) i * BLOCK_SIZE);
+ libaioFile.write(offset, BLOCK_SIZE, recordBuffer, callback);
+ }
+ }
+
+ latch.await();
+ } finally {
+ currentLatch.compareAndSet(latch, null);
+ }
+ }
+
+ private void fillHeader(long fileId) {
+ headerBuffer.putLong(0, fileId);
+ }
+
+ private void updateRecord(ByteBuffer buffer, long fileId, long recordId) {
+ buffer.putLong(0, fileId);
+ buffer.putLong(8, recordId);
+ }
+
+ private void initRecord(ByteBuffer record) {
+ while (record.position() < BLOCK_SIZE) {
+ record.put((byte) 1);
+ }
+ }
+}
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/BenchmarkRunner.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/BenchmarkRunner.java
new file mode 100644
index 0000000..ca57d78
--- /dev/null
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/BenchmarkRunner.java
@@ -0,0 +1,11 @@
+package org.apache.activemq.artemis.nativo.jlibaio.test.performance.jmh;
+
+import org.openjdk.jmh.Main;
+
+import java.io.IOException;
+
+public class BenchmarkRunner {
+ public static void main(String[] args) throws IOException {
+ Main.main(args);
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@artemis.apache.org
For additional commands, e-mail: commits-help@artemis.apache.org
(artemis-native) 03/04: removing hashMap registry
Posted by cl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
clebertsuconic pushed a commit to branch branch-panama
in repository https://gitbox.apache.org/repos/asf/artemis-native.git
commit ca8cf7fd1b0abf74d99965f86e3874e458049f88
Author: mayankkunwar <ms...@gmail.com>
AuthorDate: Tue Apr 28 13:08:06 2026 +0100
removing hashMap registry
---
.../artemis/nativo/jlibaio/LibaioContext.java | 6 +--
.../nativo/jlibaio/ffm/CallbackRegistry.java | 58 ----------------------
.../nativo/jlibaio/ffm/FFMNativeHelper.java | 57 +++++++++++----------
.../artemis/nativo/jlibaio/ffm/IOControl.java | 26 +++++++++-
4 files changed, 58 insertions(+), 89 deletions(-)
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioContext.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioContext.java
index 78e3f7c..355708f 100644
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioContext.java
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioContext.java
@@ -150,7 +150,7 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
/**
* the native ioContext including the structure created.
*/
- private final IOControl ioContext;
+ private final IOControl<Callback> ioContext;
private final AtomicBoolean closed = new AtomicBoolean(false);
@@ -376,7 +376,7 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
/**
* This is the queue for libaio, initialized with queueSize.
*/
- private IOControl newContext(int queueSize) {
+ private IOControl<Callback> newContext(int queueSize) {
return this.ffmNativeHelper.newContext(queueSize);
}
@@ -464,7 +464,7 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
/**
* This method will block as long as the context is open.
*/
- void blockedPoll(IOControl ioControl, boolean useFdatasync) {
+ void blockedPoll(IOControl<Callback> ioControl, boolean useFdatasync) {
this.ffmNativeHelper.blockedPoll(ioControl, useFdatasync);
}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java
deleted file mode 100644
index 8d86038..0000000
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.activemq.artemis.nativo.jlibaio.ffm;
-
-import org.apache.activemq.artemis.nativo.jlibaio.SubmitInfo;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Objects;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicLong;
-
-public class CallbackRegistry<Callback extends SubmitInfo> {
-// private static final Logger logger = LoggerFactory.getLogger(CallbackRegistry.class);
- private final ConcurrentHashMap<Long, Callback> registry = new ConcurrentHashMap<>();
- private final AtomicLong idGenerator = new AtomicLong(0);
-
- /*
- * <p>
- * This method is thread-safe and lock-free. It avoids returning an ID of -1 and 0,
- * as -1 and 0 are reserved as a NULL/Invalid marker in the native libaio layer.
- *
- * @param callback the I/O completion handler to register.
- * @return a unique identifier (other than -1 or 0) for this callback.
- * */
- public long register(Callback callback) {
- Objects.requireNonNull(callback, "Callbacks cannot be null");
- long id;
- do {
- id = idGenerator.incrementAndGet();
- } while (id == -1 || id == 0);
- registry.put(id, callback);
-// logger.debug("CallbackRegistry::register id = {}, callback = {}", id, callback);
- return id;
- }
-
- public Callback findCallbackById(long id) {
- return registry.get(id);
- }
-
- public void removeCallbackById(long id) {
- this.registry.remove(id);
- }
-}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java
index 9101936..79eed7f 100644
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java
@@ -135,12 +135,9 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
}
- private final CallbackRegistry<Callback> registry;
-
private final ReleaseCallback releaseCallback;
public FFMNativeHelper(ReleaseCallback releaseCallback) {
- this.registry = new CallbackRegistry<>();
this.releaseCallback = releaseCallback;
}
@@ -319,10 +316,10 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
return forceSysCall.get() || !RING_REAPER;
}
- public IOControl newContext(int queueSize) {
+ public IOControl<Callback> newContext(int queueSize) {
// logger.debug("Initializing context with QueueSize={}", queueSize);
- IOControl ioControl = new IOControl();
+ IOControl<Callback> ioControl = new IOControl<>();
try {
MemorySegment ioContext = ioQueueInit(queueSize);
ioControl.setIoContext(ioContext);
@@ -348,7 +345,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
throw new OutOfMemoryError(
String.format("Arena memory allocation failed: iocb[%d/%d]", i, queueSize));
}
- IOCBInit.setAioData(iocb, 0L);
+ IOCBInit.setAioData(iocb, i);
iocbPool[i] = iocb;
}
ioControl.setIocbPool(iocbPool);
@@ -430,7 +427,8 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
throw new IOException("Not enough space in libaio queue during shutdown");
}
ioPrepPOp(dumbIocb, DUMB_WRITE_HANDLER, MemorySegment.NULL, 0L, 0L, 1);
- IOCBInit.setAioData(dumbIocb, -1L);
+ int iocbId = (int) IOCBInit.getAioData(dumbIocb);
+ ioControl.getIocbState().set(iocbId, -1);
if(!submit(ioControl, dumbIocb)) {
// logger.warn("deleteContext: submit failed: Continuing cleanup");
@@ -631,21 +629,24 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
throw new IOException("IOCB pool exhausted (used=" + ioControl.used() +
"/queueSize=" + ioControl.queueSize() + ")");
}
-// logger.trace("submitWrite called!");
- long callbackId = registry.register(callback);
+ int callbackId = (int) IOCBInit.getAioData(iocb);
+// logger.trace("submitWrite called! callbackId: {}", callbackId);
boolean submitted = false;
try {
+ if (!ioControl.getIocbState().compareAndSet(callbackId, 0, 1)) {
+ throw new IOException("submitWrite failed: callbackId=" + callbackId + " already in use");
+ }
+ ioControl.addCallback(callbackId, callback);
bufferWrite.clear();
ioPrepPOp(iocb, fd, MemorySegment.ofBuffer(bufferWrite), size, position, 1);
- IOCBInit.setAioData(iocb, callbackId);
submit(ioControl, iocb);
submitted = true;
} catch (Throwable e) {
throw new IOException("submitWrite failed", e);
} finally {
if(!submitted) {
- registry.removeCallbackById(callbackId);
+ ioControl.takeCallback(callbackId);
}
}
}
@@ -690,25 +691,28 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
// logger.trace("submitRead called!");
- long callbackId = registry.register(callback);
+ long callbackId = IOCBInit.getAioData(iocb);
boolean submitted = false;
try {
+ if (!ioControl.getIocbState().compareAndSet((int) callbackId, 0, 1)) {
+ throw new IOException("submitRead failed: callbackId=" + callbackId + " already in use");
+ }
+ ioControl.addCallback((int) callbackId, callback);
bufferWrite.clear();
ioPrepPOp(iocb, fd, MemorySegment.ofBuffer(bufferWrite), size, position, 0);
- IOCBInit.setAioData(iocb, callbackId);
submit(ioControl, iocb);
submitted = true;
} catch (Throwable e) {
throw new IOException("submitRead failed", e);
} finally {
if(!submitted) {
- registry.removeCallbackById(callbackId);
+ ioControl.takeCallback((int) callbackId);
}
}
}
- public int poll(IOControl ioControl, Callback[] callbacks, int min, int max) {
+ public int poll(IOControl<Callback> ioControl, Callback[] callbacks, int min, int max) {
if(ioControl == null || !ioControl.isValid()) {
// logger.warn("poll: invalid context");
return 0;
@@ -734,20 +738,22 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
MemorySegment iocbp = event.get(ValueLayout.ADDRESS, 8L)
.reinterpret(64);
int eventResult = (int) event.get(ValueLayout.JAVA_LONG, 16L);
-// logger.trace("poll[{}]: res={}, iocbp=0x{}", i, eventResult, Long.toHexString(iocbp.address()));
+// logger.trace("poll[{}]: res={}, iocbp=0x{}, AioData: {}", i, eventResult, Long.toHexString(iocbp.address()),
+// IOCBInit.getAioData(iocbp));
if(eventResult < 0) {
// logger.warn("poll[{}]: I/O error: {}", i, eventResult);
}
- long callbackIdRaw = IOCBInit.getAioData(iocbp);
- if(callbackIdRaw == 0L || callbackIdRaw == -1L) {
+ int callbackIdRaw = (int) IOCBInit.getAioData(iocbp);
+ int iocbState = ioControl.getIocbState().get(callbackIdRaw);
+ if(iocbState == 0 || iocbState == -1) {
// logger.warn("poll[{}]: invalid callback=0x{}", i, Long.toHexString(callbackIdRaw));
ioControl.putIOCB(iocbp);
continue;
}
- Callback callback = registry.findCallbackById(callbackIdRaw);
+ Callback callback = ioControl.takeCallback(callbackIdRaw);
if(callback != null) {
callbacks[i] = callback;
if(eventResult < 0) {
@@ -758,11 +764,11 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
if (releaseCallback != null) {
releaseCallback.release();
}
- registry.removeCallbackById(callbackIdRaw);
} else {
// logger.warn("poll[{}]: callback not found for id=0x{}",
// i, Long.toHexString(callbackIdRaw));
}
+ ioControl.getIocbState().set(callbackIdRaw, 0);
ioControl.putIOCB(iocbp);
}
return result;
@@ -772,7 +778,7 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
}
}
- public void blockedPoll(IOControl ioControl, boolean useFdatasync) {
+ public void blockedPoll(IOControl<Callback> ioControl, boolean useFdatasync) {
// logger.debug("blockedPoll starting(useFdatasync={})", useFdatasync);
if(ioControl == null || !ioControl.isValid()) {
// logger.warn("blockedPoll: invalid context");
@@ -830,13 +836,13 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
int eventResult = (int) event.get(ValueLayout.JAVA_LONG, 16L);
- long callbackIdRaw = IOCBInit.getAioData(iocbp);
+ int callbackIdRaw = (int) IOCBInit.getAioData(iocbp);
// logger.trace("blockedPoll: callbackIdRaw: {}", callbackIdRaw);
- IOCBInit.setAioData(iocbp, 0L); // this is to detect invalid elements on the buffer.
- if(callbackIdRaw != 0L) {
+ // this IOCB state is to detect invalid elements on the buffer.
+ if(ioControl.getIocbState().compareAndSet(callbackIdRaw, 1, 0)) {
ioControl.putIOCB(iocbp);
- Callback callback = registry.findCallbackById(callbackIdRaw);
+ Callback callback = ioControl.takeCallback(callbackIdRaw);
if (callback != null) {
if (eventResult < 0) {
// logger.error("blockedPoll[{}]: I/O error fd={}, {}", i, fd, eventResult);
@@ -848,7 +854,6 @@ public class FFMNativeHelper<Callback extends SubmitInfo> {
if (releaseCallback != null) {
releaseCallback.release();
}
- registry.removeCallbackById(callbackIdRaw);
}
} else {
if(!forceSysCall.get()) {
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOControl.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOControl.java
index 8777335..8ba9eef 100644
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOControl.java
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOControl.java
@@ -16,13 +16,15 @@
*/
package org.apache.activemq.artemis.nativo.jlibaio.ffm;
+import org.apache.activemq.artemis.nativo.jlibaio.SubmitInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.foreign.MemorySegment;
-import java.util.concurrent.locks.ReentrantLock;
+import java.util.concurrent.atomic.AtomicIntegerArray;
+import java.util.concurrent.atomic.AtomicReferenceArray;
-public class IOControl {
+public class IOControl<Callback extends SubmitInfo> {
// private static final Logger logger = LoggerFactory.getLogger(IOControl.class);
private final Object iocbLock = new Object();
@@ -35,6 +37,10 @@ public class IOControl {
private int iocbGet;
private int used;
private MemorySegment[] iocbPool;
+ private AtomicReferenceArray<Callback> callbackRegistry;
+
+ // -1: delete, 0: free, 1: used
+ private AtomicIntegerArray iocbState;
public MemorySegment ioContext() {
return this.ioContext;
@@ -55,6 +61,8 @@ public class IOControl {
}
public void setQueueSize(int size) {
this.queueSize = size;
+ callbackRegistry = new AtomicReferenceArray<>(size);
+ iocbState = new AtomicIntegerArray(size);
}
public int iocbPut() {
@@ -74,6 +82,20 @@ public class IOControl {
this.iocbPool = iocbPool;
}
+ public void addCallback(int idx, Callback callback) {
+ if (callbackRegistry.get(idx) != null) {
+ throw new IllegalStateException("callback already registered");
+ }
+ callbackRegistry.set(idx, callback);
+ }
+ public Callback takeCallback(int idx) {
+ return callbackRegistry.getAndSet(idx, null);
+ }
+
+ public AtomicIntegerArray getIocbState() {
+ return this.iocbState;
+ }
+
public void withIocbLock(Runnable action) {
synchronized ( iocbLock){
action.run();
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@artemis.apache.org
For additional commands, e-mail: commits-help@artemis.apache.org
(artemis-native) 04/04: changes
Posted by cl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
clebertsuconic pushed a commit to branch branch-panama
in repository https://gitbox.apache.org/repos/asf/artemis-native.git
commit fb7a33f731d1564b3531a06fff89f2f0a4401ea5
Author: Clebert Suconic <cl...@gmail.com>
AuthorDate: Wed Apr 29 14:20:00 2026 -0400
changes
---
.../nativo/jlibaio/test/performance/jmh/AioCompareBenchmark.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/AioCompareBenchmark.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/AioCompareBenchmark.java
index 23d2770..0b5495b 100644
--- a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/AioCompareBenchmark.java
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/performance/jmh/AioCompareBenchmark.java
@@ -139,14 +139,14 @@ public class AioCompareBenchmark {
@Benchmark
public void writeHeaderAndRecord() throws Exception{
- CountDownLatch latch = new CountDownLatch(recordCount * 100);
+ CountDownLatch latch = new CountDownLatch(recordCount * 10);
currentLatch.set(latch);
try {
// fillHeader(fileId);
// libaioFile.write(0L, BLOCK_SIZE, headerBuffer, callback);
- for (int j=0; j<100; j++) {
+ for (int j=0; j<10; j++) {
for (int i = 0; i < recordCount; i++) {
updateRecord(recordBuffer, fileId, i);
long offset = BLOCK_SIZE + ((long) i * BLOCK_SIZE);
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@artemis.apache.org
For additional commands, e-mail: commits-help@artemis.apache.org
(artemis-native) 01/04: ARTEMIS-5972: Replace JNI with Panama Foreign Function & Memory (FFM) API for Journal Native Layer
Posted by cl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
clebertsuconic pushed a commit to branch branch-panama
in repository https://gitbox.apache.org/repos/asf/artemis-native.git
commit 048aa8ae09bd0298fe14ea653d607bf2e38b12d2
Author: mayankkunwar <ms...@gmail.com>
AuthorDate: Wed Mar 25 12:37:58 2026 +0000
ARTEMIS-5972: Replace JNI with Panama Foreign Function & Memory (FFM) API for Journal Native Layer
---
pom.xml | 22 +-
.../artemis/nativo/jlibaio/LibaioContext.java | 146 +--
.../artemis/nativo/jlibaio/LibaioFile.java | 16 +-
.../artemis/nativo/jlibaio/ffm/AIORing.java | 110 ++
.../nativo/jlibaio/ffm/CallbackRegistry.java | 58 ++
.../artemis/nativo/jlibaio/ffm/Constants.java | 61 ++
.../artemis/nativo/jlibaio/ffm/FFMHandles.java | 239 +++++
.../nativo/jlibaio/ffm/FFMNativeHelper.java | 1083 ++++++++++++++++++++
.../artemis/nativo/jlibaio/ffm/IOCBInit.java | 140 +++
.../artemis/nativo/jlibaio/ffm/IOControl.java | 166 +++
.../artemis/nativo/jlibaio/ffm/IOEvent.java | 55 +
.../nativo/jlibaio/ffm/ReleaseCallback.java | 22 +
.../activemq/artemis/nativo/jlibaio/ffm/Stat.java | 53 +
.../jlibaio/ffm/test/FFMNativeHelperTest.java | 443 ++++++++
.../nativo/jlibaio/ffm/test/IOCBLayoutTest.java | 52 +
.../nativo/jlibaio/ffm/test/IOControlTest.java | 304 ++++++
.../nativo/jlibaio/test/LibaioStressTest.java | 4 +-
.../artemis/nativo/jlibaio/test/LibaioTest.java | 79 +-
.../nativo/jlibaio/test/OpenCloseContextTest.java | 7 +-
19 files changed, 2952 insertions(+), 108 deletions(-)
diff --git a/pom.xml b/pom.xml
index d4693f8..3d049b6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -47,12 +47,12 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <maven.compiler.source>11</maven.compiler.source>
- <maven.compiler.target>11</maven.compiler.target>
- <maven.compiler.release>11</maven.compiler.release>
+ <maven.compiler.source>22</maven.compiler.source>
+ <maven.compiler.target>22</maven.compiler.target>
+ <maven.compiler.release>22</maven.compiler.release>
<activemq-surefire-argline>
- -Dtest.stress.time=${test.stress.time} -Djava.library.path="${activemq.basedir}/target/lib/linux-${os.arch}"
+ -Dtest.stress.time=${test.stress.time} -Djava.library.path="${activemq.basedir}/target/lib/linux-${os.arch}" --enable-native-access=ALL-UNNAMED
</activemq-surefire-argline>
<activemq.basedir>${project.basedir}</activemq.basedir>
@@ -98,6 +98,18 @@
<scope>test</scope>
<!-- License: EPL 1.0 -->
</dependency>
+ <dependency>
+ <groupId>org.junit.vintage</groupId>
+ <artifactId>junit-vintage-engine</artifactId>
+ <version>5.10.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <version>5.10.2</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>org.jacoco.ant</artifactId>
@@ -428,7 +440,7 @@
<configuration>
<instructions>
<!-- Adding Bundle-NativeCode to allow loading library from bundle. The asterisk at the end is important, so bundle resolves also without a matching library, e.g. on Windows. -->
- <Bundle-NativeCode>lib/linux-i686/libartemis-native-32.so; osname=Linux; processor=x86, lib/linux-x86_64/libartemis-native-64.so; osname=Linux; processor=x86-64, *</Bundle-NativeCode>
+<!-- <Bundle-NativeCode>lib/linux-i686/libartemis-native-32.so; osname=Linux; processor=x86, lib/linux-x86_64/libartemis-native-64.so; osname=Linux; processor=x86-64, *</Bundle-NativeCode>-->
</instructions>
</configuration>
</plugin>
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioContext.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioContext.java
index d776ea7..78e3f7c 100644
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioContext.java
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioContext.java
@@ -19,6 +19,7 @@ package org.apache.activemq.artemis.nativo.jlibaio;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
+import java.lang.foreign.MemorySegment;
import java.nio.ByteBuffer;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
@@ -26,6 +27,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
+import org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMNativeHelper;
+import org.apache.activemq.artemis.nativo.jlibaio.ffm.IOControl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -59,7 +62,7 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
*/
private static final int EXPECTED_NATIVE_VERSION = 200;
- private static boolean loaded = false;
+ private static boolean loaded = true;
private static final AtomicBoolean shuttingDown = new AtomicBoolean(false);
@@ -87,30 +90,16 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
}
static {
- String[] libraries = new String[]{"artemis-native-64", "artemis-native-32"};
-
- for (String library : libraries) {
- if (loadLibrary(library)) {
- loaded = true;
- if (System.getProperty("org.apache.activemq.artemis.native.jlibaio.FORCE_SYSCALL") != null) {
- LibaioContext.setForceSyscall(true);
- }
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
- shuttingDown.set(true);
- checkShutdown();
- }
- });
- break;
- } else {
- logger.debug("Library {} not found!", library);
- }
- }
-
- if (!loaded) {
- logger.debug("Couldn't locate LibAIO Wrapper");
+ if (System.getProperty("org.apache.activemq.artemis.native.jlibaio.FORCE_SYSCALL") != null) {
+ LibaioContext.setForceSyscall(true);
}
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ @Override
+ public void run() {
+ shuttingDown.set(true);
+ checkShutdown();
+ }
+ });
}
private static void checkShutdown() {
@@ -119,12 +108,18 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
}
}
- private static native void shutdownHook();
+ private static void shutdownHook() {
+ FFMNativeHelper.shutdownHook();
+ }
- public static native void setForceSyscall(boolean value);
+ public static void setForceSyscall(boolean value) {
+ FFMNativeHelper.setForceSyscall(value);
+ }
/** The system may choose to set this if a failing condition happened inside the code. */
- public static native boolean isForceSyscall();
+ public static boolean isForceSyscall() {
+ return FFMNativeHelper.isForceSyscall();
+ }
/**
* This is used to validate leaks on tests.
@@ -155,7 +150,7 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
/**
* the native ioContext including the structure created.
*/
- private final ByteBuffer ioContext;
+ private final IOControl ioContext;
private final AtomicBoolean closed = new AtomicBoolean(false);
@@ -165,6 +160,8 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
final boolean useFdatasync;
+ final FFMNativeHelper<Callback> ffmNativeHelper;
+
/**
* The queue size here will use resources defined on the kernel parameter
* <a href="https://www.kernel.org/doc/Documentation/sysctl/fs.txt">fs.aio-max-nr</a> .
@@ -176,6 +173,7 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
*/
public LibaioContext(int queueSize, boolean useSemaphore, boolean useFdatasync) {
try {
+ this.ffmNativeHelper = new FFMNativeHelper<>(this::releaseSemaphore);
contexts.incrementAndGet();
this.ioContext = newContext(queueSize);
this.useFdatasync = useFdatasync;
@@ -369,11 +367,7 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
}
}
- /**
- * Called from the native layer
- */
- private void done(SubmitInfo info) {
- info.done();
+ private void releaseSemaphore() {
if (ioSpace != null) {
ioSpace.release();
}
@@ -382,12 +376,16 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
/**
* This is the queue for libaio, initialized with queueSize.
*/
- private native ByteBuffer newContext(int queueSize);
+ private IOControl newContext(int queueSize) {
+ return this.ffmNativeHelper.newContext(queueSize);
+ }
/**
* Internal method to be used when closing the controller.
*/
- private native void deleteContext(ByteBuffer buffer);
+ private void deleteContext(IOControl ioControl) {
+ this.ffmNativeHelper.deleteContext(ioControl);
+ }
/**
* it will return a file descriptor.
@@ -396,9 +394,13 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
* @param direct translates as O_DIRECT On open
* @return a fd from open C call.
*/
- public static native int open(String path, boolean direct);
+ public static int open(String path, boolean direct) throws IOException {
+ return FFMNativeHelper.open(path, direct);
+ }
- public static native void close(int fd);
+ public static void close(int fd) throws IOException {
+ FFMNativeHelper.close(fd);
+ }
/**
*/
@@ -412,34 +414,42 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
* @param alignment the alignment used at the dispositive
* @return a new native buffer used with posix_memalign
*/
- public static native ByteBuffer newAlignedBuffer(int size, int alignment);
+ public static MemorySegment newAlignedBuffer(int size, int alignment) {
+ return FFMNativeHelper.newAlignedBuffer(size, alignment);
+ }
/**
* This will call posix free to release the inner buffer allocated at {@link #newAlignedBuffer(int, int)}.
*
* @param buffer a native buffer allocated with {@link #newAlignedBuffer(int, int)}.
*/
- public static native void freeBuffer(ByteBuffer buffer);
+ public static void freeBuffer(MemorySegment buffer) {
+ FFMNativeHelper.freeBuffer(buffer);
+ }
/**
* Documented at {@link LibaioFile#write(long, int, java.nio.ByteBuffer, SubmitInfo)}.
*/
- native void submitWrite(int fd,
- ByteBuffer libaioContext,
+ void submitWrite(int fd,
+ IOControl ioControl,
long position,
int size,
ByteBuffer bufferWrite,
- Callback callback) throws IOException;
+ Callback callback) throws IOException {
+ this.ffmNativeHelper.submitWrite(fd, ioControl, position, size, bufferWrite, callback);
+ }
/**
* Documented at {@link LibaioFile#read(long, int, java.nio.ByteBuffer, SubmitInfo)}.
*/
- native void submitRead(int fd,
- ByteBuffer libaioContext,
+ void submitRead(int fd,
+ IOControl ioControl,
long position,
int size,
ByteBuffer bufferWrite,
- Callback callback) throws IOException;
+ Callback callback) throws IOException {
+ this.ffmNativeHelper.submitRead(fd, ioControl, position, size, bufferWrite, callback);
+ }
/**
* Note: this shouldn't be done concurrently.
@@ -447,32 +457,54 @@ public class LibaioContext<Callback extends SubmitInfo> implements Closeable {
* <p/>
* The callbacks will include the original callback sent at submit (read or write).
*/
- native int poll(ByteBuffer libaioContext, Callback[] callbacks, int min, int max);
+ int poll(IOControl ioControl, Callback[] callbacks, int min, int max) {
+ return this.ffmNativeHelper.poll(ioControl, callbacks, min, max);
+ }
/**
* This method will block as long as the context is open.
*/
- native void blockedPoll(ByteBuffer libaioContext, boolean useFdatasync);
+ void blockedPoll(IOControl ioControl, boolean useFdatasync) {
+ this.ffmNativeHelper.blockedPoll(ioControl, useFdatasync);
+ }
- static native int getNativeVersion();
+ static int getNativeVersion() {
+ return FFMNativeHelper.getNativeVersion();
+ }
- public static native boolean lock(int fd);
+ public static boolean lock(int fd) {
+ return FFMNativeHelper.lock(fd);
+ }
- public static native void memsetBuffer(ByteBuffer buffer, int size);
+ public static void memsetBuffer(ByteBuffer buffer, int size) {
+ FFMNativeHelper.memsetBuffer(buffer, size);
+ }
- static native long getSize(int fd);
+ static long getSize(int fd) throws IOException {
+ return FFMNativeHelper.getSize(fd);
+ }
- static native int getBlockSizeFD(int fd);
+ static int getBlockSizeFD(int fd) throws IOException {
+ return FFMNativeHelper.getBlockSizeFD(fd);
+ }
- public static int getBlockSize(File path) {
+ public static int getBlockSize(File path) throws IOException {
return getBlockSize(path.getAbsolutePath());
}
- public static native int getBlockSize(String path);
+ public static int getBlockSize(String path) throws IOException {
+ return FFMNativeHelper.getBlockSize(path);
+ }
- static native void fallocate(int fd, long size);
+ static void fallocate(int fd, long size) throws IOException {
+ FFMNativeHelper.fallocate(fd, size);
+ }
- static native void fill(int fd, int alignment, long size);
+ static void fill(int fd, int alignment, long size) throws IOException {
+ FFMNativeHelper.fill(fd, alignment, size);
+ }
- static native void writeInternal(int fd, long position, long size, ByteBuffer bufferWrite) throws IOException;
+ static void writeInternal(int fd, long position, long size, ByteBuffer bufferWrite) throws IOException {
+ FFMNativeHelper.writeInternal(fd, position, size, bufferWrite);
+ }
}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioFile.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioFile.java
index 7b6967b..31bf0e7 100644
--- a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioFile.java
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/LibaioFile.java
@@ -17,7 +17,9 @@
package org.apache.activemq.artemis.nativo.jlibaio;
import java.io.IOException;
+import java.lang.foreign.MemorySegment;
import java.nio.ByteBuffer;
+import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -43,7 +45,7 @@ public final class LibaioFile<Callback extends SubmitInfo> implements AutoClosea
this.fd = fd;
}
- public int getBlockSize() {
+ public int getBlockSize() throws IOException {
return LibaioContext.getBlockSizeFD(fd);
}
@@ -60,7 +62,7 @@ public final class LibaioFile<Callback extends SubmitInfo> implements AutoClosea
/**
* @return The size of the file.
*/
- public long getSize() {
+ public long getSize() throws IOException {
return LibaioContext.getSize(fd);
}
@@ -79,6 +81,7 @@ public final class LibaioFile<Callback extends SubmitInfo> implements AutoClosea
* @throws java.io.IOException in case of error
*/
public void write(long position, int size, ByteBuffer buffer, Callback callback) throws IOException {
+ Objects.requireNonNull(callback, "Callback cannot be null");
ctx.submitWrite(fd, position, size, buffer, callback);
}
@@ -99,6 +102,7 @@ public final class LibaioFile<Callback extends SubmitInfo> implements AutoClosea
* @see LibaioContext#poll(SubmitInfo[], int, int)
*/
public void read(long position, int size, ByteBuffer buffer, Callback callback) throws IOException {
+ Objects.requireNonNull(callback, "Callback cannot be null");
ctx.submitRead(fd, position, size, buffer, callback);
}
@@ -107,12 +111,12 @@ public final class LibaioFile<Callback extends SubmitInfo> implements AutoClosea
* Buffers here are allocated with posix_memalign.
* <br>
* You need to explicitly free the buffer created from here using the
- * {@link LibaioContext#freeBuffer(java.nio.ByteBuffer)}.
+ * {@link LibaioContext#freeBuffer(java.lang.foreign.MemorySegment)}.
*
* @param size the size of the buffer.
* @return the buffer allocated.
*/
- public ByteBuffer newBuffer(int size) {
+ public MemorySegment newBuffer(int size) {
return LibaioContext.newAlignedBuffer(size, 4 * 1024);
}
@@ -121,7 +125,7 @@ public final class LibaioFile<Callback extends SubmitInfo> implements AutoClosea
*
* @param size number of bytes to be filled on the file
*/
- public void fill(int alignment, long size) {
+ public void fill(int alignment, long size) throws IOException {
try {
LibaioContext.fill(fd, alignment, size);
} catch (OutOfMemoryError e) {
@@ -135,7 +139,7 @@ public final class LibaioFile<Callback extends SubmitInfo> implements AutoClosea
*
* @param size number of bytes to be filled on the file
*/
- public void fallocate(long size) {
+ public void fallocate(long size) throws IOException {
LibaioContext.fallocate(fd, size);
}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/AIORing.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/AIORing.java
new file mode 100644
index 0000000..862b58e
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/AIORing.java
@@ -0,0 +1,110 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.foreign.MemoryLayout;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.StructLayout;
+import java.lang.foreign.ValueLayout;
+import java.lang.invoke.VarHandle;
+
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.AIO_RING_INCOMPAT_FEATURES;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.AIO_RING_MAGIC;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.IOEvent.IO_EVENT_LAYOUT;
+
+public class AIORing {
+ private static final Logger logger = LoggerFactory.getLogger(AIORing.class);
+
+ /** There is no defined aio_ring anywhere in an include,
+ This is an implementation detail, that is a binary contract.
+ it is safe to use the feature though. */
+ static final StructLayout AIO_RING_LAYOUT = MemoryLayout.structLayout(
+ // Fixed header (32 bytes)
+ ValueLayout.JAVA_INT.withName("id"), /* kernel internal index number */
+ ValueLayout.JAVA_INT.withName("nr"), /* number of io_events */
+ ValueLayout.JAVA_INT.withName("head"),
+ ValueLayout.JAVA_INT.withName("tail"),
+ ValueLayout.JAVA_INT.withName("magic"),
+ ValueLayout.JAVA_INT.withName("compat_features"),
+ ValueLayout.JAVA_INT.withName("incompat_features"),
+ ValueLayout.JAVA_INT.withName("header_length") /* size of aio_ring */
+ ).withName("aio_ring");
+
+ public static final long AIO_RING_HEADER_SIZE = AIO_RING_LAYOUT.byteSize();
+
+ public static final VarHandle AIO_RING_NR_VH =
+ AIO_RING_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("nr"));
+ public static final VarHandle AIO_RING_HEAD_VH =
+ AIO_RING_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("head"));
+ public static final VarHandle AIO_RING_TAIL_VH =
+ AIO_RING_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("tail"));
+ public static final VarHandle AIO_RING_MAGIC_VH =
+ AIO_RING_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("magic"));
+ public static final VarHandle AIO_RING_INCOMPAT_FEATURES_VH =
+ AIO_RING_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("incompat_features"));
+
+ // Check if the implementation supports AIO_RING by checking this number directly.
+ public static boolean hasUsableRing(MemorySegment ring) {
+ if (ring == null || ring.address() == 0L || ring.byteSize() < AIO_RING_HEADER_SIZE) {
+ return false;
+ }
+
+ MemorySegment header = ring.asSlice(0, AIO_RING_HEADER_SIZE);
+ int magic = (int) AIO_RING_MAGIC_VH.getAcquire(header, 0L);
+ int incompat = (int) AIO_RING_INCOMPAT_FEATURES_VH.getAcquire(header, 0L);
+ int nr = (int) AIO_RING_NR_VH.getAcquire(header, 0L);
+ logger.trace("nr={}, magic={}, incompat={}", nr, magic, incompat);
+
+ return magic == AIO_RING_MAGIC
+ && incompat == AIO_RING_INCOMPAT_FEATURES
+ && nr > 0;
+ }
+
+ // Newer versions of the kernel (newer here being a relative word, a couple years already at the time
+ // I am writing this), will have io_context_t as an opaque type, and the real type being the aio_ring.
+ public static MemorySegment toAioRing(MemorySegment aioCtx) {
+ if (aioCtx == null || aioCtx.address() == 0L) {
+ return MemorySegment.NULL;
+ }
+
+ MemorySegment header = aioCtx.reinterpret(AIO_RING_HEADER_SIZE);
+
+ if (!hasUsableRing(header)) {
+ return MemorySegment.NULL;
+ }
+
+ int nr = (int) AIO_RING_NR_VH.getAcquire(header, 0L);
+ long eventBytesize = IO_EVENT_LAYOUT.byteSize();
+ long fullSize;
+
+ try {
+ fullSize = Math.addExact(AIO_RING_HEADER_SIZE, Math.multiplyExact((long) nr, eventBytesize));
+ } catch (ArithmeticException e) {
+ logger.warn("toAioRing: overflow computing ring size (nr={}, eventBytes={})", nr, eventBytesize);
+ return MemorySegment.NULL;
+ }
+
+ if (fullSize <= AIO_RING_HEADER_SIZE) {
+ return MemorySegment.NULL;
+ }
+
+ return aioCtx.reinterpret(fullSize);
+ }
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java
new file mode 100644
index 0000000..b60f2bc
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/CallbackRegistry.java
@@ -0,0 +1,58 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+import org.apache.activemq.artemis.nativo.jlibaio.SubmitInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class CallbackRegistry<Callback extends SubmitInfo> {
+ private static final Logger logger = LoggerFactory.getLogger(CallbackRegistry.class);
+ private final ConcurrentHashMap<Long, Callback> registry = new ConcurrentHashMap<>();
+ private final AtomicLong idGenerator = new AtomicLong(0);
+
+ /*
+ * <p>
+ * This method is thread-safe and lock-free. It avoids returning an ID of -1 and 0,
+ * as -1 and 0 are reserved as a NULL/Invalid marker in the native libaio layer.
+ *
+ * @param callback the I/O completion handler to register.
+ * @return a unique identifier (other than -1 or 0) for this callback.
+ * */
+ public long register(Callback callback) {
+ Objects.requireNonNull(callback, "Callbacks cannot be null");
+ long id;
+ do {
+ id = idGenerator.incrementAndGet();
+ } while (id == -1 || id == 0);
+ registry.put(id, callback);
+ logger.debug("CallbackRegistry::register id = {}, callback = {}", id, callback);
+ return id;
+ }
+
+ public Callback findCallbackById(long id) {
+ return registry.get(id);
+ }
+
+ public void removeCallbackById(long id) {
+ this.registry.remove(id);
+ }
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/Constants.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/Constants.java
new file mode 100644
index 0000000..779d0a7
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/Constants.java
@@ -0,0 +1,61 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+public final class Constants {
+ private Constants(){}
+
+ static final long ONE_MEGA = 1048576L;
+
+ //These should be used to check if the user-space io_getevents is supported:
+ //Linux ABI for the ring buffer: https://elixir.bootlin.com/linux/v4.20.13/source/fs/aio.c#L54
+ //aio_read_events_ring: https://elixir.bootlin.com/linux/v4.20.13/source/fs/aio.c#L1148
+
+ // NOTE: if the kernel ever updates the structure, the RING-MAGIC will change and the code will switch back to normal IO calls
+ static final int AIO_RING_MAGIC = 0xa10a10a1;
+ static final int AIO_RING_INCOMPAT_FEATURES = 0;
+
+ // set this to false if you want to stop using ring reaping
+ static final boolean RING_REAPER = true;
+
+ static final int PERMISSION_MODE = 0666;
+ static final int O_RDWR = 0x0002;
+ static final int O_CREAT = 0x0040;
+ static final int O_DIRECT;
+
+ static final int LOCK_EX = 2; // Exclusive lock
+ static final int LOCK_NB = 4; // Non-blocking lock
+
+ static {
+ O_DIRECT = detectODirectFlag();
+ }
+
+ /*
+ * Detecting OS Architecture and setting O_DIRECT
+ *
+ * */
+ private static int detectODirectFlag() {
+ String arch = System.getProperty("os.arch");
+ if ("aarch64".equals(arch) || "arm64".equals(arch) || "arm".equals(arch)) {
+ return 0x10000;
+ } else if ("ppc64le".equals(arch) || "ppc64".equals(arch) || "ppc".equals(arch)) {
+ return 0x8000;
+ }
+ // amd64, x86_64
+ return 0x4000;
+ }
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMHandles.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMHandles.java
new file mode 100644
index 0000000..ffa8574
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMHandles.java
@@ -0,0 +1,239 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+import java.lang.foreign.Arena;
+import java.lang.foreign.FunctionDescriptor;
+import java.lang.foreign.Linker;
+import java.lang.foreign.MemoryLayout;
+import java.lang.foreign.StructLayout;
+import java.lang.foreign.SymbolLookup;
+import java.lang.foreign.ValueLayout;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.VarHandle;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class FFMHandles {
+
+ static final Linker LINKER = Linker.nativeLinker();
+ static final SymbolLookup STDLIB = setStdLib();
+ public static final SymbolLookup LIBAIO = setLibaio();
+
+ static final ReentrantLock oneMegaMutex = new ReentrantLock();
+
+ static final StructLayout CAPTURE_STATE_LAYOUT = Linker.Option.captureStateLayout();
+ static final VarHandle ERRNO_VH =
+ CAPTURE_STATE_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("errno"));
+
+ private static final Linker.Option captureCallState =
+ Linker.Option.captureCallState("errno");
+
+ static final MethodHandle WRITE_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("write").orElseThrow(() ->
+ new UnsatisfiedLinkError("write not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.JAVA_LONG,
+ ValueLayout.JAVA_INT,
+ ValueLayout.ADDRESS,
+ ValueLayout.JAVA_LONG),
+ captureCallState
+ );
+
+ static final MethodHandle OPEN_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("open").orElseThrow(() ->
+ new UnsatisfiedLinkError("open not found in STDLIB")),
+ FunctionDescriptor.of(
+ ValueLayout.JAVA_INT
+ ,ValueLayout.ADDRESS // pathName
+ ,ValueLayout.JAVA_INT // flags
+ ,ValueLayout.JAVA_INT), // mode
+ captureCallState
+ );
+
+ static final MethodHandle CLOSE_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("close").orElseThrow(() ->
+ new UnsatisfiedLinkError("close not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT
+ ,ValueLayout.JAVA_INT),
+ captureCallState
+ );
+
+ static final MethodHandle FALLOCATE_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("fallocate").orElseThrow(() ->
+ new UnsatisfiedLinkError("fallocate not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT,
+ ValueLayout.JAVA_INT,
+ ValueLayout.JAVA_INT,
+ ValueLayout.JAVA_LONG,
+ ValueLayout.JAVA_LONG
+ ),
+ captureCallState
+ );
+
+ static final MethodHandle FSYNC_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("fsync").orElseThrow(() ->
+ new UnsatisfiedLinkError("fsync not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT),
+ captureCallState
+ );
+
+ static final MethodHandle LSEEK_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("lseek").orElseThrow(() ->
+ new UnsatisfiedLinkError("lseek not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.JAVA_LONG,
+ ValueLayout.JAVA_INT,
+ ValueLayout.JAVA_LONG,
+ ValueLayout.JAVA_INT),
+ captureCallState
+ );
+
+ static final MethodHandle FSTAT_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("fstat").orElseThrow(() ->
+ new UnsatisfiedLinkError("fstat not found in STDLIB")),
+ FunctionDescriptor.of(
+ ValueLayout.JAVA_INT, // return
+ ValueLayout.JAVA_INT, // fd
+ ValueLayout.ADDRESS), // struct stat
+ captureCallState
+ );
+
+ // for x86_64 - stat
+ static final MethodHandle STAT_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("stat").orElseThrow(() ->
+ new UnsatisfiedLinkError("stat not found in STDLIB")),
+ FunctionDescriptor.of(
+ ValueLayout.JAVA_INT, // return
+ ValueLayout.ADDRESS, // pathname
+ ValueLayout.ADDRESS), // struct stat
+ captureCallState
+ );
+
+ static final MethodHandle IO_GETEVENTS_HANDLE = LINKER.downcallHandle(
+ LIBAIO.find("io_getevents").orElseThrow(() ->
+ new UnsatisfiedLinkError("io_getevents not found in LIBAIO")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT,
+ ValueLayout.ADDRESS,
+ ValueLayout.JAVA_LONG,
+ ValueLayout.JAVA_LONG,
+ ValueLayout.ADDRESS,
+ ValueLayout.ADDRESS),
+ captureCallState
+ );
+
+ static final MethodHandle IO_SUBMIT_HANDLE = LINKER.downcallHandle(
+ LIBAIO.find("io_submit").orElseThrow(() ->
+ new UnsatisfiedLinkError("io_submit not found in LIBAIO")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT,
+ ValueLayout.ADDRESS,
+ ValueLayout.JAVA_LONG,
+ ValueLayout.ADDRESS),
+ captureCallState
+ );
+
+ static final MethodHandle FREE_BUF_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("free").orElseThrow(() ->
+ new UnsatisfiedLinkError("free not found in STDLIB")),
+ FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)
+ );
+
+ static final MethodHandle FLOCK_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("flock").orElseThrow(() ->
+ new UnsatisfiedLinkError("flock not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT,
+ ValueLayout.JAVA_INT,
+ ValueLayout.JAVA_INT),
+ captureCallState
+ );
+
+ static final MethodHandle IO_QUEUE_INIT_HANDLE = LINKER.downcallHandle(
+ LIBAIO.find("io_queue_init").orElseThrow(() ->
+ new UnsatisfiedLinkError("io_queue_init not found in LIBAIO")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT,
+ ValueLayout.JAVA_INT,
+ ValueLayout.ADDRESS),
+ captureCallState
+ );
+
+ static final MethodHandle IO_QUEUE_RELEASE_HANDLE = LINKER.downcallHandle(
+ LIBAIO.find("io_queue_release").orElseThrow(() ->
+ new UnsatisfiedLinkError("io_queue_release not found in LIBAIO")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT,
+ ValueLayout.ADDRESS),
+ captureCallState
+ );
+
+ static final MethodHandle FDATASYNC_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("fdatasync").orElseThrow(() ->
+ new UnsatisfiedLinkError("fdatasync not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT),
+ captureCallState
+ );
+
+ static final MethodHandle MEMSET_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("memset").orElseThrow(() ->
+ new UnsatisfiedLinkError("memset not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.ADDRESS,
+ ValueLayout.ADDRESS,
+ ValueLayout.JAVA_INT,
+ ValueLayout.JAVA_LONG)
+ );
+
+ static final MethodHandle POSIX_MEMALIGN_HANDLE = LINKER.downcallHandle(
+ STDLIB.find("posix_memalign").orElseThrow(() ->
+ new UnsatisfiedLinkError("posix_memalign not found in STDLIB")),
+ FunctionDescriptor.of(ValueLayout.JAVA_INT,
+ ValueLayout.ADDRESS,
+ ValueLayout.JAVA_LONG,
+ ValueLayout.JAVA_LONG),
+ Linker.Option.captureCallState("errno")
+ );
+
+ private static SymbolLookup setStdLib() {
+ String[] libcPaths = {
+ "/lib64/libc.so.6",
+ "/usr/lib64/libc.so.6",
+ "/lib/x86_64-linux-gnu/libc.so.6",
+ "libc.so.6"
+ };
+ for(String path: libcPaths) {
+ SymbolLookup loopup = SymbolLookup.libraryLookup(path, Arena.global());
+ if(loopup != null){
+ return loopup;
+ }
+ }
+ throw new RuntimeException("libc.so.6 not found");
+ }
+
+ private static SymbolLookup setLibaio() {
+ String[] paths = {
+ System.getProperty("libaio.path"),
+ "/usr/lib64/libaio.so.1",
+ "/usr/lib/x86_64-linux-gnu/libaio.so.1",
+ "/lib64/libaio.so.1",
+ "/usr/lib/libaio.so.1",
+ "libaio.so.1"
+ };
+ for (String path: paths) {
+ if(path != null && !path.isEmpty()) {
+ SymbolLookup lookup = SymbolLookup.libraryLookup(path, Arena.global());
+ if(lookup != null) {
+ return lookup;
+ }
+ }
+ }
+ throw new RuntimeException("libaio.so.1 not found");
+ }
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java
new file mode 100644
index 0000000..61c6f2b
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/FFMNativeHelper.java
@@ -0,0 +1,1083 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+import org.apache.activemq.artemis.nativo.jlibaio.SubmitInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.nio.ByteBuffer;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.AIORing.AIO_RING_HEADER_SIZE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.AIORing.AIO_RING_HEAD_VH;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.AIORing.AIO_RING_NR_VH;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.AIORing.AIO_RING_TAIL_VH;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.AIORing.hasUsableRing;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.AIORing.toAioRing;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.LOCK_EX;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.LOCK_NB;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.ONE_MEGA;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.O_CREAT;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.O_DIRECT;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.O_RDWR;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.PERMISSION_MODE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Constants.RING_REAPER;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.CAPTURE_STATE_LAYOUT;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.CLOSE_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.ERRNO_VH;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.FALLOCATE_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.FDATASYNC_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.FLOCK_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.FREE_BUF_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.FSTAT_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.STAT_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.FSYNC_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.IO_QUEUE_RELEASE_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.IO_GETEVENTS_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.IO_QUEUE_INIT_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.IO_SUBMIT_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.LSEEK_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.MEMSET_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.OPEN_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.POSIX_MEMALIGN_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.WRITE_HANDLE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.oneMegaMutex;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.IOCBInit.IOCB_LAYOUT_SIZE;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.IOEvent.IO_EVENT_LAYOUT;
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.Stat.STAT_LAYOUT;
+
+public class FFMNativeHelper<Callback extends SubmitInfo> {
+ private static final Logger logger = LoggerFactory.getLogger(FFMNativeHelper.class);
+
+ private static volatile MemorySegment oneMegaBuffer;
+
+ private static final AtomicBoolean forceSysCall = new AtomicBoolean(false);
+
+ private static final AtomicReference<Integer> DUMB_FD = new AtomicReference<>(-1);
+
+ private static volatile String DUMB_PATH;
+
+ private final static int DUMB_WRITE_HANDLER;
+
+ static {
+ DUMB_WRITE_HANDLER = initDumbFd();
+ }
+
+ private static int initDumbFd() {
+ try {
+ Integer fd = DUMB_FD.get();
+ if(fd != null && fd >= 0) {
+ logger.trace("Dumb FD already initialized: {}", fd);
+ return fd;
+ }
+ Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));
+ Path tempFile;
+ try {
+ tempFile = Files.createTempFile(tempDir, "artemisDumb", ".tmp");
+ DUMB_PATH = tempFile.toString();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to create temp file for shutdown signaling", e);
+ }
+ fd = open(DUMB_PATH, false);
+ if(fd < 0) {
+ Files.deleteIfExists(tempFile);
+ throw new RuntimeException("Failed to open dumb file: " + tempFile);
+ }
+
+ DUMB_FD.set(fd);
+ logger.debug("Dumb FD created: {}, path = {}", fd, DUMB_PATH);
+ return fd;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static void closeDumbFd() {
+ try {
+ Integer fd = DUMB_FD.getAndSet(-1);
+ if (fd != null && fd >= 0) {
+ try {
+ close(fd);
+ if (DUMB_PATH != null) {
+ Path path = Path.of(DUMB_PATH);
+ Files.deleteIfExists(path);
+ }
+ logger.debug("Dumb FD closed and file removed: fd={}, path={}", fd, DUMB_PATH);
+ } catch (IOException e) {
+ logger.warn("Failed to close/remove dumb FD {}: {}", fd, e.getMessage());
+ }
+ }
+ } finally {
+ DUMB_PATH = null;
+ }
+ }
+
+ private final CallbackRegistry<Callback> registry;
+
+ private final ReleaseCallback releaseCallback;
+
+ public FFMNativeHelper(ReleaseCallback releaseCallback) {
+ this.registry = new CallbackRegistry<>();
+ this.releaseCallback = releaseCallback;
+ }
+
+ //It implements a user space batch read io events implementation that attempts to read io avoiding any sys calls
+ // This implementation will look at the internal structure (aio_ring) and move along the memory result
+ private int ringioGetEvents(MemorySegment aioCtxAddr, MemorySegment events, int min, int max, MemorySegment timeout) throws Throwable {
+ if (aioCtxAddr == null || aioCtxAddr.address() == 0) {
+ logger.trace("ringioGetEvents: aioCtxAddr is null -> syscall");
+ return ioGetEvents(aioCtxAddr, events, min, max, timeout);
+ }
+
+ if (min < 0 || max <= 0 || min > max) {
+ logger.warn("ringioGetEvents: invalid parameters: min={}, max={}", min, max);
+ return ioGetEvents(aioCtxAddr, events, min, max, timeout);
+ }
+
+ MemorySegment ring = toAioRing(aioCtxAddr);
+ if(ring.address() == 0) {
+ logger.trace("toAioRing failed -> syscall");
+ return ioGetEvents(aioCtxAddr, events, min, max, timeout);
+ }
+
+ //checks if it could be completed in user space, saving a sys call
+ if(!(RING_REAPER && !isForceSyscall() && hasUsableRing(ring))) {
+ logger.trace("kernel not supporting ring buffer");
+ return ioGetEvents(aioCtxAddr, events, min, max, timeout);
+ }
+
+ int ringNr = (int) AIO_RING_NR_VH.getAcquire(ring, 0L);
+ if (ringNr <= 0) {
+ logger.trace("ringioGetEvents: invalid ring size {} -> syscall", ringNr);
+ return ioGetEvents(aioCtxAddr, events, min, max, timeout);
+ }
+
+ // We're assuming to be the exclusive writer to head, so we just need a compiler barrier
+ // instead of compiler barrier, using getAcquired
+ int head = (int) AIO_RING_HEAD_VH.getAcquire(ring, 0L);
+ int tail = (int) AIO_RING_TAIL_VH.getAcquire(ring, 0L);
+
+ int available = tail - head;
+ if(available < 0) {
+ available += ringNr;
+ }
+
+ logger.trace("tail={}, head={} nr={} available={}", tail, head, ringNr, available);
+
+ boolean timeoutZero = false;
+ if (timeout != null && timeout.address() != 0) {
+ timeoutZero = timeout.get(ValueLayout.JAVA_LONG, 0L) == 0
+ && timeout.get(ValueLayout.JAVA_LONG, 8L) == 0;
+ }
+
+ if (available < min && !timeoutZero) {
+ logger.trace("ringioGetEvents: not enough available events -> syscall");
+ return ioGetEvents(aioCtxAddr, events, min, max, timeout);
+ }
+
+ if (available == 0) {
+ return 0;
+ }
+
+ if(available >= max) {
+ // This is to trap a possible bug from the kernel:
+ // https://bugzilla.redhat.com/show_bug.cgi?id=1845326
+ // https://issues.apache.org/jira/browse/ARTEMIS-2800
+ //
+ // On the race available would eventually be >= max, while ring->tail was invalid
+ // we could work around by waiting ring-tail to change:
+ // while (ring->tail == tail) mem_barrier();
+ //
+ // however eventually we could have available==max in a legal situation what could lead to infinite loop here
+ logger.trace("ringioGetEvents: ring full ({}>= {}) → syscall", available, max);
+ return ioGetEvents(aioCtxAddr, events, min, max, timeout);
+
+ // also: I could have called io_getevents to the one at the end of this method
+ // but I really hate goto, so I would rather have a duplicate code here
+ // and I did not want to create another memory flag to stop the rest of the code
+ }
+
+ //the kernel has written ring->tail from an interrupt:
+ //we need to load acquire the completed events here
+
+ // available < max ( this is always true )
+ // old code -> int availableNr = available < max ? available : max;
+ //if isn't needed to wrap we can avoid % operations that are quite expansive
+ int needMod = ((head + available) >= ringNr) ? 1: 0;
+
+ long eventSize = IO_EVENT_LAYOUT.byteSize();
+ long requiredBytes;
+ try {
+ requiredBytes = Math.multiplyExact((long) max, eventSize);
+ } catch (ArithmeticException e) {
+ logger.warn("ringioGetEvents: overflow computing required event bytes max={}, eventSize={}",
+ max, eventSize);
+ return ioGetEvents(aioCtxAddr, events, min, max, timeout);
+ }
+
+ MemorySegment usableEvents = events.reinterpret(requiredBytes);
+
+ int eventIdx = head;
+ int contiguous = Math.min(available, ringNr - head);
+
+ // first contiguous chunk
+ for(int i=0; i<contiguous; i++) {
+ long eventOffset = AIO_RING_HEADER_SIZE + (long) (eventIdx + i) * eventSize;
+ MemorySegment srcEvent = ring.asSlice(eventOffset, eventSize);
+ MemorySegment dstEvent = usableEvents.asSlice((long) i * eventSize, eventSize);
+ dstEvent.copyFrom(srcEvent);
+ }
+
+ // wrap around chunk, if any
+ if (contiguous < available) {
+ for (int i = contiguous; i < available; i++) {
+ long eventOffset = AIO_RING_HEADER_SIZE + (long) (i - contiguous) * eventSize;
+ MemorySegment srcEvent = ring.asSlice(eventOffset, eventSize);
+ MemorySegment dstEvent = usableEvents.asSlice((long) i * eventSize, eventSize);
+ dstEvent.copyFrom(srcEvent);
+ }
+ }
+ //it allow the kernel to build its own view of the ring buffer size
+ //and push new events if there are any
+ int newHead = (head + available) % ringNr;
+ AIO_RING_HEAD_VH.setRelease(ring, 0L, newHead);
+
+ logger.trace("consumed non sys-call = {}", available);
+ return available;
+ }
+
+ private int ioGetEvents(MemorySegment aioCtx, MemorySegment events, long min,
+ long max, MemorySegment timeout) throws Throwable {
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+ // Direct syscall wrapper
+ int result = (int) IO_GETEVENTS_HANDLE.invoke(
+ captureState,
+ aioCtx,
+ min,
+ max,
+ events,
+ (timeout == null ? MemorySegment.NULL : timeout)
+ );
+
+ if(result < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ logger.warn("ioGetEvents: failed to call IO_GETEVENTS_HANDLE. result={}, errno={}", result, errno);
+ }
+ return result;
+ }
+ }
+
+ private static void freeOneMegaBuffer() {
+ oneMegaMutex.lock();
+ try {
+ if (oneMegaBuffer != null) {
+ freeBuffer(oneMegaBuffer);
+ oneMegaBuffer = null;
+ logger.debug("One mega buffer freed");
+ }
+ } finally {
+ oneMegaMutex.unlock();
+ }
+ }
+
+ public static void shutdownHook() {
+ logger.debug("FFMNativeHelper shutdown hook executing");
+ closeDumbFd();
+ freeOneMegaBuffer();
+ }
+
+ public static void setForceSyscall(boolean value) {
+ forceSysCall.set(value);
+ logger.info("forceSysCall={}", value);
+ }
+
+ public static boolean isForceSyscall() {
+ return forceSysCall.get() || !RING_REAPER;
+ }
+
+ public IOControl newContext(int queueSize) {
+ logger.debug("Initializing context with QueueSize={}", queueSize);
+
+ IOControl ioControl = new IOControl();
+ try {
+ MemorySegment ioContext = ioQueueInit(queueSize);
+ ioControl.setIoContext(ioContext);
+
+ MemorySegment events = Arena.global().allocate(IO_EVENT_LAYOUT, queueSize);
+ if(events.address() == 0) {
+ ioQueueRelease(ioContext);
+ throw new OutOfMemoryError("Arena allocation failed: events array(queueSize = " + queueSize + ")");
+ }
+ ioControl.setEvents(events);
+
+ MemorySegment[] iocbPool = new MemorySegment[queueSize];
+ for(int i=0; i<queueSize; i++) {
+ MemorySegment iocb = Arena.global().allocate(IOCBInit.IOCB_LAYOUT);
+ if(iocb.address() == 0) {
+ for (int j = 0; j < i; j++) {
+ if (iocbPool[j] != null && iocbPool[j].address() != 0) {
+ freeBuffer(iocbPool[j]);
+ }
+ }
+ destroyIOCBs(events, queueSize);
+ ioQueueRelease(ioContext);
+ throw new OutOfMemoryError(
+ String.format("Arena memory allocation failed: iocb[%d/%d]", i, queueSize));
+ }
+ IOCBInit.setAioData(iocb, 0L);
+ iocbPool[i] = iocb;
+ }
+ ioControl.setIocbPool(iocbPool);
+ ioControl.setQueueSize(queueSize);
+
+ logger.debug("Context created successfully: queueSize={}, ioContext=0x{}",
+ queueSize, Long.toHexString(ioContext.address()));
+ return ioControl;
+ } catch (Throwable t) {
+ logger.error("newContext failed: queueSize={}, error={}", queueSize, t.getMessage(), t);
+ throw new RuntimeException(t);
+ }
+ }
+
+ private void ioQueueRelease(MemorySegment ioContext) {
+ if (ioContext == null || ioContext.address() == 0) {
+ return;
+ }
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+ int result = (int) IO_QUEUE_RELEASE_HANDLE.invoke(captureState, ioContext);
+ if(result < 0) {
+ logger.warn("io_queue_release(0x{}) failed: errno={}",
+ Long.toHexString(ioContext.address()), ERRNO_VH.get(captureState, 0L));
+ } else {
+ logger.trace("io_queue_release(0x{}) successful",
+ Long.toHexString(ioContext.address()));
+ }
+ } catch (Throwable e) {
+ logger.warn("ioQueueRelease failed: error:{}", e.getMessage(), e);
+ }
+ }
+
+ private void destroyIOCBs(MemorySegment array, int size) throws Throwable {
+ destroyIOCBsBounded(array, size);
+ }
+
+ private void destroyIOCBsBounded(MemorySegment iocbArray, int upperBound) throws Throwable {
+ for(int i=0; i<upperBound; i++) {
+ MemorySegment iocb = iocbArray.getAtIndex(ValueLayout.ADDRESS, i);
+ if(iocb.address() != 0) {
+ freeBuffer(iocb);
+ }
+ }
+ freeBuffer(iocbArray);
+ }
+
+ private MemorySegment ioQueueInit(int queueSize) {
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment ctx = arena.allocate(ValueLayout.ADDRESS);
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+ int result = (int) IO_QUEUE_INIT_HANDLE.invokeExact(captureState, queueSize, ctx);
+ if(result < 0) {
+ throw new IOException("io_queue_init failed: " + ERRNO_VH.get(captureState, 0L));
+ }
+ long rawAddress = ctx.get(ValueLayout.JAVA_LONG, 0L);
+ logger.trace("ioQueueInit({}) → 0x{} (result={})",
+ queueSize, Long.toHexString(rawAddress), result);
+ return MemorySegment.ofAddress(rawAddress).reinterpret(1, Arena.global(),null);
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void deleteContext(IOControl ioControl) {
+ if(ioControl == null) {
+ logger.debug("deleteContext: null ioControl");
+ return;
+ }
+ if(!ioControl.isValid()) {
+ logger.warn("deleteContext: invalid ioControl");
+ return;
+ }
+ logger.debug("deleteContext: queueSize={}, ioContext=0x{}",
+ ioControl.queueSize(), Long.toHexString(ioControl.ioContext().address()));
+ try {
+ MemorySegment dumbIocb = ioControl.getIOCB();
+ if(dumbIocb == null || dumbIocb.address() == 0) {
+ throw new IOException("Not enough space in libaio queue during shutdown");
+ }
+ ioPrepPOp(dumbIocb, DUMB_WRITE_HANDLER, MemorySegment.NULL, 0L, 0L, 1);
+ IOCBInit.setAioData(dumbIocb, -1L);
+
+ if(!submit(ioControl, dumbIocb)) {
+ logger.warn("deleteContext: submit failed: Continuing cleanup");
+ return;
+ } else {
+ logger.debug("deleteContext: dumb write submitted (fd={})", DUMB_WRITE_HANDLER);
+ }
+
+ // to make sure the poll has finished
+ ioControl.withPollLock(()->{});
+
+ // To return any pending IOCBs
+ int drained = 0;
+ while (true) {
+ try {
+ int result = ringioGetEvents(ioControl.ioContext(), ioControl.events(), 0, 1, null);
+ if(result <= 0) {
+ logger.trace("deleteContext: drain complete (result={})", result);
+ break;
+ }
+ logger.debug("deleteContext: drained {} pending IOCBs", result);
+ MemorySegment events = ioControl.events();
+ events = events.reinterpret((long) result * IO_EVENT_LAYOUT.byteSize());
+ for (int i = 0; i < result; i++) {
+ MemorySegment event = events.asSlice(i * IO_EVENT_LAYOUT.byteSize(),
+ IO_EVENT_LAYOUT.byteSize());
+ MemorySegment iocbp = event.get(ValueLayout.ADDRESS, 8L);
+ if (iocbp != null && iocbp.address() != 0) {
+ ioControl.putIOCB(iocbp);
+ }
+ }
+ drained += result;
+ } catch (Throwable t) {
+ logger.warn("deleteContext: drain unexpected error: {}", t.getMessage());
+ break;
+ }
+ }
+ logger.trace("deleteContext: drained {} IOCBs under lock", drained);
+
+ ioQueueRelease(ioControl.ioContext());
+
+ MemorySegment[] iocbPool = ioControl.iocbPool();
+ if(iocbPool != null) {
+ for(MemorySegment iocb : iocbPool) {
+ if(iocb != null && iocb.address() != 0) {
+ freeBuffer(iocb);
+ }
+ }
+ }
+
+ freeBuffer(ioControl.events());
+ logger.debug("deleteContext completed successfully");
+ } catch (IOException e) {
+ logger.warn("deleteContext: {}", e.getMessage());
+ } catch (Throwable e) {
+ logger.error("deleteContext: unexpected error", e);
+ }
+ }
+
+ public static int open(String filePath, boolean direct) throws IOException {
+ int flags = O_RDWR | O_CREAT;
+ if (direct) {
+ flags |= O_DIRECT;
+ logger.debug("Opening with O_DIRECT= {}", Integer.toHexString(O_DIRECT));
+ }
+ try (Arena arena = Arena.ofConfined()) {
+ // manually ensuring null termination by adding "\0"
+ MemorySegment path = arena.allocateFrom(filePath + "\0");
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+
+ int fd = (int) OPEN_HANDLE.invoke(captureState, path, flags, (int) PERMISSION_MODE);
+
+ if (fd < 0) {
+ int errorCode = (int) ERRNO_VH.get(captureState, 0L);
+ logger.error("open failed: path={}, flags={}, direct={}, errno={}",
+ filePath, Integer.toHexString(flags), direct, errorCode);
+ throw new IOException("Open failed for filePath = "
+ + filePath + " with fd errno = " + errorCode);
+ }
+ logger.debug("Opened {} with fd = {}", direct ? "O_DIRECT" : "normal", fd);
+ return fd;
+ } catch (Throwable t) {
+ throw new IOException("Failed to open " + filePath, t);
+ }
+ }
+
+ public static void close(int fd) throws IOException {
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+
+ int res = (int) CLOSE_HANDLE.invoke(captureState, fd);
+
+ if (res < 0) {
+ int errorCode = (int) ERRNO_VH.get(captureState, 0L);
+ throw new IOException("Error during close for fd = " + fd
+ + ", error code = " + errorCode);
+ }
+ logger.debug("File with fd = {} is successfully closed", fd);
+ } catch (Throwable t) {
+ throw new IOException(t);
+ }
+ }
+
+ public static MemorySegment newAlignedBuffer(int size, int alignment) {
+ if(size % alignment != 0) {
+ throw new IllegalArgumentException(
+ "size " + size + " must be aligned to " + alignment);
+ }
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment prtOut = arena.allocate(ValueLayout.ADDRESS);
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+
+ int res = (int) POSIX_MEMALIGN_HANDLE.invoke(
+ captureState, prtOut, (long) alignment, (long) size);
+ if(res != 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ throw new RuntimeException("posix_memalign failed: result= " + res
+ + " errno=" + errno + "(size= " + size + ", align= " + alignment + ")");
+ }
+ // get allocated pointer
+ MemorySegment memorySegment = prtOut.get(ValueLayout.ADDRESS, 0L)
+ .reinterpret(size);
+ if(memorySegment.address() == 0) {
+ throw new RuntimeException("posix_memalign returned NULL!");
+ }
+ //zero initialization
+ MEMSET_HANDLE.invoke(memorySegment, 0, (long) size);
+ logger.debug("posix_memalign(addrs={}, size={}, align={})",
+ Long.toHexString(memorySegment.address()), size, alignment);
+ return memorySegment;
+ } catch (Throwable t) {
+ throw new RuntimeException("newAlignedBuffer failed", t);
+ }
+ }
+
+ public static void freeBuffer(MemorySegment memorySegment) {
+ if(memorySegment == null || memorySegment.address() == 0) {
+ logger.debug("freeBuffer: memorySegment is null");
+ }
+ try {
+ if(logger.isTraceEnabled()) {
+ logger.trace("freeing buffer at address: 0x{} with capacity={}",
+ Long.toHexString(memorySegment.address()), memorySegment.asByteBuffer().capacity());
+ }
+ FREE_BUF_HANDLE.invoke(memorySegment);
+ } catch (Throwable t) {
+ throw new RuntimeException("freeBuffer: Native free failed for address 0x" +
+ Long.toHexString(memorySegment.address()), t);
+ }
+ }
+
+ private boolean submit(IOControl ioControl, MemorySegment iocb) throws IOException {
+ Objects.requireNonNull(ioControl.ioContext(), "Attempted to submit I/O to a null context");
+ int result = -1;
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+// int currIdx = (ioControl.iocbGet() + ioControl.queueSize() - 1) % ioControl.queueSize();
+// MemorySegment pointerInArray = ioControl.iocbArrayWithSize()
+// .asSlice((long) currIdx * 8L, 8L);
+
+ MemorySegment iocbArray = arena.allocate(ValueLayout.ADDRESS, 1);
+ iocbArray.setAtIndex(ValueLayout.JAVA_LONG, 0, iocb.address());
+
+ logger.trace("submit: ctx=0x{}, iocb=0x{}, iocbArray=0x{}",
+ Long.toHexString(ioControl.ioContext().address()),
+ Long.toHexString(iocb.address()),
+ Long.toHexString(iocbArray.address()));
+
+ result = (int) IO_SUBMIT_HANDLE.invoke(captureState,
+ ioControl.ioContext(),
+ 1L,
+ iocbArray);
+
+ if(result < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ throw new IOException("Error while submitting IO: errno = " + errno);
+ }
+ return true;
+ } catch (Throwable t) {
+ throw new IOException(t);
+ } finally {
+ if(result < 0) {
+ // return to the pool
+ ioControl.putIOCB(iocb);
+ }
+ }
+ }
+
+ public void submitWrite(int fd,
+ IOControl ioControl,
+ long position,
+ int size,
+ ByteBuffer bufferWrite,
+ Callback callback) throws IOException {
+
+ MemorySegment iocb = ioControl.getIOCB();
+ if(iocb == null || iocb.address() == 0) {
+ throw new IOException("IOCB pool exhausted (used=" + ioControl.used() +
+ "/queueSize=" + ioControl.queueSize() + ")");
+ }
+ logger.trace("submitWrite called!");
+ long callbackId = registry.register(callback);
+ boolean submitted = false;
+ try {
+ bufferWrite.clear();
+ ioPrepPOp(iocb, fd, MemorySegment.ofBuffer(bufferWrite), size, position, 1);
+
+ IOCBInit.setAioData(iocb, callbackId);
+ submit(ioControl, iocb);
+ submitted = true;
+ } catch (Throwable e) {
+ throw new IOException("submitWrite failed", e);
+ } finally {
+ if(!submitted) {
+ registry.removeCallbackById(callbackId);
+ }
+ }
+ }
+
+ /*
+ * Unable to load io_prep_pwrite and io_prep_pread from libaio because it is defined as a static inline function
+ * in the <libaio.h> header file
+ * Because it is an inline function, the code is compiled directly into any C program that
+ * includes the header. It does not exist as a named symbol inside the copiled libaio.so shared lib file.
+ *
+ * 0: IO_CMD_PREAD
+ * 1: IO_CMD_PWRITE
+ * 2: IO_CMD_FSYNC
+ * 3: IO_CMD_FDSYNC
+ * 7: IO_CMD_NOOP
+ * 8: IO_CMD_PREADV (Vectorized read)
+ *
+ * */
+ private void ioPrepPOp(MemorySegment iocb, int fd, MemorySegment buffer, long nbytes, long offset, int op) {
+ if (iocb == null) {
+ logger.trace("ioPrepPOp: iocb is null");
+ return;
+ }
+ IOCBInit.setAioFildes(iocb, fd);
+ IOCBInit.setAioLioOpcode(iocb, (short) op);
+ IOCBInit.setAioReqprio(iocb, (short) 0);
+ IOCBInit.setAioBuf(iocb, buffer.address());
+ IOCBInit.setAioNbytes(iocb, nbytes);
+ IOCBInit.setAioOffset(iocb, offset);
+ }
+
+ public void submitRead(int fd,
+ IOControl ioControl,
+ long position,
+ int size,
+ ByteBuffer bufferWrite,
+ Callback callback) throws IOException {
+
+ MemorySegment iocb = ioControl.getIOCB();
+ if(iocb==null || iocb.address() == 0) {
+ throw new IOException("IOCB pool exhausted");
+ }
+
+ logger.trace("submitRead called!");
+ long callbackId = registry.register(callback);
+ boolean submitted = false;
+ try {
+ bufferWrite.clear();
+ ioPrepPOp(iocb, fd, MemorySegment.ofBuffer(bufferWrite), size, position, 0);
+
+ IOCBInit.setAioData(iocb, callbackId);
+ submit(ioControl, iocb);
+ submitted = true;
+ } catch (Throwable e) {
+ throw new IOException("submitRead failed", e);
+ } finally {
+ if(!submitted) {
+ registry.removeCallbackById(callbackId);
+ }
+ }
+ }
+
+ public int poll(IOControl ioControl, Callback[] callbacks, int min, int max) {
+ if(ioControl == null || !ioControl.isValid()) {
+ logger.warn("poll: invalid context");
+ return 0;
+ }
+
+ try {
+ int result = ringioGetEvents(ioControl.ioContext(), ioControl.events(), min, max, null);
+ logger.trace("poll harvested {} events (min={}, max={})", result, min, max);
+ if(result <= 0) {
+ return result;
+ }
+
+ MemorySegment events = ioControl.events();
+ if(!events.scope().isAlive()) {
+ logger.error("Poll:: CRITICAL: Events segment is closed before polling!");
+ return 0;
+ }
+
+ events = events.reinterpret((long) result * IO_EVENT_LAYOUT.byteSize());
+ for(int i=0; i<result; i++) {
+ MemorySegment event = events.asSlice(i * IO_EVENT_LAYOUT.byteSize(),
+ IO_EVENT_LAYOUT.byteSize());
+ MemorySegment iocbp = event.get(ValueLayout.ADDRESS, 8L)
+ .reinterpret(64);
+ int eventResult = (int) event.get(ValueLayout.JAVA_LONG, 16L);
+ logger.trace("poll[{}]: res={}, iocbp=0x{}", i, eventResult, Long.toHexString(iocbp.address()));
+
+ if(eventResult < 0) {
+ logger.warn("poll[{}]: I/O error: {}", i, eventResult);
+ }
+
+ long callbackIdRaw = IOCBInit.getAioData(iocbp);
+ if(callbackIdRaw == 0L || callbackIdRaw == -1L) {
+ logger.warn("poll[{}]: invalid callback=0x{}", i, Long.toHexString(callbackIdRaw));
+ ioControl.putIOCB(iocbp);
+ continue;
+ }
+
+ Callback callback = registry.findCallbackById(callbackIdRaw);
+ if(callback != null) {
+ callbacks[i] = callback;
+ if(eventResult < 0) {
+ callback.onError(eventResult, "I/O error");
+ } else {
+ callback.done();
+ }
+ if (releaseCallback != null) {
+ releaseCallback.release();
+ }
+ registry.removeCallbackById(callbackIdRaw);
+ } else {
+ logger.warn("poll[{}]: callback not found for id=0x{}",
+ i, Long.toHexString(callbackIdRaw));
+ }
+ ioControl.putIOCB(iocbp);
+ }
+ return result;
+ } catch (Throwable e) {
+ logger.error("poll failed", e);
+ return -1;
+ }
+ }
+
+ public void blockedPoll(IOControl ioControl, boolean useFdatasync) {
+ logger.debug("blockedPoll starting(useFdatasync={})", useFdatasync);
+ if(ioControl == null || !ioControl.isValid()) {
+ logger.warn("blockedPoll: invalid context");
+ return;
+ }
+
+ ioControl.withPollLock(()->{
+ try(Arena arena = Arena.ofConfined()) {
+ boolean running = true;
+ int lastFile = -1;
+
+ while(running) {
+ if(!ioControl.isValid()) {
+ logger.debug("blockedPoll: context destroyed - self-exit");
+ break;
+ }
+ int result = ringioGetEvents(ioControl.ioContext(),
+ ioControl.events(), 1, ioControl.queueSize(), null);
+ if(result == -4) {
+ logger.trace("blockedPoll: EINTR - ignoring (jmap?)");
+ continue;
+ }
+
+ if(result < 0) {
+ logger.error("blockedPoll: ringio_get_events failed: {}", result);
+ throw new IOException("blockedPoll: ringio_get_events failed:" + result);
+ }
+
+ logger.trace("blockedPoll returned: {} events", result);
+ lastFile = -1;
+
+ MemorySegment harvestedEvents = ioControl.events()
+ .reinterpret((long) result * IO_EVENT_LAYOUT.byteSize());
+
+ for(int i=0; i<result; i++) {
+
+ MemorySegment event = harvestedEvents
+ .asSlice(i * IO_EVENT_LAYOUT.byteSize(),
+ IO_EVENT_LAYOUT.byteSize());
+ MemorySegment iocbp = IOEvent.getObj(event)
+ .reinterpret(IOCB_LAYOUT_SIZE);
+
+ int fd = IOCBInit.getAioFildes(iocbp);
+ if(fd == DUMB_WRITE_HANDLER ) {
+ logger.trace("blockedPoll: shutdown signal detected (dumb fd={})", fd);
+ ioControl.putIOCB(iocbp);
+ running = false;
+ break;
+ }
+
+ if(useFdatasync && lastFile != fd) {
+ lastFile = fd;
+ fdatasync(arena, fd);
+ }
+
+ int eventResult = (int) event.get(ValueLayout.JAVA_LONG, 16L);
+
+ long callbackIdRaw = IOCBInit.getAioData(iocbp);
+ logger.trace("blockedPoll: callbackIdRaw: {}", callbackIdRaw);
+ IOCBInit.setAioData(iocbp, 0L); // this is to detect invalid elements on the buffer.
+
+ if(callbackIdRaw != 0L) {
+ ioControl.putIOCB(iocbp);
+ Callback callback = registry.findCallbackById(callbackIdRaw);
+ if (callback != null) {
+ if (eventResult < 0) {
+ logger.error("blockedPoll[{}]: I/O error fd={}, {}", i, fd, eventResult);
+ callback.onError(eventResult, "I/O error in blockedPoll");
+ } else {
+ callback.done();
+ logger.trace("callback executed!");
+ }
+ if (releaseCallback != null) {
+ releaseCallback.release();
+ }
+ registry.removeCallbackById(callbackIdRaw);
+ }
+ } else {
+ if(!forceSysCall.get()) {
+ logger.warn("blockedPoll: Warning from ActiveMQ Artemis Native Layer: Your system is hitting duplicate / invalid records from libaio, which is a bug on the Linux Kernel you are using.You should set property org.apache.activemq.artemis.native.jlibaio.FORCE_SYSCALL=1 or upgrade to a kernel version that contains a fix");
+ }
+ setForceSyscall(true);
+ }
+ }
+ }
+ } catch (Throwable e) {
+ logger.error("blockedPoll error", e);
+ }
+ });
+ logger.debug("blockedPoll completed");
+ }
+
+ private static void fdatasync(Arena arena, int fd) throws Throwable {
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+ int res = (int) FDATASYNC_HANDLE.invoke(captureState, fd);
+ if(res < 0) {
+ throw new IOException("fdatasync(fd = " + fd + ") failed, errno: "
+ + ERRNO_VH.get(captureState, 0L));
+ }
+ }
+
+ public static int getNativeVersion() {
+ return 200;
+ }
+
+ public static boolean lock(int fd) {
+ if (fd < 0) {
+ return false;
+ }
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+ int result = (int) FLOCK_HANDLE.invokeExact(captureState,
+ fd, LOCK_EX | LOCK_NB);
+ return result == 0;
+ } catch (Throwable t) {
+ logger.warn("lock(fd={}) failed", fd);
+ return false;
+ }
+ }
+
+ public static void memsetBuffer(ByteBuffer buffer, int size) {
+ if(!buffer.isDirect()) {
+ throw new IllegalArgumentException("libaio requires NativeBuffer (Direct ByteBuffer)");
+ }
+ if (size <= 0 || size > buffer.capacity()) {
+ throw new IllegalArgumentException("Invalid size: " + size +
+ " (capacity = " + buffer.capacity() + ")");
+ }
+
+ try(Arena arena = Arena.ofConfined()) {
+ ByteBuffer dup = buffer.duplicate();
+ dup.clear();
+ MemorySegment seg = MemorySegment.ofBuffer(dup);
+ long addr = seg.address();
+ logger.trace("memset(buffer={}, size={})", buffer, size);
+ MemorySegment nativeSeg = MemorySegment
+ .ofAddress(addr)
+ .reinterpret(buffer.capacity());
+ // memset(buffer, 0, size)
+ MemorySegment ignore = (MemorySegment) MEMSET_HANDLE.invokeExact(nativeSeg, 0, (long) size);
+ logger.trace("memset completed!");
+ } catch (Throwable t){
+ throw new RuntimeException("memset failed", t);
+ }
+ }
+
+ public static long getSize(int fd) throws IOException {
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment statbuf = arena.allocate(STAT_LAYOUT);
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+
+ int res = (int) FSTAT_HANDLE.invokeExact(
+ captureState,
+ fd,
+ statbuf);
+ if (res < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ throw new IOException("fstat failed for fd=" + fd + ": errno=" + errno);
+ }
+
+ long size = Stat.getSize(statbuf);
+ logger.debug("getSize(fd = {}): {} bytes", fd, size);
+ return size;
+ } catch (Throwable t) {
+ throw new IOException("getSize failed for fd = " + fd, t);
+ }
+ }
+
+ public static int getBlockSizeFD(int fd) throws IOException {
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment statbuf = arena.allocate(STAT_LAYOUT);
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+ int res = (int) FSTAT_HANDLE.invokeExact(
+ captureState,
+ fd,
+ statbuf);
+ if (res < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ throw new IOException("fstat failed for fd=" + fd + ": errno=" + errno);
+ }
+
+ int blksize = Stat.getBlksize(statbuf);
+ if (blksize <= 0 || blksize > 65536) {
+ logger.warn("Invalid st_blksize={} for fd={}, using 4096", blksize, fd);
+ return 4096;
+ }
+ logger.trace("getBlockSizeFD(fd = {}) = {} bytes", fd, blksize);
+ return blksize;
+ } catch (Throwable t) {
+ throw new IOException("getBlockSizeFD failed for fd=" + fd, t);
+ }
+ }
+
+ public static int getBlockSize(String path) throws IOException {
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment pathSeg = arena.allocateFrom(path);
+ MemorySegment statbuf = arena.allocate(STAT_LAYOUT);
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+ int res = (int) STAT_HANDLE.invokeExact(
+ captureState,
+ pathSeg,
+ statbuf);
+ if(res < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ throw new IOException("statx failed path=" + path + ": errno = " + errno);
+ }
+ int blksize = Stat.getBlksize(statbuf);
+ if (blksize <= 0 || blksize > 65536) {
+ logger.warn("Invalid st_blksize={} for path={}, using 4096", blksize, path);
+ return 4096;
+ }
+ logger.trace("getBlockSize(path = {}) = {} bytes", path, blksize);
+ return blksize;
+ } catch (Throwable t) {
+ logger.warn("getBlockSize failed '{}', fallback 4096", path, t);
+ return 4096;
+ }
+ }
+
+ public static void fallocate(int fd, long size) throws IOException {
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+
+ // fallocate(fd, mode=0, offset=0, len=size)
+ int res = (int) FALLOCATE_HANDLE.invoke(captureState, fd, 0, 0L, size);
+ if(res < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ throw new IOException("fallocate failed fd="
+ + fd + " size="
+ + size + ": errno= "
+ + errno);
+ }
+ // fsync(fd) - ensure allocation hits the disk
+ res = (int) FSYNC_HANDLE.invoke(captureState, fd);
+ if(res < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ logger.warn("fsync after allocation failed fd={}: errno={}", fd, errno);
+ }
+ //lseek(fd, 0, SEEK_SET) - reset position
+ long pos = (long) LSEEK_HANDLE.invoke(captureState, fd, 0L, 0);
+ if(pos < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ logger.warn("lseek reset failed fd={}: errno={}", fd, errno);
+ }
+ logger.debug("fallocate(fd={}, size={}) + fsync + lseek(reset)", fd, size);
+ } catch (Throwable t) {
+ throw new IOException("fallocate failed fd="+ fd + " size=" + size, t);
+ }
+ }
+
+ private static MemorySegment verifyBuffer(int alignment) {
+ oneMegaMutex.lock();
+ try {
+ if (oneMegaBuffer == null) {
+ logger.debug("Allocating 1MB shared buffer (align={})", alignment);
+ oneMegaBuffer = newAlignedBuffer((int) ONE_MEGA, alignment);
+ }
+ return oneMegaBuffer;
+ } finally {
+ oneMegaMutex.unlock();
+ }
+ }
+
+ public static void fill(int fd, int alignment, long size) throws IOException {
+ logger.debug("fill(fd={}, alignment={}, size={})", fd, alignment, size);
+
+ long blocks = size / ONE_MEGA;
+ long rest = size % ONE_MEGA;
+
+ //verify/create 1MB buffer
+ verifyBuffer(alignment);
+
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment captureState = arena.allocate(CAPTURE_STATE_LAYOUT);
+ // lseek (fd, 0, SEEK_SET)
+ LSEEK_HANDLE.invoke(captureState, fd, 0L, 0);
+ //Write full blocks
+ for (long i=0; i<blocks; i++) {
+ MemorySegment bufferAddrs = oneMegaBuffer;
+ long written = (long) WRITE_HANDLE.invoke(captureState, fd, bufferAddrs, ONE_MEGA);
+ if (written < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ throw new IOException("write failed block " + i + ": errno= " + errno);
+ }
+ }
+
+ // Remainder
+ if (rest > 0) {
+ MemorySegment bufferAddrs = oneMegaBuffer;
+ long written = (long) WRITE_HANDLE.invoke(captureState, fd, bufferAddrs, rest);
+ if (written < 0) {
+ int errno = (int) ERRNO_VH.get(captureState, 0L);
+ throw new IOException("write rest failed: errno= " + errno);
+ }
+ }
+
+ //Reset position
+ LSEEK_HANDLE.invoke(captureState, fd, 0L, 0);
+ } catch (Throwable t) {
+ throw new IOException("fill failed fd=" + fd + " size=" + size, t);
+ }
+ logger.debug("fill completed: {} bytes written.", size);
+ }
+
+ public static void writeInternal(int fd, long position, long size, ByteBuffer bufferWrite) throws IOException {
+ // No Impl
+ }
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOCBInit.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOCBInit.java
new file mode 100644
index 0000000..e4ed0d3
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOCBInit.java
@@ -0,0 +1,140 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+import java.lang.foreign.MemoryLayout;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+
+public class IOCBInit {
+ public static final int IOCB_LAYOUT_SIZE = 64;
+ public static final MemoryLayout IOCB_LAYOUT = MemoryLayout.structLayout(
+ ValueLayout.JAVA_LONG.withName("aio_data"),
+ ValueLayout.JAVA_INT.withName("aio_key"),
+ ValueLayout.JAVA_INT.withName("aio_rw_flags"),
+ ValueLayout.JAVA_SHORT.withName("aio_lio_opcode"),
+ ValueLayout.JAVA_SHORT.withName("aio_reqprio"),
+ ValueLayout.JAVA_INT.withName("aio_fildes"),
+ ValueLayout.JAVA_LONG.withName("aio_buf"),
+ ValueLayout.JAVA_LONG.withName("aio_nbytes"),
+ ValueLayout.JAVA_LONG.withName("aio_offset"),
+ ValueLayout.JAVA_LONG.withName("aio_reserved2"),
+ ValueLayout.JAVA_INT.withName("aio_flags"),
+ ValueLayout.JAVA_INT.withName("aio_resfd")
+ ).withByteAlignment(8).withName("iocb");
+
+ public static final long AIO_DATA = 0;
+ public static final long AIO_KEY = 8;
+ public static final long AIO_RW_FLAGS = 12;
+ public static final long AIO_LIO_OPCODE = 16;
+ public static final long AIO_REQPRIO = 18;
+ public static final long AIO_FILDES = 20;
+ public static final long AIO_BUF = 24;
+ public static final long AIO_NBYTES = 32;
+ public static final long AIO_OFFSET = 40;
+ public static final long AIO_RESERVED2 = 48;
+ public static final long AIO_FLAGS = 56;
+ public static final long AIO_RESFD = 60;
+
+ public static long getAioData(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_LONG, AIO_DATA);
+ }
+
+ public static void setAioData(MemorySegment iocb, long value) {
+ iocb.set(ValueLayout.JAVA_LONG, AIO_DATA, value);
+ }
+
+ public static int getAioKey(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_INT, AIO_KEY);
+ }
+
+ public static void setAioKey(MemorySegment iocb, int value) {
+ iocb.set(ValueLayout.JAVA_INT, AIO_KEY, value);
+ }
+
+ public static int getAioRwFlags(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_INT, AIO_RW_FLAGS);
+ }
+
+ public static void setAioRwFlags(MemorySegment iocb, int value) {
+ iocb.set(ValueLayout.JAVA_INT, AIO_RW_FLAGS, value);
+ }
+
+ public static short getAioLioOpcode(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_SHORT, AIO_LIO_OPCODE);
+ }
+
+ public static void setAioLioOpcode(MemorySegment iocb, short value) {
+ iocb.set(ValueLayout.JAVA_SHORT, AIO_LIO_OPCODE, value);
+ }
+
+ public static short getAioReqprio(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_SHORT, AIO_REQPRIO);
+ }
+
+ public static void setAioReqprio(MemorySegment iocb, short value) {
+ iocb.set(ValueLayout.JAVA_SHORT, AIO_REQPRIO, value);
+ }
+
+ public static int getAioFildes(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_INT, AIO_FILDES);
+ }
+
+ public static void setAioFildes(MemorySegment iocb, int value) {
+ iocb.set(ValueLayout.JAVA_INT, AIO_FILDES, value);
+ }
+
+ public static long getAioBuf(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_LONG, AIO_BUF);
+ }
+
+ public static void setAioBuf(MemorySegment iocb, long value) {
+ iocb.set(ValueLayout.JAVA_LONG, AIO_BUF, value);
+ }
+
+ public static long getAioNbytes(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_LONG, AIO_NBYTES);
+ }
+
+ public static void setAioNbytes(MemorySegment iocb, long value) {
+ iocb.set(ValueLayout.JAVA_LONG, AIO_NBYTES, value);
+ }
+
+ public static long getAioOffset(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_LONG, AIO_OFFSET);
+ }
+
+ public static void setAioOffset(MemorySegment iocb, long value) {
+ iocb.set(ValueLayout.JAVA_LONG, AIO_OFFSET, value);
+ }
+
+ public static int getAioFlags(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_INT, AIO_FLAGS);
+ }
+
+ public static void setAioFlags(MemorySegment iocb, int value) {
+ iocb.set(ValueLayout.JAVA_INT, AIO_FLAGS, value);
+ }
+
+ public static int getAioResfd(MemorySegment iocb) {
+ return iocb.get(ValueLayout.JAVA_INT, AIO_RESFD);
+ }
+
+ public static void setAioResfd(MemorySegment iocb, int value) {
+ iocb.set(ValueLayout.JAVA_INT, AIO_RESFD, value);
+ }
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOControl.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOControl.java
new file mode 100644
index 0000000..8777335
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOControl.java
@@ -0,0 +1,166 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.foreign.MemorySegment;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class IOControl {
+// private static final Logger logger = LoggerFactory.getLogger(IOControl.class);
+
+ private final Object iocbLock = new Object();
+ private final Object pollLock = new Object();
+
+ private MemorySegment ioContext;
+ private MemorySegment events;
+ private int queueSize;
+ private int iocbPut;
+ private int iocbGet;
+ private int used;
+ private MemorySegment[] iocbPool;
+
+ public MemorySegment ioContext() {
+ return this.ioContext;
+ }
+ public void setIoContext(MemorySegment ioContext) {
+ this.ioContext = ioContext;
+ }
+
+ public MemorySegment events() {
+ return this.events;
+ }
+ public void setEvents(MemorySegment events) {
+ this.events = events;
+ }
+
+ public int queueSize() {
+ return queueSize;
+ }
+ public void setQueueSize(int size) {
+ this.queueSize = size;
+ }
+
+ public int iocbPut() {
+ return this.iocbPut;
+ }
+ public int iocbGet() {
+ return this.iocbGet;
+ }
+ public int used() {
+ return this.used;
+ }
+
+ public MemorySegment[] iocbPool() {
+ return this.iocbPool;
+ }
+ public void setIocbPool(MemorySegment[] iocbPool) {
+ this.iocbPool = iocbPool;
+ }
+
+ public void withIocbLock(Runnable action) {
+ synchronized ( iocbLock){
+ action.run();
+ }
+ }
+
+ public void withPollLock(Runnable action) {
+ synchronized ( pollLock){
+ action.run();
+ }
+ }
+
+ public MemorySegment getIOCB() {
+ synchronized ( iocbLock){
+ final int qSize = this.queueSize;
+ if (qSize <= 0 || used >= qSize || iocbPool == null) {
+ return null;
+ }
+
+ final int idx = iocbGet;
+ if(idx < 0 || idx >= qSize) {
+ return null;
+ }
+
+ final MemorySegment seg = iocbPool[idx];
+ if(seg == null || seg.address() == 0L) {
+// logger.error("getIOCB: null IOCB at index {}", idx);
+ return null;
+ }
+
+ used++;
+ iocbGet = (idx + 1);
+ if(iocbGet >= qSize) {
+ iocbGet = 0;
+ }
+ return seg;
+ }
+ }
+
+ public void putIOCB(MemorySegment iocb) {
+ if(iocb == null || iocb.address() == 0L) {
+// logger.warn("putIOCB: null IOCB ignored");
+ return;
+ }
+ synchronized ( iocbLock) {
+ final int qSize = this.queueSize;
+ if (qSize <= 0 || used <= 0 || iocbPool == null) {
+ return;
+ }
+
+ int idx = this.iocbPut;
+ if(idx < 0 || idx >= qSize) {
+// logger.error("putIOCB: invalid putIdx={} queueSize={}",
+// idx, qSize);
+ return;
+ }
+
+ iocbPool[idx] = iocb;
+ used--;
+ iocbPut = (idx + 1);
+ if(iocbPut >= qSize) {
+ iocbPut = 0;
+ }
+ }
+ }
+
+ public boolean isValid() {
+ if(ioContext == null || ioContext.address() == 0) {
+ return false;
+ }
+ if(events == null || events.address() == 0) {
+ return false;
+ }
+
+ if(queueSize <= 0) {
+ return false;
+ }
+
+ if(used < 0 || used > queueSize) {
+ return false;
+ }
+
+ if(iocbPool == null || iocbPool.length != queueSize) {
+ return false;
+ }
+
+ return iocbPut >= 0 && iocbPut < queueSize &&
+ iocbGet >= 0 && iocbGet < queueSize;
+ }
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOEvent.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOEvent.java
new file mode 100644
index 0000000..62beb07
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/IOEvent.java
@@ -0,0 +1,55 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+import java.lang.foreign.MemoryLayout;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.StructLayout;
+import java.lang.foreign.ValueLayout;
+
+public class IOEvent {
+
+ public final static int IO_EVENT_LAYOUT_SIZE = 32;
+
+ static final StructLayout IO_EVENT_LAYOUT = MemoryLayout.structLayout(
+ ValueLayout.JAVA_LONG.withName("data"),
+ ValueLayout.ADDRESS.withName("obj"),
+ ValueLayout.JAVA_LONG.withName("res"),
+ ValueLayout.JAVA_LONG.withName("res2")
+ ).withName("io_event");
+
+ public static final long DATA = 0;
+ public static final long OBJ = 8;
+ public static final long RES = 16;
+ public static final long RES2 = 24;
+
+ public static long getData(MemorySegment ioEvent) {
+ return ioEvent.get(ValueLayout.JAVA_LONG, DATA);
+ }
+
+ public static void setData(MemorySegment ioEvent, long value) {
+ ioEvent.set(ValueLayout.JAVA_LONG, DATA, value);
+ }
+
+ public static MemorySegment getObj(MemorySegment ioEvent) {
+ return ioEvent.get(ValueLayout.ADDRESS, OBJ);
+ }
+
+ public static void setObj(MemorySegment ioEvent, MemorySegment value) {
+ ioEvent.set(ValueLayout.ADDRESS, OBJ, value);
+ }
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/ReleaseCallback.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/ReleaseCallback.java
new file mode 100644
index 0000000..5352f94
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/ReleaseCallback.java
@@ -0,0 +1,22 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+@FunctionalInterface
+public interface ReleaseCallback {
+ void release();
+}
diff --git a/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/Stat.java b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/Stat.java
new file mode 100644
index 0000000..a55be55
--- /dev/null
+++ b/src/main/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/Stat.java
@@ -0,0 +1,53 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm;
+
+import java.lang.foreign.MemoryLayout;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.StructLayout;
+import java.lang.foreign.ValueLayout;
+import java.lang.invoke.VarHandle;
+
+public final class Stat {
+
+ // this will work only for 64-bit linux
+ static final StructLayout STAT_LAYOUT = MemoryLayout.structLayout(
+ MemoryLayout.paddingLayout(48),
+ ValueLayout.JAVA_LONG.withName("st_size"), // File size (bytes)
+ ValueLayout.JAVA_INT.withName("st_blksize"), // Block size for filesystem I/O
+ ValueLayout.JAVA_INT.withName("__pad2"),
+ ValueLayout.JAVA_LONG.withName("st_blocks"), // Number of 512B blocks allocated
+ MemoryLayout.paddingLayout(192)
+ ).withName("stat")
+ .withByteAlignment(8L);
+
+ static final VarHandle ST_SIZE_VH = STAT_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("st_size"));
+ static final VarHandle ST_BLKSIZE_VH = STAT_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("st_blksize"));
+ static final VarHandle ST_BLOCKS_VH = STAT_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("st_blocks"));
+
+ public static long getSize(MemorySegment stat) {
+ return (long) ST_SIZE_VH.get(stat, 0L);
+ }
+
+ public static int getBlksize(MemorySegment stat) {
+ return (int) ST_BLKSIZE_VH.get(stat, 0L);
+ }
+
+ public static int getBlocks(MemorySegment stat) {
+ return (int) ST_BLOCKS_VH.get(stat, 0L);
+ }
+}
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/FFMNativeHelperTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/FFMNativeHelperTest.java
new file mode 100644
index 0000000..70608bf
--- /dev/null
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/FFMNativeHelperTest.java
@@ -0,0 +1,443 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm.test;
+
+import org.apache.activemq.artemis.nativo.jlibaio.SubmitInfo;
+import org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMNativeHelper;
+import org.apache.activemq.artemis.nativo.jlibaio.ffm.IOControl;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.SymbolLookup;
+import java.nio.ByteBuffer;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.FFMHandles.LIBAIO;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class FFMNativeHelperTest {
+ private static final Logger logger = LoggerFactory.getLogger(FFMNativeHelperTest.class);
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void libLoadInittest() {
+ logger.trace("@Test:: libLoadInittest");
+ String libName = System.getProperty("libaio.path", "libaio.so.1");
+ SymbolLookup libaio = SymbolLookup.libraryLookup(libName, Arena.global());
+ assertTrue(libaio.find("io_setup").isPresent());
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void libLoadtest() {
+ logger.trace("@Test:: libLoadtest");
+ assertTrue(LIBAIO.find("io_setup").isPresent());
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void testOpenCloseLifecycle() throws IOException, InterruptedException {
+ logger.trace("@Test:: testOpenCloseLifecycle");
+ Path testFile = Path.of("libaio-test.bin");
+ logger.info("Testing file: {}", testFile.toAbsolutePath());
+ try {
+ int fd = FFMNativeHelper.open(testFile.toString(), false);
+ long allocate = 16 * 1024 * 1024L;
+ FFMNativeHelper.fallocate(fd, allocate);
+ long size = FFMNativeHelper.getSize(fd);
+ assertEquals(allocate, size, "file size mismatch");
+
+ fd = FFMNativeHelper.open(testFile.toString(), true);
+ assertTrue(fd >= 0, "Failed to open with O_DIRECT");
+ logger.info("Opened fd={} WITH O_DIRECT", fd);
+
+ FFMNativeHelper.close(fd);
+ } finally {
+ // Cleanup
+ Files.deleteIfExists(testFile);
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void getBlockSizeFDTest() throws IOException {
+ logger.trace("@Test:: getBlockSizeFDTest");
+ Path testFile = Path.of("libaio-test.bin");
+ logger.info("Testing file: {}", testFile.toAbsolutePath());
+ try {
+ int fd = FFMNativeHelper.open(testFile.toString(), false);
+ long blockSize = FFMNativeHelper.getBlockSizeFD(fd);
+ assertTrue(blockSize > 512 && blockSize < 65536,
+ "Invalid blockSize = " + blockSize);
+ FFMNativeHelper.close(fd);
+ } finally {
+ // Cleanup
+ Files.deleteIfExists(testFile);
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void getBlockSizeTest() throws IOException {
+ logger.trace("@Test:: getBlockSizeTest");
+ Path testFile = Path.of("libaio-test.bin");
+ Files.write(testFile, new byte[4096]);
+ logger.info("Testing file: {}", testFile.toAbsolutePath());
+ try {
+ int fd = FFMNativeHelper.open(testFile.toString(), false);
+ int fdBlockSize = FFMNativeHelper.getBlockSizeFD(fd);
+ FFMNativeHelper.close(fd);
+
+ int pathBlockSize = FFMNativeHelper.getBlockSize(testFile.toString());
+ assertEquals(fdBlockSize, pathBlockSize, "FD vs Path block size mismatch");
+ } finally {
+ // Cleanup
+ Files.deleteIfExists(testFile);
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void memsetBufferTest() throws IOException {
+ logger.trace("@Test:: memsetBufferTest");
+ int blockSize = 4096;
+ ByteBuffer buffer = ByteBuffer.allocateDirect(blockSize * 2);
+ byte[] garbage = new byte[blockSize];
+ new Random().nextBytes(garbage);
+ buffer.put(garbage);
+
+ FFMNativeHelper.memsetBuffer(buffer, blockSize);
+ for(int i=0; i<blockSize; i++){
+ assertEquals(0, buffer.get(i), "Byte " + i + " is not Zeroed");
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void newAlignedBufferTest() throws IOException {
+ logger.trace("@Test:: newAlignedBufferTest");
+ int alignment = 4096;
+ int size = alignment * 4;
+
+ ByteBuffer buffer = FFMNativeHelper.newAlignedBuffer(size, alignment).asByteBuffer();
+ assertTrue(buffer.isDirect());
+ assertEquals(size, buffer.capacity());
+
+ MemorySegment addr = MemorySegment.ofBuffer(buffer);
+ long address = addr.address();
+
+ assertEquals(0, address % alignment, "Buffer not aligned to " + alignment);
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void testNewContextDeleteContextLifecycle() throws IOException {
+ logger.trace("@Test:: testNewContextDeleteContextLifecycle");
+ FFMNativeHelper<TestSubmitInfo> helper = new FFMNativeHelper<>(null);
+ IOControl context = null;
+ context = helper.newContext(10);
+ assertNotNull(context, "Context should not be null");
+ logger.info("Created context = {}", context);
+
+ helper.deleteContext(context);
+ logger.info("Context deleted successfully");
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void testSubmitWriteReadFullCycle() throws IOException, InterruptedException {
+ logger.trace("@Test:: testSubmitWriteReadFullCycle");
+ Path testFile = Path.of("aio-cycle-test.bin");
+ FFMNativeHelper<TestSubmitInfo> helper = new FFMNativeHelper<>(null);
+ IOControl context = null;
+ int fd = -1;
+ ByteBuffer writeBuffer = null, readBuffer = null;
+ try {
+ Files.deleteIfExists(testFile);
+ fd = FFMNativeHelper.open(testFile.toString(), true);
+ FFMNativeHelper.fallocate(fd, 4096);
+
+ context = helper.newContext(4);
+
+ byte[] testData = new byte[4096];
+ new Random(12345).nextBytes(testData);
+
+ writeBuffer = FFMNativeHelper.newAlignedBuffer(4096, 4096).asByteBuffer();
+ writeBuffer.put(testData).flip();
+
+ readBuffer = FFMNativeHelper.newAlignedBuffer(4096, 4096).asByteBuffer();
+
+ //Write
+ TestSubmitInfo writeCb = new TestSubmitInfo();
+ helper.submitWrite(fd, context, 0, 4096, writeBuffer, writeCb);
+
+ int events = helper.poll(context, new TestSubmitInfo[1], 1, 1);
+ assertEquals(1, events);
+ assertTrue(writeCb.isDone());
+ assertFalse(writeCb.hasError());
+
+ //Read
+ TestSubmitInfo readCb = new TestSubmitInfo();
+ helper.submitRead(fd, context, 0, 4096, readBuffer, readCb);
+
+ events = helper.poll(context, new TestSubmitInfo[1], 1, 1);
+ assertEquals(1, events);
+ assertTrue(readCb.isDone());
+ assertFalse(readCb.hasError());
+
+ //verify data
+ readBuffer.position(0);
+ byte[] readData = new byte[4096];
+ readBuffer.get(readData);
+ assertArrayEquals(testData, readData);
+ } finally {
+ if (context != null) {
+ helper.deleteContext(context);
+ }
+ if (fd >= 0) {
+ FFMNativeHelper.close(fd);
+ }
+ Files.deleteIfExists(testFile);
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void testPollMultipleEvents() throws IOException, InterruptedException {
+ logger.trace("@Test:: testPollMultipleEvents");
+ Path testFile = Path.of("multi-poll-test.bin");
+ FFMNativeHelper<TestSubmitInfo> helper = new FFMNativeHelper<>(null);
+ IOControl context = null;
+ int fd = -1;
+ TestSubmitInfo[] callBacks = new TestSubmitInfo[4];
+ MemorySegment[] nativeBuffers = new MemorySegment[4];
+ ByteBuffer[] buffers = new ByteBuffer[4];
+
+ try {
+ Files.deleteIfExists(testFile);
+ fd = FFMNativeHelper.open(testFile.toString(), true);
+ FFMNativeHelper.fallocate(fd, 8192);
+
+ context = helper.newContext(8);
+
+
+ for(int i=0; i<4; i++) {
+ callBacks[i] = new TestSubmitInfo();
+ nativeBuffers[i] = FFMNativeHelper.newAlignedBuffer(4096, 4096);
+ buffers[i] = nativeBuffers[i].asByteBuffer();
+ byte[] data = new byte[2048];
+ new Random(12345+i).nextBytes(data);
+ buffers[i].put(data).flip();
+ helper.submitWrite(fd, context, i * 2048, 2048, buffers[i], callBacks[i]);
+ }
+
+ int events = helper.poll(context, callBacks, 2, 4);
+ assertTrue(events >= 2 && events <= 4, "Expected 2-4 events, got = " + events);
+
+ for (TestSubmitInfo cb : callBacks) {
+ assertTrue(cb.isDone());
+ assertFalse(cb.hasError());
+ }
+
+ } finally {
+ if (context != null) {
+ helper.deleteContext(context);
+ }
+ if (fd >= 0) {
+ FFMNativeHelper.close(fd);
+ }
+ Files.deleteIfExists(testFile);
+ for (MemorySegment buf: nativeBuffers) {
+ if (buf != null){
+ FFMNativeHelper.freeBuffer(buf);
+ }
+ }
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void blockedPollTest() throws IOException, InterruptedException {
+ logger.trace("@Test:: blockedPollTest");
+ Path testFile = Path.of("blocked-poll-test.bin");
+ FFMNativeHelper<TestSubmitInfo> helper = new FFMNativeHelper<>(null);
+ IOControl context = null;
+ int fd = -1;
+ MemorySegment nativeBuffer = null;
+ ByteBuffer buffer = null;
+
+ try {
+ Files.deleteIfExists(testFile);
+ fd = FFMNativeHelper.open(testFile.toString(), true);
+ FFMNativeHelper.fallocate(fd, 4096);
+
+ context = helper.newContext(2);
+
+ TestSubmitInfo callBack = new TestSubmitInfo();
+ nativeBuffer = FFMNativeHelper.newAlignedBuffer(4096, 4096);
+ buffer = nativeBuffer.asByteBuffer();
+ buffer.put((byte) 42).flip();
+
+ helper.submitWrite(fd, context, 0, 4096, buffer, callBack);
+ final IOControl contextRef = context;
+ Thread pollThread = new Thread(() -> {
+ try {
+ helper.blockedPoll(contextRef, false);
+ } catch (Throwable e){
+ logger.error("BlockedPoll failed", e);
+ }
+ });
+
+ pollThread.start();
+ Thread.sleep(100);
+ pollThread.join(1000);
+
+ assertTrue(callBack.isDone());
+ } finally {
+ if (context != null) {
+ helper.deleteContext(context);
+ }
+ if (fd >= 0) {
+ FFMNativeHelper.close(fd);
+ }
+ Files.deleteIfExists(testFile);
+ if (buffer != null){
+ FFMNativeHelper.freeBuffer(nativeBuffer);
+ }
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void fillMethodTest() throws IOException {
+ logger.trace("@Test:: fillMethodTest");
+ Path testFile = Path.of("fill-test.bin");
+ int fd = -1;
+
+ try {
+ Files.deleteIfExists(testFile);
+ fd = FFMNativeHelper.open(testFile.toString(), false);
+ long size = 3 * 1024 * 1024L;
+
+ FFMNativeHelper.fill(fd, 4096, size);
+ long actualSize = FFMNativeHelper.getSize(fd);
+ assertEquals(size, actualSize);
+ } finally {
+ if(fd >= 0) {
+ FFMNativeHelper.close(fd);
+ }
+ Files.deleteIfExists(testFile);
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void lockUnlockTest() throws IOException {
+ logger.trace("@Test:: lockUnlockTest");
+ Path testFile = Path.of("lock-test.bin");
+ int fd = -1;
+
+ try {
+ Files.deleteIfExists(testFile);
+ fd = FFMNativeHelper.open(testFile.toString(), false);
+
+ assertTrue(FFMNativeHelper.lock(fd));
+ int fd2 = FFMNativeHelper.open(testFile.toString(), false);
+ try {
+ assertFalse(FFMNativeHelper.lock(fd2));
+ } finally {
+ FFMNativeHelper.close(fd2);
+ }
+ } finally {
+ if (fd >= 0) {
+ FFMNativeHelper.close(fd);
+ Files.deleteIfExists(testFile);
+ }
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ public void iocbPoolExhaustionTest() throws IOException {
+ logger.trace("@Test:: iocbPoolExhaustionTest");
+ FFMNativeHelper<TestSubmitInfo> helper = new FFMNativeHelper<>(null);
+ IOControl context = helper.newContext(1);
+ int fd = FFMNativeHelper.open("pool-test.bin", false);
+ MemorySegment nativeBuffer = FFMNativeHelper.newAlignedBuffer(4096, 4096);
+ ByteBuffer buffer = nativeBuffer.asByteBuffer();
+ try {
+ TestSubmitInfo cb1 = new TestSubmitInfo();
+ helper.submitWrite(fd, context, 0, 4096, buffer, cb1);
+
+ TestSubmitInfo cb2 = new TestSubmitInfo();
+ assertThrows(IOException.class, () ->
+ helper.submitWrite(fd, context, 4096, 4096, buffer, cb2));
+
+ helper.poll(context, new TestSubmitInfo[1], 1, 1);
+
+ TestSubmitInfo cb3 = new TestSubmitInfo();
+ helper.submitWrite(fd, context, 8192, 4096, buffer, cb3);
+ } finally {
+ FFMNativeHelper.freeBuffer(nativeBuffer);
+ helper.deleteContext(context);
+ FFMNativeHelper.close(fd);
+ Files.deleteIfExists(Path.of("pool-test.bin"));
+ }
+ }
+
+ private static class TestSubmitInfo implements SubmitInfo {
+
+ private final AtomicBoolean done = new AtomicBoolean(false);
+ private final AtomicBoolean error = new AtomicBoolean(false);
+ private final AtomicReference<Integer> errorCode = new AtomicReference<>(0);
+ private final AtomicReference<String> errorMessage = new AtomicReference<>("");
+
+ @Override
+ public void onError(int errno, String message) {
+ error.set(true);
+ this.errorCode.set(errno);
+ this.errorMessage.set(message);
+ }
+
+ @Override
+ public void done() {
+ done.set(true);
+ }
+
+ public boolean isDone() {
+ return done.get();
+ }
+ public boolean hasError() {
+ return error.get();
+ }
+ }
+}
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOCBLayoutTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOCBLayoutTest.java
new file mode 100644
index 0000000..fda739d
--- /dev/null
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOCBLayoutTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm.test;
+
+import org.apache.activemq.artemis.nativo.jlibaio.ffm.IOCBInit;
+import org.junit.jupiter.api.Test;
+
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+
+import static org.apache.activemq.artemis.nativo.jlibaio.ffm.IOCBInit.IOCB_LAYOUT;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class IOCBLayoutTest {
+
+ @Test
+ public void iocbLayoutSizeTest() {
+ assertEquals(64, (int) IOCB_LAYOUT.byteSize(), "Expected 64-byte iocb");
+ }
+
+ @Test
+ public void iocbLayoutValueTest() {
+ try(Arena arena = Arena.ofConfined()) {
+ MemorySegment iocb = arena.allocate(IOCB_LAYOUT);
+ IOCBInit.setAioKey(iocb, 123);
+ IOCBInit.setAioFildes(iocb, 42);
+ IOCBInit.setAioBuf(iocb, 0x7f1234567890L);
+ IOCBInit.setAioNbytes(iocb, 4096);
+ IOCBInit.setAioFlags(iocb, 0);
+
+ assertEquals(123, IOCBInit.getAioKey(iocb));
+ assertEquals(42, IOCBInit.getAioFildes(iocb));
+ assertEquals(0x7f1234567890L, IOCBInit.getAioBuf(iocb));
+ assertEquals(4096, IOCBInit.getAioNbytes(iocb));
+ assertEquals(0, IOCBInit.getAioFlags(iocb));
+ }
+ }
+}
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOControlTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOControlTest.java
new file mode 100644
index 0000000..4c956d3
--- /dev/null
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/ffm/test/IOControlTest.java
@@ -0,0 +1,304 @@
+/*
+ * 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.activemq.artemis.nativo.jlibaio.ffm.test;
+
+import org.apache.activemq.artemis.nativo.jlibaio.ffm.IOControl;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import org.apache.activemq.artemis.nativo.jlibaio.ffm.IOCBInit;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+@DisplayName("IOControl lifecycle and concurrency tests")
+public class IOControlTest {
+
+ private Arena arena;
+ private IOControl ioControl;
+
+ @BeforeEach
+ void setUp() {
+ arena = Arena.ofConfined();
+
+ ioControl = new IOControl();
+ ioControl.setIoContext(arena.allocate(8));
+ ioControl.setEvents(arena.allocate(8));
+ ioControl.setQueueSize(8);
+
+ MemorySegment[] pool = new MemorySegment[8];
+ for (int i = 0; i < pool.length; i++) {
+ pool[i] = arena.allocate(IOCBInit.IOCB_LAYOUT);
+ }
+ ioControl.setIocbPool(pool);
+ }
+
+ @AfterEach
+ void tearDown() {
+ if (arena != null) {
+ arena.close();
+ }
+ }
+
+ @Test
+ void isValidShouldBeTrueForProperlyInitializedControl() {
+ assertTrue(ioControl.isValid());
+ }
+
+ @Test
+ void isValidShouldFailForNullContext() {
+ ioControl.setIoContext(MemorySegment.NULL);
+ assertFalse(ioControl.isValid());
+ }
+
+ @Test
+ void isValidShouldFailForNullEvents() {
+ ioControl.setEvents(MemorySegment.NULL);
+ assertFalse(ioControl.isValid());
+ }
+
+ @Test
+ void isValidShouldFailForZeroQueueSize() {
+ ioControl.setQueueSize(0);
+ assertFalse(ioControl.isValid());
+ }
+
+ @Test
+ void getIOCBShouldReturnDifferentSegmentsUntilQueueIsExhausted() {
+ Set<Long> addresses = new HashSet<>();
+
+ for (int i = 0; i < 8; i++) {
+ MemorySegment iocb = ioControl.getIOCB();
+ assertNotNull(iocb);
+ assertTrue(iocb.address() != 0L);
+ addresses.add(iocb.address());
+ }
+
+ assertEquals(8, addresses.size());
+ assertEquals(8, ioControl.used());
+ assertEquals(0, ioControl.iocbGet());
+
+ assertNull(ioControl.getIOCB());
+ }
+
+ @Test
+ void putIOCBShouldReturnIOCBToPoolAndDecrementUsed() {
+ MemorySegment first = ioControl.getIOCB();
+ MemorySegment second = ioControl.getIOCB();
+
+ assertNotNull(first);
+ assertNotNull(second);
+ assertEquals(2, ioControl.used());
+
+ ioControl.putIOCB(first);
+ assertEquals(1, ioControl.used());
+
+ ioControl.putIOCB(second);
+ assertEquals(0, ioControl.used());
+ }
+
+ @Test
+ void getIOCBShouldWrapAround() {
+ for (int i = 0; i < 8; i++) {
+ assertNotNull(ioControl.getIOCB());
+ }
+
+ for (int i = 0; i < 8; i++) {
+ ioControl.putIOCB(ioControl.iocbPool()[i]);
+ }
+
+ assertEquals(0, ioControl.used());
+ assertEquals(0, ioControl.iocbGet());
+ assertEquals(0, ioControl.iocbPut());
+
+ MemorySegment again = ioControl.getIOCB();
+ assertNotNull(again);
+ assertEquals(1, ioControl.used());
+ assertEquals(1, ioControl.iocbGet());
+ }
+
+ @Test
+ void putIOCBShouldIgnoreNullAndInvalidSegments() {
+ assertDoesNotThrow(() -> ioControl.putIOCB(null));
+ assertDoesNotThrow(() -> ioControl.putIOCB(MemorySegment.NULL));
+ assertEquals(0, ioControl.used());
+ }
+
+ @Test
+ void getIOCBShouldReturnNullWhenPoolIsEmpty() {
+ for (int i = 0; i < 8; i++) {
+ assertNotNull(ioControl.getIOCB());
+ }
+
+ assertNull(ioControl.getIOCB());
+ assertEquals(8, ioControl.used());
+ }
+
+ @Test
+ void concurrentGetAndPutShouldPreserveInvariant() throws Exception {
+ final int threads = 8;
+ final int iterationsPerThread = 5_000;
+
+ ExecutorService executor = Executors.newFixedThreadPool(threads);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Callable<Void>> tasks = new ArrayList<>();
+
+ for (int t = 0; t < threads; t++) {
+ tasks.add(() -> {
+ start.await();
+
+ for (int i = 0; i < iterationsPerThread; i++) {
+ MemorySegment iocb = ioControl.getIOCB();
+ if (iocb != null) {
+ ioControl.putIOCB(iocb);
+ }
+ }
+ return null;
+ });
+ }
+
+ try {
+ List<Future<Void>> futures = new ArrayList<>();
+ for (Callable<Void> task : tasks) {
+ futures.add(executor.submit(task));
+ }
+
+ start.countDown();
+
+ for (Future<Void> future : futures) {
+ future.get(30, TimeUnit.SECONDS);
+ }
+
+ assertTrue(ioControl.isValid());
+ assertEquals(0, ioControl.used());
+ assertEquals(0, ioControl.iocbGet());
+ assertEquals(0, ioControl.iocbPut());
+
+ MemorySegment[] pool = ioControl.iocbPool();
+ assertNotNull(pool);
+ assertEquals(8, pool.length);
+
+ Set<Long> addresses = new HashSet<>();
+ for (MemorySegment seg : pool) {
+ assertNotNull(seg);
+ assertTrue(seg.address() != 0L);
+ addresses.add(seg.address());
+ }
+ assertEquals(8, addresses.size());
+ } finally {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void concurrentGetShouldNeverReturnSameIOCBTwiceWithoutPut() throws Exception {
+ final int threads = 8;
+ ExecutorService executor = Executors.newFixedThreadPool(threads);
+ CountDownLatch start = new CountDownLatch(1);
+
+ try {
+ List<Future<MemorySegment>> futures = new ArrayList<>();
+ for (int i = 0; i < threads; i++) {
+ futures.add(executor.submit(() -> {
+ start.await();
+ return ioControl.getIOCB();
+ }));
+ }
+
+ start.countDown();
+
+ Set<Long> addresses = new HashSet<>();
+ int nonNullCount = 0;
+
+ for (Future<MemorySegment> future : futures) {
+ MemorySegment seg = future.get(10, TimeUnit.SECONDS);
+ if (seg != null) {
+ nonNullCount++;
+ addresses.add(seg.address());
+ }
+ }
+
+ assertEquals(nonNullCount, addresses.size());
+ assertTrue(ioControl.used() <= ioControl.queueSize());
+ assertTrue(ioControl.isValid());
+ } finally {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void concurrentPutShouldBeSafeAfterPreallocation() throws Exception {
+ MemorySegment[] taken = new MemorySegment[8];
+ for (int i = 0; i < 8; i++) {
+ taken[i] = ioControl.getIOCB();
+ assertNotNull(taken[i]);
+ }
+ assertEquals(8, ioControl.used());
+
+ final int threads = 8;
+ ExecutorService executor = Executors.newFixedThreadPool(threads);
+ CountDownLatch start = new CountDownLatch(1);
+
+ try {
+ List<Future<Void>> futures = new ArrayList<>();
+ for (int i = 0; i < threads; i++) {
+ final MemorySegment seg = taken[i];
+ futures.add(executor.submit(() -> {
+ start.await();
+ ioControl.putIOCB(seg);
+ return null;
+ }));
+ }
+
+ start.countDown();
+
+ for (Future<Void> future : futures) {
+ future.get(10, TimeUnit.SECONDS);
+ }
+
+ assertEquals(0, ioControl.used());
+ assertEquals(0, ioControl.iocbGet());
+ assertEquals(0, ioControl.iocbPut());
+ assertTrue(ioControl.isValid());
+ } finally {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+}
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioStressTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioStressTest.java
index aeb7344..ebdeaf9 100644
--- a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioStressTest.java
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioStressTest.java
@@ -19,6 +19,7 @@ package org.apache.activemq.artemis.nativo.jlibaio.test;
import java.io.File;
import java.io.IOException;
+import java.lang.foreign.MemorySegment;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
@@ -207,7 +208,8 @@ public class LibaioStressTest {
LibaioFile fileDescriptor = control.openFile(file, true);
// ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
- ByteBuffer buffer = LibaioContext.newAlignedBuffer(4096, 4096);
+ MemorySegment memorySegment = LibaioContext.newAlignedBuffer(4096, 4096);
+ ByteBuffer buffer = memorySegment.asByteBuffer();
int maxSize = 4096 * LIBAIO_QUEUE_SIZE;
fileDescriptor.fill(4096, maxSize);
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioTest.java
index 7318412..b92605a 100644
--- a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioTest.java
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/LibaioTest.java
@@ -20,6 +20,7 @@ package org.apache.activemq.artemis.nativo.jlibaio.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.lang.foreign.MemorySegment;
import java.lang.ref.Cleaner;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
@@ -129,23 +130,23 @@ public class LibaioTest {
LibaioFile fileDescriptor = control.openFile(temporaryFolder.newFile("test.bin"), true);
fileDescriptor.fallocate(size);
- ByteBuffer buffer = fileDescriptor.newBuffer(size);
- fileDescriptor.read(0, size, buffer, new TestInfo());
+ MemorySegment buffer = fileDescriptor.newBuffer(size);
+ fileDescriptor.read(0, size, buffer.asByteBuffer(), new TestInfo());
TestInfo[] callbacks = new TestInfo[1];
control.poll(callbacks, 1, 1);
fileDescriptor.close();
- buffer.position(0);
+ buffer.asByteBuffer().position(0);
LibaioFile fileDescriptor2 = control.openFile(temporaryFolder.newFile("test2.bin"), true);
fileDescriptor2.fill(fileDescriptor.getBlockSize(), size);
- fileDescriptor2.read(0, size, buffer, new TestInfo());
+ fileDescriptor2.read(0, size, buffer.asByteBuffer(), new TestInfo());
control.poll(callbacks, 1, 1);
for (int i = 0; i < size; i++) {
- Assert.assertEquals(0, buffer.get());
+ Assert.assertEquals(0, buffer.asByteBuffer().get());
}
LibaioContext.freeBuffer(buffer);
@@ -180,11 +181,11 @@ public class LibaioTest {
logger.debug("blockSize = " + fileDescriptor[0].getBlockSize());
logger.debug("blockSize /tmp= " + LibaioContext.getBlockSize("/tmp"));
- ByteBuffer buffer = LibaioContext.newAlignedBuffer(4096, 4096);
+ MemorySegment buffer = LibaioContext.newAlignedBuffer(4096, 4096);
try {
for (int i = 0; i < 4096; i++) {
- buffer.put((byte) 'a');
+ buffer.asByteBuffer().put((byte) 'a');
}
TestInfo callback = new TestInfo();
@@ -192,7 +193,7 @@ public class LibaioTest {
for (int i = 0; i < LIBAIO_QUEUE_SIZE / 2; i++) {
for (LibaioFile file : fileDescriptor) {
- file.write(i * 4096, 4096, buffer, callback);
+ file.write(i * 4096, 4096, buffer.asByteBuffer(), callback);
}
}
@@ -203,8 +204,8 @@ public class LibaioTest {
}
for (LibaioFile file : fileDescriptor) {
- ByteBuffer bigbuffer = LibaioContext.newAlignedBuffer(4096 * 25, 4096);
- file.read(0, 4096 * 25, bigbuffer, callback);
+ MemorySegment bigbuffer = LibaioContext.newAlignedBuffer(4096 * 25, 4096);
+ file.read(0, 4096 * 25, bigbuffer.asByteBuffer(), callback);
Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE));
for (Object returnedCallback : callbacks) {
@@ -212,7 +213,7 @@ public class LibaioTest {
}
for (int i = 0; i < 4096 * 25; i++) {
- Assert.assertEquals((byte) 'a', bigbuffer.get());
+ Assert.assertEquals((byte) 'a', bigbuffer.asByteBuffer().get());
}
LibaioContext.freeBuffer(bigbuffer);
@@ -233,16 +234,16 @@ public class LibaioTest {
LibaioFile fileDescriptor = control.openFile(temporaryFolder.newFile("test.bin"), true);
// ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
- ByteBuffer buffer = LibaioContext.newAlignedBuffer(4096, 4096);
+ MemorySegment buffer = LibaioContext.newAlignedBuffer(4096, 4096);
try {
for (int i = 0; i < 4096; i++) {
- buffer.put((byte) 'a');
+ buffer.asByteBuffer().put((byte) 'a');
}
- buffer.rewind();
+ buffer.asByteBuffer().rewind();
- fileDescriptor.write(0, 4096, buffer, callback);
+ fileDescriptor.write(0, 4096, buffer.asByteBuffer(), callback);
int retValue = control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE);
Assert.assertEquals(1, retValue);
@@ -254,21 +255,21 @@ public class LibaioTest {
buffer = LibaioContext.newAlignedBuffer(4096, 4096);
for (int i = 0; i < 4096; i++) {
- buffer.put((byte) 'B');
+ buffer.asByteBuffer().put((byte) 'B');
}
- fileDescriptor.write(0, 4096, buffer, null);
+ fileDescriptor.write(0, 4096, buffer.asByteBuffer(), new TestInfo());
Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE));
- buffer.rewind();
+ buffer.asByteBuffer().rewind();
- fileDescriptor.read(0, 4096, buffer, null);
+ fileDescriptor.read(0, 4096, buffer.asByteBuffer(), new TestInfo());
Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE));
for (int i = 0; i < 4096; i++) {
- Assert.assertEquals('B', buffer.get());
+ Assert.assertEquals('B', buffer.asByteBuffer().get());
}
} finally {
LibaioContext.freeBuffer(buffer);
@@ -316,13 +317,13 @@ public class LibaioTest {
buffer.put((byte) 'B');
}
- fileDescriptor.write(0, BUFFER_SIZE, buffer, null);
+ fileDescriptor.write(0, BUFFER_SIZE, buffer, new TestInfo());
Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE));
buffer.rewind();
- fileDescriptor.read(0, 50, buffer, null);
+ fileDescriptor.read(0, 50, buffer, new TestInfo());
Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE));
@@ -347,28 +348,28 @@ public class LibaioTest {
LibaioFile fileDescriptor = control.openFile(file, true);
- ByteBuffer buffer = LibaioContext.newAlignedBuffer(4096, 4096);
+ MemorySegment buffer = LibaioContext.newAlignedBuffer(4096, 4096);
final int BUFFER_SIZE = 4096;
try {
for (int i = 0; i < BUFFER_SIZE; i++) {
- buffer.put((byte) '@');
+ buffer.asByteBuffer().put((byte) '@');
}
- fileDescriptor.write(0, BUFFER_SIZE, buffer, callback);
+ fileDescriptor.write(0, BUFFER_SIZE, buffer.asByteBuffer(), callback);
Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE));
Assert.assertSame(callback, callbacks[0]);
- buffer.rewind();
+ buffer.asByteBuffer().rewind();
- fileDescriptor.read(0, BUFFER_SIZE, buffer, callback);
+ fileDescriptor.read(0, BUFFER_SIZE, buffer.asByteBuffer(), callback);
Assert.assertEquals(1, control.poll(callbacks, 1, LIBAIO_QUEUE_SIZE));
Assert.assertSame(callback, callbacks[0]);
for (int i = 0; i < BUFFER_SIZE; i++) {
- Assert.assertEquals('@', buffer.get());
+ Assert.assertEquals('@', buffer.asByteBuffer().get());
}
} finally {
LibaioContext.freeBuffer(buffer);
@@ -406,7 +407,8 @@ public class LibaioTest {
logger.debug("Error:" + callbacks[0]);
- buffer = fileDescriptor.newBuffer(4096);
+ MemorySegment memorySegment = fileDescriptor.newBuffer(4096);
+ buffer = memorySegment.asByteBuffer();
for (int i = 0; i < 4096; i++) {
buffer.put((byte) 'z');
}
@@ -444,17 +446,17 @@ public class LibaioTest {
LibaioFile<TestInfo> fileDescriptor = control.openFile(file, true);
- ByteBuffer bufferWrite = LibaioContext.newAlignedBuffer(4096, 4096);
+ MemorySegment bufferWrite = LibaioContext.newAlignedBuffer(4096, 4096);
try {
for (int i = 0; i < 4096; i++) {
- bufferWrite.put((byte) 'B');
+ bufferWrite.asByteBuffer().put((byte) 'B');
}
for (int j = 0; j < LIBAIO_QUEUE_SIZE * 2; j++) {
for (int i = 0; i < LIBAIO_QUEUE_SIZE; i++) {
TestInfo countClass = new TestInfo();
- fileDescriptor.write(i * 4096, 4096, bufferWrite, countClass);
+ fileDescriptor.write(i * 4096, 4096, bufferWrite.asByteBuffer(), countClass);
}
Assert.assertEquals(LIBAIO_QUEUE_SIZE, control.poll(callbacks, LIBAIO_QUEUE_SIZE, LIBAIO_QUEUE_SIZE));
@@ -507,7 +509,8 @@ public class LibaioTest {
@Test
public void testMemset() throws Exception {
- ByteBuffer buffer = LibaioContext.newAlignedBuffer(4096 * 8, 4096);
+ MemorySegment memorySegment = LibaioContext.newAlignedBuffer(4096 * 8, 4096);
+ ByteBuffer buffer = memorySegment.asByteBuffer();
for (int i = 0; i < buffer.capacity(); i++) {
buffer.put((byte) 'z');
@@ -527,7 +530,7 @@ public class LibaioTest {
Assert.assertEquals((byte) 0, buffer.get());
}
- LibaioContext.freeBuffer(buffer);
+ LibaioContext.freeBuffer(memorySegment);
}
@@ -570,7 +573,8 @@ public class LibaioTest {
fileDescriptor = control.openFile(temporaryFolder.newFile(), true);
- ByteBuffer buffer = fileDescriptor.newBuffer(4096);
+ MemorySegment memorySegment = fileDescriptor.newBuffer(4096);
+ ByteBuffer buffer = memorySegment.asByteBuffer();
try {
for (int i = 0; i < 4096; i++) {
@@ -628,7 +632,7 @@ public class LibaioTest {
Assert.assertTrue(exceptionThrown);
} finally {
- LibaioContext.freeBuffer(buffer);
+ LibaioContext.freeBuffer(memorySegment);
}
}
@@ -669,7 +673,8 @@ public class LibaioTest {
MyCallback callback = new MyCallback();
- ByteBuffer buffer = LibaioContext.newAlignedBuffer(4096, 4096);
+ MemorySegment memorySegment = LibaioContext.newAlignedBuffer(4096, 4096);
+ ByteBuffer buffer = memorySegment.asByteBuffer();
for (int i = 0; i < 4096; i++) {
buffer.put((byte) 'a');
diff --git a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/OpenCloseContextTest.java b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/OpenCloseContextTest.java
index 1d8775e..50e2fcb 100644
--- a/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/OpenCloseContextTest.java
+++ b/src/test/java/org/apache/activemq/artemis/nativo/jlibaio/test/OpenCloseContextTest.java
@@ -18,6 +18,7 @@
package org.apache.activemq.artemis.nativo.jlibaio.test;
import java.io.File;
+import java.lang.foreign.MemorySegment;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -51,7 +52,8 @@ public class OpenCloseContextTest {
@Test
public void testRepeatOpenCloseContext() throws Exception {
- ByteBuffer buffer = LibaioContext.newAlignedBuffer(512, 512);
+ MemorySegment memorySegment = LibaioContext.newAlignedBuffer(512, 512);
+ ByteBuffer buffer = memorySegment.asByteBuffer();
for (int i = 0; i < 512; i++)
buffer.put((byte) 'x');
@@ -109,7 +111,8 @@ public class OpenCloseContextTest {
@Test
public void testRepeatOpenCloseContext2() throws Exception {
- ByteBuffer buffer = LibaioContext.newAlignedBuffer(512, 512);
+ MemorySegment memorySegment = LibaioContext.newAlignedBuffer(512, 512);
+ ByteBuffer buffer = memorySegment.asByteBuffer();
for (int i = 0; i < 512; i++)
buffer.put((byte) 'x');
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@artemis.apache.org
For additional commands, e-mail: commits-help@artemis.apache.org