package sun.nio.ch;
import java.io.IOException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import static sun.nio.ch.KQueue.EVFILT_READ;
import static sun.nio.ch.KQueue.EVFILT_WRITE;
import static sun.nio.ch.KQueue.EV_ADD;
import static sun.nio.ch.KQueue.EV_DELETE;
class KQueueSelectorImpl extends SelectorImpl {
private static final int MAX_KEVENTS = 256;
private final int kqfd;
private final long pollArrayAddress;
private final int fd0;
private final int fd1;
private final Map<Integer, SelectionKeyImpl> fdToKey = new HashMap<>();
private final Object updateLock = new Object();
private final Deque<SelectionKeyImpl> updateKeys = new ArrayDeque<>();
private final Object interruptLock = new Object();
private boolean interruptTriggered;
private int pollCount;
KQueueSelectorImpl(SelectorProvider sp) throws IOException {
super(sp);
this.kqfd = KQueue.create();
this.pollArrayAddress = KQueue.allocatePollArray(MAX_KEVENTS);
try {
long fds = IOUtil.makePipe(false);
this.fd0 = (int) (fds >>> 32);
this.fd1 = (int) fds;
} catch (IOException ioe) {
KQueue.freePollArray(pollArrayAddress);
FileDispatcherImpl.closeIntFD(kqfd);
throw ioe;
}
KQueue.register(kqfd, fd0, EVFILT_READ, EV_ADD);
}
private void ensureOpen() {
if (!isOpen())
throw new ClosedSelectorException();
}
@Override
protected int doSelect(Consumer<SelectionKey> action, long timeout)
throws IOException
{
assert Thread.holdsLock(this);
long to = Math.min(timeout, Integer.MAX_VALUE);
boolean blocking = (to != 0);
boolean timedPoll = (to > 0);
int numEntries;
processUpdateQueue();
processDeregisterQueue();
try {
begin(blocking);
do {
long startTime = timedPoll ? System.nanoTime() : 0;
numEntries = KQueue.poll(kqfd, pollArrayAddress, MAX_KEVENTS, to);
if (numEntries == IOStatus.INTERRUPTED && timedPoll) {
long adjust = System.nanoTime() - startTime;
to -= TimeUnit.MILLISECONDS.convert(adjust, TimeUnit.NANOSECONDS);
if (to <= 0) {
numEntries = 0;
}
}
} while (numEntries == IOStatus.INTERRUPTED);
assert IOStatus.check(numEntries);
} finally {
end(blocking);
}
processDeregisterQueue();
return processEvents(numEntries, action);
}
private void processUpdateQueue() {
assert Thread.holdsLock(this);
synchronized (updateLock) {
SelectionKeyImpl ski;
while ((ski = updateKeys.pollFirst()) != null) {
if (ski.isValid()) {
int fd = ski.getFDVal();
SelectionKeyImpl previous = fdToKey.putIfAbsent(fd, ski);
assert (previous == null) || (previous == ski);
int newEvents = ski.translateInterestOps();
int registeredEvents = ski.registeredEvents();
if (ski.getAndClearReset() && registeredEvents != 0) {
KQueue.register(kqfd, fd, EVFILT_READ, EV_DELETE);
registeredEvents = 0;
}
if (newEvents != registeredEvents) {
if ((registeredEvents & Net.POLLIN) != 0) {
if ((newEvents & Net.POLLIN) == 0) {
KQueue.register(kqfd, fd, EVFILT_READ, EV_DELETE);
}
} else if ((newEvents & Net.POLLIN) != 0) {
KQueue.register(kqfd, fd, EVFILT_READ, EV_ADD);
}
if ((registeredEvents & Net.POLLOUT) != 0) {
if ((newEvents & Net.POLLOUT) == 0) {
KQueue.register(kqfd, fd, EVFILT_WRITE, EV_DELETE);
}
} else if ((newEvents & Net.POLLOUT) != 0) {
KQueue.register(kqfd, fd, EVFILT_WRITE, EV_ADD);
}
ski.registeredEvents(newEvents);
}
}
}
}
}
private int processEvents(int numEntries, Consumer<SelectionKey> action)
throws IOException
{
assert Thread.holdsLock(this);
int numKeysUpdated = 0;
boolean interrupted = false;
pollCount++;
for (int i = 0; i < numEntries; i++) {
long kevent = KQueue.getEvent(pollArrayAddress, i);
int fd = KQueue.getDescriptor(kevent);
if (fd == fd0) {
interrupted = true;
} else {
SelectionKeyImpl ski = fdToKey.get(fd);
if (ski != null) {
int rOps = 0;
short filter = KQueue.getFilter(kevent);
if (filter == EVFILT_READ) {
rOps |= Net.POLLIN;
} else if (filter == EVFILT_WRITE) {
rOps |= Net.POLLOUT;
}
int updated = processReadyEvents(rOps, ski, action);
if (updated > 0 && ski.lastPolled != pollCount) {
numKeysUpdated++;
ski.lastPolled = pollCount;
}
}
}
}
if (interrupted) {
clearInterrupt();
}
return numKeysUpdated;
}
@Override
protected void implClose() throws IOException {
assert !isOpen();
assert Thread.holdsLock(this);
synchronized (interruptLock) {
interruptTriggered = true;
}
FileDispatcherImpl.closeIntFD(kqfd);
KQueue.freePollArray(pollArrayAddress);
FileDispatcherImpl.closeIntFD(fd0);
FileDispatcherImpl.closeIntFD(fd1);
}
@Override
protected void implDereg(SelectionKeyImpl ski) throws IOException {
assert !ski.isValid();
assert Thread.holdsLock(this);
int fd = ski.getFDVal();
int registeredEvents = ski.registeredEvents();
if (fdToKey.remove(fd) != null) {
if (registeredEvents != 0) {
if ((registeredEvents & Net.POLLIN) != 0)
KQueue.register(kqfd, fd, EVFILT_READ, EV_DELETE);
if ((registeredEvents & Net.POLLOUT) != 0)
KQueue.register(kqfd, fd, EVFILT_WRITE, EV_DELETE);
ski.registeredEvents(0);
}
} else {
assert registeredEvents == 0;
}
}
@Override
public void setEventOps(SelectionKeyImpl ski) {
ensureOpen();
synchronized (updateLock) {
updateKeys.addLast(ski);
}
}
@Override
public Selector wakeup() {
synchronized (interruptLock) {
if (!interruptTriggered) {
try {
IOUtil.write1(fd1, (byte)0);
} catch (IOException ioe) {
throw new InternalError(ioe);
}
interruptTriggered = true;
}
}
return this;
}
private void clearInterrupt() throws IOException {
synchronized (interruptLock) {
IOUtil.drain(fd0);
interruptTriggered = false;
}
}
}