1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.channel.uring;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufAllocator;
20 import io.netty.buffer.ByteBufHolder;
21 import io.netty.buffer.ByteBufUtil;
22 import io.netty.buffer.Unpooled;
23 import io.netty.channel.AbstractChannel;
24 import io.netty.channel.Channel;
25 import io.netty.channel.ChannelConfig;
26 import io.netty.channel.ChannelFuture;
27 import io.netty.channel.ChannelFutureListener;
28 import io.netty.channel.ChannelOption;
29 import io.netty.channel.ChannelOutboundBuffer;
30 import io.netty.channel.ChannelPromise;
31 import io.netty.channel.ConnectTimeoutException;
32 import io.netty.channel.EventLoop;
33 import io.netty.channel.IoEvent;
34 import io.netty.channel.IoEventLoop;
35 import io.netty.channel.IoRegistration;
36 import io.netty.channel.RecvByteBufAllocator;
37 import io.netty.channel.ServerChannel;
38 import io.netty.channel.socket.ChannelInputShutdownEvent;
39 import io.netty.channel.socket.ChannelInputShutdownReadComplete;
40 import io.netty.channel.socket.SocketChannelConfig;
41 import io.netty.channel.unix.Buffer;
42 import io.netty.channel.unix.DomainSocketAddress;
43 import io.netty.channel.unix.Errors;
44 import io.netty.channel.unix.FileDescriptor;
45 import io.netty.channel.unix.IovArray;
46 import io.netty.channel.unix.UnixChannel;
47 import io.netty.channel.unix.UnixChannelUtil;
48 import io.netty.util.ReferenceCountUtil;
49 import io.netty.util.ReferenceCounted;
50 import io.netty.util.concurrent.PromiseNotifier;
51 import io.netty.util.internal.CleanableDirectBuffer;
52 import io.netty.util.internal.StringUtil;
53 import io.netty.util.internal.logging.InternalLogger;
54 import io.netty.util.internal.logging.InternalLoggerFactory;
55
56 import java.io.IOException;
57 import java.net.InetSocketAddress;
58 import java.net.SocketAddress;
59 import java.nio.ByteBuffer;
60 import java.nio.channels.AlreadyConnectedException;
61 import java.nio.channels.ClosedChannelException;
62 import java.nio.channels.ConnectionPendingException;
63 import java.nio.channels.NotYetConnectedException;
64 import java.nio.channels.UnresolvedAddressException;
65 import java.util.Collections;
66 import java.util.List;
67 import java.util.concurrent.ScheduledFuture;
68 import java.util.concurrent.TimeUnit;
69
70 import static io.netty.channel.unix.Errors.ERRNO_EINPROGRESS_NEGATIVE;
71 import static io.netty.channel.unix.Errors.ERROR_EALREADY_NEGATIVE;
72 import static io.netty.channel.unix.UnixChannelUtil.computeRemoteAddr;
73 import static io.netty.util.internal.ObjectUtil.checkNotNull;
74 import static io.netty.util.internal.StringUtil.className;
75
76
77 abstract class AbstractIoUringChannel extends AbstractChannel implements UnixChannel {
78 private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractIoUringChannel.class);
79 final LinuxSocket socket;
80 protected volatile boolean active;
81
82
83 private static final int POLL_IN_SCHEDULED = 1;
84 private static final int POLL_OUT_SCHEDULED = 1 << 2;
85 private static final int POLL_RDHUP_SCHEDULED = 1 << 3;
86 private static final int WRITE_SCHEDULED = 1 << 4;
87 private static final int READ_SCHEDULED = 1 << 5;
88 private static final int CONNECT_SCHEDULED = 1 << 6;
89
90 private short opsId = Short.MIN_VALUE;
91
92 private long pollInId;
93 private long pollOutId;
94 private long pollRdhupId;
95 private long connectId;
96
97
98 private byte ioState;
99
100
101
102
103 private short numOutstandingWrites;
104
105 private short numOutstandingReads;
106
107 private boolean readPending;
108 private boolean inReadComplete;
109 private boolean socketHasMoreData;
110
111 private static final class DelayedClose {
112 private final ChannelPromise promise;
113 private final Throwable cause;
114 private final ClosedChannelException closeCause;
115
116 DelayedClose(ChannelPromise promise, Throwable cause, ClosedChannelException closeCause) {
117 this.promise = promise;
118 this.cause = cause;
119 this.closeCause = closeCause;
120 }
121 }
122 private DelayedClose delayedClose;
123 private boolean inputClosedSeenErrorOnRead;
124
125
126
127
128 private ChannelPromise connectPromise;
129 private ScheduledFuture<?> connectTimeoutFuture;
130 private SocketAddress requestedRemoteAddress;
131 private CleanableDirectBuffer cleanable;
132 private ByteBuffer remoteAddressMemory;
133 private MsgHdrMemoryArray msgHdrMemoryArray;
134
135
136
137
138 private ChannelOutboundBuffer fastOpenOutboundBuffer;
139 private Object fastOpenData;
140 private long fastOpenBytes;
141
142 private IoRegistration registration;
143
144 private volatile SocketAddress local;
145 private volatile SocketAddress remote;
146
147 AbstractIoUringChannel(final Channel parent, LinuxSocket socket, boolean active) {
148 super(parent);
149 this.socket = checkNotNull(socket, "fd");
150
151 if (active) {
152
153
154 this.active = true;
155 this.local = socket.localAddress();
156 this.remote = socket.remoteAddress();
157 }
158
159 logger.trace("Create {} Socket: {}", this instanceof ServerChannel ? "Server" : "Channel", socket.intValue());
160 }
161
162 AbstractIoUringChannel(Channel parent, LinuxSocket fd, SocketAddress remote) {
163 super(parent);
164 this.socket = checkNotNull(fd, "fd");
165 this.active = true;
166
167
168
169 this.remote = remote;
170 this.local = fd.localAddress();
171 }
172
173
174 final void autoReadCleared() {
175 if (!isRegistered()) {
176 return;
177 }
178 IoRegistration registration = this.registration;
179 if (registration == null || !registration.isValid()) {
180 return;
181 }
182 if (eventLoop().inEventLoop()) {
183 clearRead();
184 } else {
185 eventLoop().execute(this::clearRead);
186 }
187 }
188
189 private void clearRead() {
190 assert eventLoop().inEventLoop();
191 readPending = false;
192 IoRegistration registration = this.registration;
193 if (registration == null || !registration.isValid()) {
194 return;
195 }
196
197 cancelOutstandingReads(registration(), numOutstandingReads);
198 }
199
200
201
202
203
204
205 protected final short nextOpsId() {
206 short id = opsId++;
207
208
209 if (id == 0) {
210 id = opsId++;
211 }
212 return id;
213 }
214
215 public final boolean isOpen() {
216 return socket.isOpen();
217 }
218
219 @Override
220 public boolean isActive() {
221 return active;
222 }
223
224 @Override
225 public final FileDescriptor fd() {
226 return socket;
227 }
228
229 private AbstractUringUnsafe ioUringUnsafe() {
230 return (AbstractUringUnsafe) unsafe();
231 }
232
233 @Override
234 protected boolean isCompatible(final EventLoop loop) {
235 return loop instanceof IoEventLoop && ((IoEventLoop) loop).isCompatible(AbstractUringUnsafe.class);
236 }
237
238 protected final ByteBuf newDirectBuffer(ByteBuf buf) {
239 return newDirectBuffer(buf, buf);
240 }
241
242 protected boolean allowMultiShotPollIn() {
243 return IoUring.isPollAddMultishotEnabled();
244 }
245
246 protected final ByteBuf newDirectBuffer(Object holder, ByteBuf buf) {
247 final int readableBytes = buf.readableBytes();
248 if (readableBytes == 0) {
249 ReferenceCountUtil.release(holder);
250 return Unpooled.EMPTY_BUFFER;
251 }
252
253 final ByteBufAllocator alloc = alloc();
254 if (alloc.isDirectBufferPooled()) {
255 return newDirectBuffer0(holder, buf, alloc, readableBytes);
256 }
257
258 final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer();
259 if (directBuf == null) {
260 return newDirectBuffer0(holder, buf, alloc, readableBytes);
261 }
262
263 directBuf.writeBytes(buf, buf.readerIndex(), readableBytes);
264 ReferenceCountUtil.safeRelease(holder);
265 return directBuf;
266 }
267
268 private static ByteBuf newDirectBuffer0(Object holder, ByteBuf buf, ByteBufAllocator alloc, int capacity) {
269 final ByteBuf directBuf = alloc.directBuffer(capacity);
270 directBuf.writeBytes(buf, buf.readerIndex(), capacity);
271 ReferenceCountUtil.safeRelease(holder);
272 return directBuf;
273 }
274
275
276
277
278
279
280
281 protected abstract void cancelOutstandingReads(IoRegistration registration, int numOutstandingReads);
282
283
284
285
286
287
288
289 protected abstract void cancelOutstandingWrites(IoRegistration registration, int numOutstandingWrites);
290
291 @Override
292 protected void doDisconnect() throws Exception {
293 }
294
295 private void freeRemoteAddressMemory() {
296 if (remoteAddressMemory != null) {
297 cleanable.clean();
298 cleanable = null;
299 remoteAddressMemory = null;
300 }
301 }
302
303 final MsgHdrMemory writeMsgHdr() {
304 if (msgHdrMemoryArray == null) {
305 msgHdrMemoryArray = new MsgHdrMemoryArray((short) 1);
306 }
307 return msgHdrMemoryArray.hdr(0);
308 }
309
310 private void freeMsgHdrArray() {
311 if (msgHdrMemoryArray != null) {
312 msgHdrMemoryArray.release();
313 msgHdrMemoryArray = null;
314 }
315 }
316
317 @Override
318 protected void doClose() throws Exception {
319 active = false;
320
321 if (registration != null) {
322 if (socket.markClosed()) {
323 int fd = fd().intValue();
324 IoUringIoOps ops = IoUringIoOps.newClose(fd, (byte) 0, nextOpsId());
325 registration.submit(ops);
326 }
327 } else {
328
329 socket.close();
330 ioUringUnsafe().unregistered();
331 }
332 }
333
334 @Override
335 protected final void doShutdownOutput() throws Exception {
336
337 removeFastOpenData();
338
339 AbstractUringUnsafe unsafe = ioUringUnsafe();
340 unsafe.prepareToDiscardOutboundMessages(unsafe.originalOutboundBuffer);
341 doShutdownOutput0();
342 }
343
344
345
346
347
348
349 private void removeFastOpenData() {
350 ChannelOutboundBuffer in = fastOpenOutboundBuffer;
351 if (in == null) {
352 return;
353 }
354 Object data = fastOpenData;
355 long bytes = fastOpenBytes;
356 fastOpenOutboundBuffer = null;
357 fastOpenData = null;
358 fastOpenBytes = 0;
359 if (bytes > 0 && isActive() && in.current() == data) {
360 in.removeBytes(bytes);
361 }
362 }
363
364
365
366
367 protected void doShutdownOutput0() throws Exception {
368 super.doShutdownOutput();
369 }
370
371 @Override
372 protected final void doBeginRead() {
373 if (inputClosedSeenErrorOnRead) {
374
375 return;
376 }
377 if (readPending) {
378
379 return;
380 }
381 readPending = true;
382 if (inReadComplete || !isActive()) {
383
384
385
386 return;
387 }
388 doBeginReadNow();
389 }
390
391 private void doBeginReadNow() {
392 if (inputClosedSeenErrorOnRead) {
393
394 return;
395 }
396 if (!isPollInFirst() ||
397
398
399 socketHasMoreData) {
400
401 ioUringUnsafe().scheduleFirstReadIfNeeded();
402 } else if ((ioState & POLL_IN_SCHEDULED) == 0) {
403 ioUringUnsafe().schedulePollIn();
404 }
405 }
406
407 @Override
408 protected void doWrite(ChannelOutboundBuffer in) {
409 scheduleWriteIfNeeded(in, true);
410 }
411
412 protected void scheduleWriteIfNeeded(ChannelOutboundBuffer in, boolean submitAndRunNow) {
413 if ((ioState & WRITE_SCHEDULED) != 0) {
414 return;
415 }
416 if (scheduleWrite(in) > 0) {
417 ioState |= WRITE_SCHEDULED;
418 if (submitAndRunNow && !isWritable()) {
419 submitAndRunNow();
420 }
421 }
422 }
423
424 protected void submitAndRunNow() {
425
426 }
427
428 private int scheduleWrite(ChannelOutboundBuffer in) {
429 if (delayedClose != null || numOutstandingWrites == Short.MAX_VALUE) {
430 return 0;
431 }
432 if (in == null) {
433 return 0;
434 }
435
436 int msgCount = in.size();
437 if (msgCount == 0) {
438 return 0;
439 }
440 Object msg = in.current();
441
442 int scheduled;
443 if (msgCount > 1 && in.current() instanceof ByteBuf) {
444 scheduled = ioUringUnsafe().scheduleWriteMultiple(in);
445 } else if (msg instanceof ByteBuf && ((ByteBuf) msg).nioBufferCount() > 1 ||
446 (msg instanceof ByteBufHolder && ((ByteBufHolder) msg).content().nioBufferCount() > 1)) {
447
448 scheduled = ioUringUnsafe().scheduleWriteMultiple(in);
449 } else {
450 scheduled = ioUringUnsafe().scheduleWriteSingle(msg);
451 }
452
453
454
455
456
457 assert scheduled <= Short.MAX_VALUE;
458 numOutstandingWrites = (short) scheduled;
459 return numOutstandingWrites;
460 }
461
462 protected final IoRegistration registration() {
463 assert registration != null;
464 return registration;
465 }
466
467 private void schedulePollOut() {
468 pollOutId = schedulePollAdd(POLL_OUT_SCHEDULED, Native.POLLOUT, false);
469 }
470
471 final void schedulePollRdHup() {
472 pollRdhupId = schedulePollAdd(POLL_RDHUP_SCHEDULED, Native.POLLRDHUP, false);
473 }
474
475 protected abstract boolean isStreamSocket();
476
477 private long schedulePollAdd(int ioMask, int mask, boolean multishot) {
478 assert (ioState & ioMask) == 0;
479 int fd = fd().intValue();
480 IoRegistration registration = registration();
481 IoUringIoOps ops = IoUringIoOps.newPollAdd(
482 fd, (byte) 0, mask, multishot ? Native.IORING_POLL_ADD_MULTI : 0, nextOpsId());
483 long id = registration.submit(ops);
484 if (id != 0) {
485 ioState |= (byte) ioMask;
486 }
487 return id;
488 }
489
490 final void resetCachedAddresses() {
491 local = socket.localAddress();
492 remote = socket.remoteAddress();
493 }
494
495
496
497
498
499 private static short narrowUserData(long userData) {
500 assert userData == (short) userData : "user_data does not fit a short: " + userData;
501 return (short) userData;
502 }
503
504 protected abstract class AbstractUringUnsafe extends AbstractUnsafe implements IoUringIoHandle {
505 private IoUringRecvByteAllocatorHandle allocHandle;
506 private boolean closed;
507 private boolean socketIsEmpty;
508 private ChannelPromise deregisterPromise;
509
510 final WriteOpsSnapshot currentWrite = new WriteOpsSnapshot();
511
512 final ChannelOutboundBuffer originalOutboundBuffer = outboundBuffer();
513
514
515 List<ReferenceCounted> retainedWriteBuffers;
516
517 final long submitWrite(IoUringIoOps ops) {
518 long id = registration().submit(ops);
519 if (id != 0) {
520 currentWrite.copyFrom(ops);
521 }
522 return id;
523 }
524
525
526 final void prepareToDiscardOutboundMessages(ChannelOutboundBuffer buffer) {
527 if (retainedWriteBuffers != null || (ioState & WRITE_SCHEDULED) == 0) {
528 return;
529 }
530 retainedWriteBuffers = numOutstandingWrites != 0 ? retainWriteBuffers(buffer) :
531 Collections.<ReferenceCounted>emptyList();
532 }
533
534 List<ReferenceCounted> retainWriteBuffers(ChannelOutboundBuffer buffer) {
535 return Collections.emptyList();
536 }
537
538 void releaseWriteBuffers(List<ReferenceCounted> buffers, long data) {
539 for (ReferenceCounted buffer : buffers) {
540 ReferenceCountUtil.safeRelease(buffer);
541 }
542 }
543
544
545
546
547
548 protected abstract int scheduleWriteMultiple(ChannelOutboundBuffer in);
549
550
551
552
553
554 protected abstract int scheduleWriteSingle(Object msg);
555
556 @Override
557 public final void handle(IoRegistration registration, IoEvent ioEvent) {
558 IoUringIoEvent event = (IoUringIoEvent) ioEvent;
559 byte op = event.opcode();
560 int res = event.res();
561 int flags = event.flags();
562 long userData = event.userData();
563 switch (op) {
564 case Native.IORING_OP_RECV:
565 case Native.IORING_OP_ACCEPT:
566 case Native.IORING_OP_RECVMSG:
567 case Native.IORING_OP_READ:
568 readComplete(op, res, flags, narrowUserData(userData));
569 break;
570 case Native.IORING_OP_WRITEV:
571 case Native.IORING_OP_SEND:
572 case Native.IORING_OP_SENDMSG:
573 case Native.IORING_OP_WRITE:
574 case Native.IORING_OP_SPLICE:
575 case Native.IORING_OP_SEND_ZC:
576 case Native.IORING_OP_SENDMSG_ZC:
577 writeComplete(op, res, flags, userData);
578 break;
579 case Native.IORING_OP_POLL_ADD:
580 pollAddComplete(res, flags, narrowUserData(userData));
581 break;
582 case Native.IORING_OP_ASYNC_CANCEL:
583 cancelComplete0(op, res, flags, narrowUserData(userData));
584 break;
585 case Native.IORING_OP_CONNECT:
586 connectComplete(op, res, flags, userData);
587
588 break;
589 case Native.IORING_OP_CLOSE:
590 if (res != Native.ERRNO_ECANCELED_NEGATIVE) {
591 if (delayedClose != null) {
592 delayedClose.promise.setSuccess();
593 }
594 closed = true;
595 }
596 break;
597 default:
598 break;
599 }
600
601
602
603 handleDelayedClosed();
604
605 if (ioState == 0 && (closed || !isRegistered())) {
606
607 registration.cancel();
608 }
609 }
610
611 @Override
612 public void unregistered() {
613 freeMsgHdrArray();
614 freeRemoteAddressMemory();
615 assert retainedWriteBuffers == null;
616
617
618 if (deregisterPromise != null) {
619 ChannelPromise promise = deregisterPromise;
620 deregisterPromise = null;
621 promise.setSuccess();
622 }
623 }
624
625 private void handleDelayedClosed() {
626 if (delayedClose != null && canCloseNow()) {
627 closeNow();
628 }
629 }
630
631 private void pollAddComplete(int res, int flags, short data) {
632 if ((res & Native.POLLOUT) != 0) {
633 pollOut(res);
634 }
635 if ((res & Native.POLLIN) != 0) {
636 pollIn(res, flags, data);
637 }
638 if ((res & Native.POLLRDHUP) != 0) {
639 pollRdHup(res);
640 }
641 }
642
643 @Override
644 public final void close() throws Exception {
645 close(voidPromise());
646 }
647
648 @Override
649 protected void close(ChannelPromise promise, Throwable cause, ClosedChannelException closeCause) {
650 if (closeFuture().isDone()) {
651
652 safeSetSuccess(promise);
653 return;
654 }
655 if (delayedClose == null) {
656
657
658
659 delayedClose = new DelayedClose(promise.isVoid() ? newPromise() : promise, cause, closeCause);
660 } else {
661 delayedClose.promise.addListener(new PromiseNotifier<>(false, promise));
662 return;
663 }
664
665 boolean cancelConnect = connectId != 0;
666 try {
667 ChannelPromise connectPromise = AbstractIoUringChannel.this.connectPromise;
668 if (connectPromise != null) {
669
670 connectPromise.tryFailure(new ClosedChannelException());
671 AbstractIoUringChannel.this.connectPromise = null;
672 cancelConnect = true;
673 }
674
675 cancelConnectTimeoutFuture();
676 } finally {
677
678
679 cancelOps(cancelConnect);
680 }
681
682 if (canCloseNow()) {
683
684 closeNow();
685 }
686 }
687
688 private boolean cancelOps(boolean cancelConnect) {
689 if (registration == null || !registration.isValid()) {
690 return false;
691 }
692 boolean cancelled = false;
693 byte flags = (byte) 0;
694 if ((ioState & POLL_RDHUP_SCHEDULED) != 0 && pollRdhupId != 0) {
695 long id = registration.submit(
696 IoUringIoOps.newAsyncCancel(flags, pollRdhupId, Native.IORING_OP_POLL_ADD));
697 assert id != 0;
698 pollRdhupId = 0;
699 cancelled = true;
700 }
701 if ((ioState & POLL_IN_SCHEDULED) != 0 && pollInId != 0) {
702 long id = registration.submit(
703 IoUringIoOps.newAsyncCancel(flags, pollInId, Native.IORING_OP_POLL_ADD));
704 assert id != 0;
705 pollInId = 0;
706 cancelled = true;
707 }
708 if ((ioState & POLL_OUT_SCHEDULED) != 0 && pollOutId != 0) {
709 long id = registration.submit(
710 IoUringIoOps.newAsyncCancel(flags, pollOutId, Native.IORING_OP_POLL_ADD));
711 assert id != 0;
712 pollOutId = 0;
713 cancelled = true;
714 }
715 if (cancelConnect && connectId != 0) {
716
717 long id = registration.submit(IoUringIoOps.newAsyncCancel(flags, connectId, Native.IORING_OP_CONNECT));
718 assert id != 0;
719 connectId = 0;
720 cancelled = true;
721 }
722 if (numOutstandingReads != 0 || numOutstandingWrites != 0) {
723 cancelled = true;
724 }
725 cancelOutstandingReads(registration, numOutstandingReads);
726 cancelOutstandingWrites(registration, numOutstandingWrites);
727 return cancelled;
728 }
729
730 private boolean canCloseNow() {
731
732
733 return canCloseNow0() && (ioState & (WRITE_SCHEDULED | READ_SCHEDULED)) == 0;
734 }
735
736 protected boolean canCloseNow0() {
737 return true;
738 }
739
740 private void closeNow() {
741 super.close(newPromise(), delayedClose.cause, delayedClose.closeCause);
742 }
743
744 @Override
745 protected final void flush0() {
746
747
748
749 if ((ioState & POLL_OUT_SCHEDULED) == 0) {
750 ChannelOutboundBuffer in = outboundBuffer();
751 if (in != null && !in.isEmpty() && !isActive()) {
752
753 prepareToDiscardOutboundMessages(in);
754 }
755 super.flush0();
756 }
757 }
758
759 private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) {
760 if (promise == null) {
761
762 return;
763 }
764
765
766 promise.tryFailure(cause);
767 closeIfClosed();
768 }
769
770 private void fulfillConnectPromise(ChannelPromise promise, boolean wasActive) {
771 if (promise == null) {
772
773 return;
774 }
775 active = true;
776
777 if (local == null) {
778 local = socket.localAddress();
779 }
780 computeRemote();
781
782 if (isStreamSocket()) {
783
784 schedulePollRdHup();
785 }
786
787
788
789 boolean active = isActive();
790
791
792 boolean promiseSet = promise.trySuccess();
793
794
795
796 if (!wasActive && active) {
797 pipeline().fireChannelActive();
798 }
799
800
801 if (!promiseSet) {
802 close(voidPromise());
803 }
804 }
805
806 @Override
807 public final IoUringRecvByteAllocatorHandle recvBufAllocHandle() {
808 if (allocHandle == null) {
809 allocHandle = new IoUringRecvByteAllocatorHandle(
810 (RecvByteBufAllocator.ExtendedHandle) super.recvBufAllocHandle());
811 }
812 return allocHandle;
813 }
814
815 final void shutdownInput(boolean allDataRead) {
816 logger.trace("shutdownInput Fd: {}", fd().intValue());
817 if (!socket.isInputShutdown()) {
818 if (isAllowHalfClosure(config())) {
819 try {
820 socket.shutdown(true, false);
821 } catch (IOException ignored) {
822
823
824 fireEventAndClose(ChannelInputShutdownEvent.INSTANCE);
825 return;
826 } catch (NotYetConnectedException ignore) {
827
828
829 }
830 pipeline().fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
831 } else {
832
833 inputClosedSeenErrorOnRead = true;
834 close(voidPromise());
835 return;
836 }
837 }
838 if (allDataRead && !inputClosedSeenErrorOnRead) {
839 inputClosedSeenErrorOnRead = true;
840 pipeline().fireUserEventTriggered(ChannelInputShutdownReadComplete.INSTANCE);
841 }
842 }
843
844 private void fireEventAndClose(Object evt) {
845 pipeline().fireUserEventTriggered(evt);
846 close(voidPromise());
847 }
848
849 final void schedulePollIn() {
850 assert (ioState & POLL_IN_SCHEDULED) == 0;
851 if (!isActive() || shouldBreakIoUringInReady(config())) {
852 return;
853 }
854 pollInId = schedulePollAdd(POLL_IN_SCHEDULED, Native.POLLIN, allowMultiShotPollIn());
855 }
856
857 protected final boolean isReadMultishot() {
858 return numOutstandingReads == -1;
859 }
860
861 private void readComplete(byte op, int res, int flags, short data) {
862 assert numOutstandingReads > 0 || numOutstandingReads == -1 : numOutstandingReads;
863
864 boolean multishot = isReadMultishot();
865 boolean rearm = (flags & Native.IORING_CQE_F_MORE) == 0;
866 boolean pending = readPending;
867 if (multishot) {
868 if (rearm) {
869
870 ioState &= ~READ_SCHEDULED;
871 }
872
873
874 readPending = false;
875 } else if (--numOutstandingReads == 0) {
876
877 readPending = false;
878 ioState &= ~READ_SCHEDULED;
879 }
880 inReadComplete = true;
881 try {
882 socketIsEmpty = socketIsEmpty(flags);
883 socketHasMoreData = IoUring.isCqeFSockNonEmptySupported() &&
884 (flags & Native.IORING_CQE_F_SOCK_NONEMPTY) != 0;
885 readComplete0(op, res, flags, data, numOutstandingReads);
886 } finally {
887 try {
888
889 if (recvBufAllocHandle().isReadComplete()) {
890
891 recvBufAllocHandle().reset(config());
892
893
894 if (!multishot) {
895 if (readPending) {
896
897
898 doBeginReadNow();
899 }
900 } else {
901
902
903
904 if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
905
906
907
908
909 if (pending) {
910 readPending = true;
911 doBeginReadNow();
912 }
913 } else if (rearm) {
914
915 doBeginReadNow();
916 } else if (!readPending) {
917
918
919 cancelOutstandingReads(registration, numOutstandingReads);
920 }
921 }
922 } else if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
923
924
925
926
927 if (pending) {
928 readPending = true;
929 doBeginReadNow();
930 }
931 } else if (multishot && rearm) {
932
933 doBeginReadNow();
934 }
935 } finally {
936 inReadComplete = false;
937 socketIsEmpty = false;
938 }
939 }
940 }
941
942
943
944
945 protected abstract void readComplete0(byte op, int res, int flags, short data, int outstandingCompletes);
946
947
948
949
950 private void pollRdHup(int res) {
951 ioState &= ~POLL_RDHUP_SCHEDULED;
952 pollRdhupId = 0;
953 if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
954 return;
955 }
956
957
958 recvBufAllocHandle().rdHupReceived();
959
960 if (isActive()) {
961 scheduleFirstReadIfNeeded();
962 } else {
963
964 shutdownInput(false);
965 }
966 }
967
968
969
970
971 private void pollIn(int res, int flags, short data) {
972
973 boolean rearm = (flags & Native.IORING_CQE_F_MORE) == 0;
974 if (rearm) {
975 ioState &= ~POLL_IN_SCHEDULED;
976 pollInId = 0;
977 }
978 if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
979 return;
980 }
981 if (!readPending) {
982
983
984 socketHasMoreData = true;
985 return;
986 }
987 scheduleFirstReadIfNeeded();
988 }
989
990 private void scheduleFirstReadIfNeeded() {
991 if ((ioState & READ_SCHEDULED) == 0) {
992 scheduleFirstRead();
993 }
994 }
995
996 private void scheduleFirstRead() {
997
998 final ChannelConfig config = config();
999 final IoUringRecvByteAllocatorHandle allocHandle = recvBufAllocHandle();
1000 allocHandle.reset(config);
1001 scheduleRead(true);
1002 }
1003
1004 protected final void scheduleRead(boolean first) {
1005
1006 if (delayedClose == null && fd().isOpen() && (ioState & READ_SCHEDULED) == 0) {
1007 numOutstandingReads = (short) scheduleRead0(first, socketIsEmpty);
1008 if (numOutstandingReads > 0 || numOutstandingReads == -1) {
1009 ioState |= READ_SCHEDULED;
1010 }
1011 }
1012 }
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024 protected abstract int scheduleRead0(boolean first, boolean socketIsEmpty);
1025
1026
1027
1028
1029
1030
1031 private void pollOut(int res) {
1032 ioState &= ~POLL_OUT_SCHEDULED;
1033 pollOutId = 0;
1034 if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
1035 return;
1036 }
1037
1038 if (connectPromise != null) {
1039
1040
1041
1042 assert eventLoop().inEventLoop();
1043
1044 boolean connectStillInProgress = false;
1045 try {
1046 boolean wasActive = isActive();
1047 if (!socket.finishConnect()) {
1048 connectStillInProgress = true;
1049 return;
1050 }
1051 fulfillConnectPromise(connectPromise, wasActive);
1052 } catch (Throwable t) {
1053 fulfillConnectPromise(connectPromise, annotateConnectException(t, requestedRemoteAddress));
1054 } finally {
1055 if (!connectStillInProgress) {
1056
1057
1058
1059 cancelConnectTimeoutFuture();
1060 connectPromise = null;
1061 } else {
1062
1063 schedulePollOut();
1064 }
1065 }
1066 } else if (!socket.isOutputShutdown()) {
1067
1068 flush0();
1069 }
1070 }
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080 private void writeComplete(byte op, int res, int flags, long data) {
1081
1082
1083 if ((ioState & CONNECT_SCHEDULED) != 0 && op == Native.IORING_OP_SENDMSG &&
1084 (currentWrite.union3() & Native.MSG_FASTOPEN) != 0) {
1085 completeFastOpenWrite(op, res, flags, (short) data);
1086 return;
1087 }
1088
1089 if ((flags & Native.IORING_CQE_F_NOTIF) == 0) {
1090 assert numOutstandingWrites > 0;
1091 --numOutstandingWrites;
1092 }
1093
1094 boolean writtenAll = retainedWriteBuffers == null ?
1095 writeComplete0(op, res, flags, data, numOutstandingWrites) :
1096 writeCompleteAndReleaseBuffers(op, res, flags, data);
1097 if (!writtenAll && delayedClose == null && (ioState & POLL_OUT_SCHEDULED) == 0) {
1098
1099
1100 schedulePollOut();
1101 }
1102
1103
1104
1105 if (numOutstandingWrites == 0) {
1106 retainedWriteBuffers = null;
1107 ioState &= ~WRITE_SCHEDULED;
1108
1109
1110 if (writtenAll && (ioState & POLL_OUT_SCHEDULED) == 0) {
1111 scheduleWriteIfNeeded(unsafe().outboundBuffer(), false);
1112 }
1113 }
1114 }
1115
1116 private boolean writeCompleteAndReleaseBuffers(byte op, int res, int flags, long data) {
1117
1118 boolean writtenAll = writeComplete0(op, res, flags, data, numOutstandingWrites);
1119 if ((flags & Native.IORING_CQE_F_NOTIF) == 0) {
1120 releaseWriteBuffers(retainedWriteBuffers, data);
1121 }
1122 return writtenAll;
1123 }
1124
1125 private void completeFastOpenWrite(byte op, int res, int flags, short data) {
1126
1127 assert numOutstandingWrites == 1;
1128 --numOutstandingWrites;
1129 connectId = 0;
1130 freeMsgHdrArray();
1131 try {
1132 if (res > 0) {
1133
1134 if (retainedWriteBuffers == null) {
1135 fastOpenBytes = res;
1136 }
1137
1138
1139 connectComplete(op, 0, flags, data);
1140 removeFastOpenData();
1141 } else if (res == ERRNO_EINPROGRESS_NEGATIVE || res == 0) {
1142
1143 removeFastOpenData();
1144 if (connectPromise != null && !connectPromise.isDone()) {
1145 submitConnect((InetSocketAddress) requestedRemoteAddress);
1146 } else {
1147 connectComplete(op, Native.ERRNO_ECANCELED_NEGATIVE, flags, data);
1148 }
1149 } else {
1150
1151 removeFastOpenData();
1152 connectComplete(op, res, flags, data);
1153 }
1154 } finally {
1155 if (retainedWriteBuffers != null) {
1156 releaseWriteBuffers(retainedWriteBuffers, data);
1157 }
1158 retainedWriteBuffers = null;
1159 ioState &= ~WRITE_SCHEDULED;
1160 }
1161
1162 if (res > 0 && (ioState & POLL_OUT_SCHEDULED) == 0) {
1163 scheduleWriteIfNeeded(outboundBuffer(), false);
1164 }
1165 }
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175 abstract boolean writeComplete0(byte op, int res, int flags, long data, int outstanding);
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185 void cancelComplete0(byte op, int res, int flags, short data) {
1186
1187 }
1188
1189
1190
1191
1192
1193
1194
1195
1196 void connectComplete(byte op, int res, int flags, long data) {
1197 ioState &= ~CONNECT_SCHEDULED;
1198 connectId = 0;
1199 freeRemoteAddressMemory();
1200
1201 if (res == ERRNO_EINPROGRESS_NEGATIVE || res == ERROR_EALREADY_NEGATIVE) {
1202
1203 schedulePollOut();
1204 } else {
1205 try {
1206 if (res == 0) {
1207 fulfillConnectPromise(connectPromise, active);
1208 if (readPending) {
1209 doBeginReadNow();
1210 }
1211 } else {
1212 try {
1213 Errors.throwConnectException("io_uring connect", res);
1214 } catch (Throwable cause) {
1215 fulfillConnectPromise(connectPromise, cause);
1216 }
1217 }
1218 } finally {
1219
1220
1221
1222 cancelConnectTimeoutFuture();
1223 connectPromise = null;
1224 }
1225 }
1226 }
1227
1228 @Override
1229 public void connect(
1230 final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {
1231
1232
1233 if (promise.isDone() || !ensureOpen(promise)) {
1234 return;
1235 }
1236
1237 if (delayedClose != null) {
1238 promise.tryFailure(annotateConnectException(new ClosedChannelException(), remoteAddress));
1239 return;
1240 }
1241 try {
1242 if (connectPromise != null) {
1243 throw new ConnectionPendingException();
1244 }
1245 if (localAddress instanceof InetSocketAddress) {
1246 checkResolvable((InetSocketAddress) localAddress);
1247 }
1248
1249 if (remoteAddress instanceof InetSocketAddress) {
1250 checkResolvable((InetSocketAddress) remoteAddress);
1251 }
1252
1253 if (remote != null) {
1254
1255
1256
1257 throw new AlreadyConnectedException();
1258 }
1259
1260 if (localAddress != null) {
1261 socket.bind(localAddress);
1262 }
1263
1264 if (remoteAddress instanceof InetSocketAddress) {
1265 InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
1266 ByteBuf initialData = null;
1267 if (IoUring.isTcpFastOpenClientSideAvailable() &&
1268 config().getOption(ChannelOption.TCP_FASTOPEN_CONNECT) == Boolean.TRUE) {
1269 ChannelOutboundBuffer outbound = unsafe().outboundBuffer();
1270 outbound.addFlush();
1271 Object curr;
1272 if ((curr = outbound.current()) instanceof ByteBuf) {
1273 initialData = (ByteBuf) curr;
1274 }
1275 }
1276 if (initialData != null) {
1277 MsgHdrMemory hdr = writeMsgHdr();
1278 fillTFOInitData(hdr, inetSocketAddress, initialData);
1279
1280 int fd = fd().intValue();
1281 IoUringIoOps ops = IoUringIoOps.newSendmsg(fd, (byte) 0, Native.MSG_FASTOPEN,
1282 hdr.address(), nextOpsId());
1283 try {
1284 connectId = submitWrite(ops);
1285 if (connectId != 0) {
1286 numOutstandingWrites = 1;
1287 ioState |= WRITE_SCHEDULED;
1288 }
1289 } finally {
1290 if (connectId == 0) {
1291 freeMsgHdrArray();
1292 } else {
1293 fastOpenOutboundBuffer = unsafe().outboundBuffer();
1294 fastOpenData = initialData;
1295 }
1296 }
1297 } else {
1298 submitConnect(inetSocketAddress);
1299 }
1300 } else if (remoteAddress instanceof DomainSocketAddress) {
1301 DomainSocketAddress unixDomainSocketAddress = (DomainSocketAddress) remoteAddress;
1302 submitConnect(unixDomainSocketAddress);
1303 } else {
1304 throw new Error("Unexpected SocketAddress implementation " + className(remoteAddress));
1305 }
1306
1307 if (connectId != 0) {
1308 ioState |= CONNECT_SCHEDULED;
1309 }
1310 } catch (Throwable t) {
1311 closeIfClosed();
1312 promise.tryFailure(annotateConnectException(t, remoteAddress));
1313 return;
1314 }
1315 connectPromise = promise;
1316 requestedRemoteAddress = remoteAddress;
1317
1318 int connectTimeoutMillis = config().getConnectTimeoutMillis();
1319 if (connectTimeoutMillis > 0) {
1320 connectTimeoutFuture = eventLoop().schedule(new Runnable() {
1321 @Override
1322 public void run() {
1323 ChannelPromise connectPromise = AbstractIoUringChannel.this.connectPromise;
1324 if (connectPromise != null && !connectPromise.isDone() &&
1325 connectPromise.tryFailure(new ConnectTimeoutException(
1326 "connection timed out: " + remoteAddress))) {
1327 close(voidPromise());
1328 }
1329 }
1330 }, connectTimeoutMillis, TimeUnit.MILLISECONDS);
1331 }
1332
1333 promise.addListener(new ChannelFutureListener() {
1334 @Override
1335 public void operationComplete(ChannelFuture future) {
1336
1337
1338 if (future.isCancelled()) {
1339 cancelConnectTimeoutFuture();
1340 connectPromise = null;
1341 close(voidPromise());
1342 }
1343 }
1344 });
1345 }
1346
1347 private void fillTFOInitData(MsgHdrMemory hdr, InetSocketAddress inetSocketAddress,
1348 ByteBuf initialData) throws Exception {
1349 if (initialData.hasMemoryAddress()) {
1350 hdr.set(socket, inetSocketAddress,
1351 initialData.memoryAddress() + initialData.readerIndex(),
1352 initialData.readableBytes(), (short) 0);
1353 } else {
1354
1355
1356 IoUringIoHandler handler = registration().attachment();
1357 IovArray iovArray = handler.iovArray();
1358 int iovOffset = iovArray.count();
1359 iovArray.processMessage(initialData);
1360 long iovArrayAddress = iovArray.memoryAddress(iovOffset);
1361 int iovArrayLength = iovArray.count() - iovOffset;
1362 hdr.setWithIovArrayAddress(socket, inetSocketAddress, iovArrayAddress, iovArrayLength, (short) 0);
1363 }
1364 }
1365
1366 @Override
1367 public final void deregister(ChannelPromise promise) {
1368 if (deregisterPromise != null) {
1369
1370 PromiseNotifier.cascade(deregisterPromise, promise);
1371 } else if (!isRegistered()) {
1372 promise.setSuccess();
1373 } else {
1374
1375
1376 deregisterPromise = promise;
1377 super.deregister(newPromise().addListener(f -> {
1378 if (!f.isSuccess()) {
1379 this.deregisterPromise = null;
1380 promise.setFailure(f.cause());
1381 }
1382 }));
1383 }
1384 }
1385 }
1386
1387 private void submitConnect(InetSocketAddress inetSocketAddress) {
1388 cleanable = Buffer.allocateDirectBufferWithNativeOrder(Native.SIZEOF_SOCKADDR_STORAGE);
1389 remoteAddressMemory = cleanable.buffer();
1390
1391 SockaddrIn.set(socket.isIpv6(), remoteAddressMemory, inetSocketAddress);
1392
1393 int fd = fd().intValue();
1394 IoRegistration registration = registration();
1395 IoUringIoOps ops = IoUringIoOps.newConnect(
1396 fd, (byte) 0, Buffer.memoryAddress(remoteAddressMemory), nextOpsId());
1397 connectId = registration.submit(ops);
1398 if (connectId == 0) {
1399
1400 freeRemoteAddressMemory();
1401 }
1402 }
1403
1404 private void submitConnect(DomainSocketAddress unixDomainSocketAddress) {
1405 cleanable = Buffer.allocateDirectBufferWithNativeOrder(Native.SIZEOF_SOCKADDR_UN);
1406 remoteAddressMemory = cleanable.buffer();
1407 int addrLen = SockaddrIn.setUds(remoteAddressMemory, unixDomainSocketAddress);
1408 int fd = fd().intValue();
1409 IoRegistration registration = registration();
1410 long addr = Buffer.memoryAddress(remoteAddressMemory);
1411 IoUringIoOps ops = IoUringIoOps.newConnect(fd, (byte) 0, addr, addrLen, nextOpsId());
1412 connectId = registration.submit(ops);
1413 if (connectId == 0) {
1414
1415 freeRemoteAddressMemory();
1416 }
1417 }
1418
1419 @Override
1420 protected Object filterOutboundMessage(Object msg) {
1421 if (msg instanceof ByteBuf) {
1422 ByteBuf buf = (ByteBuf) msg;
1423 return UnixChannelUtil.isBufferCopyNeededForWrite(buf)? newDirectBuffer(buf) : buf;
1424 }
1425 throw new UnsupportedOperationException("unsupported message type: " + StringUtil.simpleClassName(msg));
1426 }
1427
1428 @Override
1429 protected void doRegister(ChannelPromise promise) {
1430 IoEventLoop eventLoop = (IoEventLoop) eventLoop();
1431 eventLoop.register(ioUringUnsafe()).addListener(f -> {
1432 if (f.isSuccess()) {
1433 registration = (IoRegistration) f.getNow();
1434 promise.setSuccess();
1435 } else {
1436 promise.setFailure(f.cause());
1437 }
1438 });
1439 }
1440
1441 @Override
1442 protected final void doDeregister() {
1443
1444 if (!ioUringUnsafe().cancelOps(connectPromise != null)) {
1445
1446
1447 if (registration != null) {
1448 registration.cancel();
1449 }
1450 }
1451 }
1452
1453 @Override
1454 protected void doBind(final SocketAddress local) throws Exception {
1455 if (local instanceof InetSocketAddress) {
1456 checkResolvable((InetSocketAddress) local);
1457 }
1458 socket.bind(local);
1459 this.local = socket.localAddress();
1460 }
1461
1462 protected static void checkResolvable(InetSocketAddress addr) {
1463 if (addr.isUnresolved()) {
1464 throw new UnresolvedAddressException();
1465 }
1466 }
1467
1468 @Override
1469 protected final SocketAddress localAddress0() {
1470 return local;
1471 }
1472
1473 @Override
1474 protected final SocketAddress remoteAddress0() {
1475 return remote;
1476 }
1477
1478 private static boolean isAllowHalfClosure(ChannelConfig config) {
1479 return config instanceof SocketChannelConfig &&
1480 ((SocketChannelConfig) config).isAllowHalfClosure();
1481 }
1482
1483 private void cancelConnectTimeoutFuture() {
1484 if (connectTimeoutFuture != null) {
1485 connectTimeoutFuture.cancel(false);
1486 connectTimeoutFuture = null;
1487 }
1488 }
1489
1490 private void computeRemote() {
1491 if (requestedRemoteAddress instanceof InetSocketAddress) {
1492 remote = computeRemoteAddr((InetSocketAddress) requestedRemoteAddress, socket.remoteAddress());
1493 }
1494 }
1495
1496 private boolean shouldBreakIoUringInReady(ChannelConfig config) {
1497 return socket.isInputShutdown() && (inputClosedSeenErrorOnRead || !isAllowHalfClosure(config));
1498 }
1499
1500
1501
1502
1503
1504
1505
1506 protected abstract boolean socketIsEmpty(int flags);
1507
1508 abstract boolean isPollInFirst();
1509 }