View Javadoc
1   /*
2    * Copyright 2024 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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      // Different masks for outstanding I/O operations.
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      // A byte is enough for now.
98      private byte ioState;
99  
100     // It's possible that multiple read / writes are issued. We need to keep track of these.
101     // Let's limit the amount of pending writes and reads by Short.MAX_VALUE. Maybe Byte.MAX_VALUE would also be good
102     // enough but let's be a bit more flexible for now.
103     private short numOutstandingWrites;
104     // A value of -1 means that multi-shot is used and so reads will be issued as long as the request is not canceled.
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      * The future of the current connection attempt.  If not null, subsequent connection attempts will fail.
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     // The initial data of a TCP_FASTOPEN_CONNECT and the number of its bytes that were sent. These bytes are only
136     // removed from the ChannelOutboundBuffer once the connect is complete, so listeners of the initial write see an
137     // active channel.
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             // Directly cache the remote and local addresses
153             // See https://github.com/netty/netty/issues/2359
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         // Directly cache the remote and local addresses
168         // See https://github.com/netty/netty/issues/2359
169         this.remote = remote;
170         this.local = fd.localAddress();
171     }
172 
173     // Called once a Channel changed from AUTO_READ=true to AUTO_READ=false
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         // Also cancel all outstanding reads as the user did signal there is no more desire to read.
197         cancelOutstandingReads(registration(), numOutstandingReads);
198     }
199 
200     /**
201      * Returns the next id that should be used when submitting {@link IoUringIoOps}.
202      *
203      * @return  opsId
204      */
205     protected final short nextOpsId() {
206         short id = opsId++;
207 
208         // We use 0 for "none".
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      * Cancel all outstanding reads
277      *
278      * @param registration          the {@link IoRegistration}.
279      * @param numOutstandingReads   the number of outstanding reads, or {@code -1} if multi-shot was used.
280      */
281     protected abstract void cancelOutstandingReads(IoRegistration registration, int numOutstandingReads);
282 
283     /**
284      * Cancel all outstanding writes
285      *
286      * @param registration          the {@link IoRegistration}.
287      * @param numOutstandingWrites  the number of outstanding writes.
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             // This one was never registered just use a syscall to close.
329             socket.close();
330             ioUringUnsafe().unregistered();
331         }
332     }
333 
334     @Override
335     protected final void doShutdownOutput() throws Exception {
336         // The initial data that was sent by TCP_FASTOPEN_CONNECT must not be failed when shutting down the output.
337         removeFastOpenData();
338         // AbstractUnsafe has already cleared outboundBuffer and fails flushed messages after this method returns.
339         AbstractUringUnsafe unsafe = ioUringUnsafe();
340         unsafe.prepareToDiscardOutboundMessages(unsafe.originalOutboundBuffer);
341         doShutdownOutput0();
342     }
343 
344     /**
345      * Removes the bytes that were sent by a TCP_FASTOPEN_CONNECT from the {@link ChannelOutboundBuffer} if the
346      * channel was connected, and forgets about them otherwise. Must be called before the
347      * {@link ChannelOutboundBuffer} is written or its messages are failed.
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      * Performs the actual output shutdown. Overridden by subclasses that support it.
366      */
367     protected void doShutdownOutput0() throws Exception {
368         super.doShutdownOutput();
369     }
370 
371     @Override
372     protected final void doBeginRead() {
373         if (inputClosedSeenErrorOnRead) {
374             // We did see an error while reading and so closed the input. Stop reading.
375             return;
376         }
377         if (readPending) {
378             // We already have a read pending.
379             return;
380         }
381         readPending = true;
382         if (inReadComplete || !isActive()) {
383             // We are currently in the readComplete(...) callback which might issue more reads by itself.
384             // If readComplete(...) will not issue more reads itself it will pick up the readPending flag, reset it and
385             // call doBeginReadNow().
386             return;
387         }
388         doBeginReadNow();
389     }
390 
391     private void doBeginReadNow() {
392         if (inputClosedSeenErrorOnRead) {
393             // We did see an error while reading and so closed the input.
394             return;
395         }
396         if (!isPollInFirst() ||
397                 // If the socket was not empty, and we stopped reading we need to ensure we just force the
398                 // read as POLLIN might be edge-triggered (in case of POLL_ADD_MULTI).
399                 socketHasMoreData) {
400             // If the socket is blocking we will directly call scheduleFirstReadIfNeeded() as we can use FASTPOLL.
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         // NOOP
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             // We also need some special handling for CompositeByteBuf
448             scheduled = ioUringUnsafe().scheduleWriteMultiple(in);
449         } else {
450             scheduled = ioUringUnsafe().scheduleWriteSingle(msg);
451         }
452         // A zero return means the write could not be scheduled: registration.submit(...) failed because the
453         // registration is no longer valid, a FileRegion's open() threw, or transferTo(...) produced no bytes or
454         // threw. numOutstandingWrites is a short, so guard the narrowing before it happens: a future
455         // scheduleWriteSingle/scheduleWriteMultiple override that batches more writes than a short can hold must
456         // not silently wrap around.
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     // Write completions may carry an id that fell back out of the short range, so they get the untruncated
496     // user_data. Connect completions always submit a short id, but connectComplete(...) takes a long to stay
497     // consistent with writeComplete(...), so it is also handed the untruncated value. The remaining completions
498     // (read, poll, cancel) only ever submit short ids, so narrowUserData(...) below asserts and narrows those.
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         // Only one primary write batch is submitted at a time. Notifications belong to older zero-copy writes.
510         final WriteOpsSnapshot currentWrite = new WriteOpsSnapshot();
511         // Never null, unlike outboundBuffer(). Only used to retain in-flight writes after shutdownOutput().
512         final ChannelOutboundBuffer originalOutboundBuffer = outboundBuffer();
513         // References retained before outbound messages are released. Non-null until the batch completes,
514         // even when empty, so subsequent completions no longer consume the outbound queue.
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         // Must be called before AbstractUnsafe fails flushed messages that in-flight writes may still use.
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          * Schedule the write of multiple messages in the {@link ChannelOutboundBuffer} and returns the number of
546          * {@link #writeComplete(byte, int, int, long)} calls that are expected because of the scheduled write.
547          */
548         protected abstract int scheduleWriteMultiple(ChannelOutboundBuffer in);
549 
550         /**
551          * Schedule the write of a single message and returns the number of
552          * {@link #writeComplete(byte, int, int, long)} calls that are expected because of the scheduled write.
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             // We delay the actual close if there is still a write or read scheduled, let's see if there
602             // was a close that needs to be done now.
603             handleDelayedClosed();
604 
605             if (ioState == 0 && (closed || !isRegistered())) {
606                 // Cancel the registration now.
607                 registration.cancel();
608             }
609         }
610 
611         @Override
612         public void unregistered() {
613             freeMsgHdrArray();
614             freeRemoteAddressMemory();
615             assert retainedWriteBuffers == null;
616 
617             // Check if we need to notify about the deregistration.
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                 // Closed already before.
652                 safeSetSuccess(promise);
653                 return;
654             }
655             if (delayedClose == null) {
656                 // We have a write operation pending that should be completed asap.
657                 // We will do the actual close operation one this write result is returned as otherwise
658                 // we may get into trouble as we may close the fd while we did not process the write yet.
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                     // Use tryFailure() instead of setFailure() to avoid the race against cancel().
670                     connectPromise.tryFailure(new ClosedChannelException());
671                     AbstractIoUringChannel.this.connectPromise = null;
672                     cancelConnect = true;
673                 }
674 
675                 cancelConnectTimeoutFuture();
676             } finally {
677                 // It's important we cancel all outstanding connect, write and read operations now so
678                 // we will be able to process a delayed close if needed.
679                 cancelOps(cancelConnect);
680             }
681 
682             if (canCloseNow()) {
683                 // Currently there are is no WRITE and READ scheduled so we can start to teardown the channel.
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                 // Best effort to cancel the already submitted connect request.
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             // Currently there are is no WRITE and READ scheduled, we can close the channel now without
732             // problems related to re-ordering of completions.
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             // Flush immediately only when there's no pending flush.
747             // If there's a pending flush operation, event loop will call forceFlush() later,
748             // and thus there's no need to call it now.
749             if ((ioState & POLL_OUT_SCHEDULED) == 0) {
750                 ChannelOutboundBuffer in = outboundBuffer();
751                 if (in != null && !in.isEmpty() && !isActive()) {
752                     // super.flush0() fails flushed messages when the channel is inactive.
753                     prepareToDiscardOutboundMessages(in);
754                 }
755                 super.flush0();
756             }
757         }
758 
759         private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) {
760             if (promise == null) {
761                 // Closed via cancellation and the promise has been notified already.
762                 return;
763             }
764 
765             // Use tryFailure() instead of setFailure() to avoid the race against cancel().
766             promise.tryFailure(cause);
767             closeIfClosed();
768         }
769 
770         private void fulfillConnectPromise(ChannelPromise promise, boolean wasActive) {
771             if (promise == null) {
772                 // Closed via cancellation and the promise has been notified already.
773                 return;
774             }
775             active = true;
776 
777             if (local == null) {
778                 local = socket.localAddress();
779             }
780             computeRemote();
781 
782             if (isStreamSocket()) {
783                 // Register POLLRDHUP
784                 schedulePollRdHup();
785             }
786 
787             // Get the state as trySuccess() may trigger an ChannelFutureListener that will close the Channel.
788             // We still need to ensure we call fireChannelActive() in this case.
789             boolean active = isActive();
790 
791             // trySuccess() will return false if a user cancelled the connection attempt.
792             boolean promiseSet = promise.trySuccess();
793 
794             // Regardless if the connection attempt was cancelled, channelActive() event should be triggered,
795             // because what happened is what happened.
796             if (!wasActive && active) {
797                 pipeline().fireChannelActive();
798             }
799 
800             // If a user cancelled the connection attempt, close the channel, which is followed by channelInactive().
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                         // We attempted to shutdown and failed, which means the input has already effectively been
823                         // shutdown.
824                         fireEventAndClose(ChannelInputShutdownEvent.INSTANCE);
825                         return;
826                     } catch (NotYetConnectedException ignore) {
827                         // We attempted to shutdown and failed, which means the input has already effectively been
828                         // shutdown.
829                     }
830                     pipeline().fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
831                 } else {
832                     // Handle this same way as if we did read all data so we don't schedule another read.
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                     // Reset READ_SCHEDULED if there is nothing more to handle and so we need to re-arm.
870                     ioState &= ~READ_SCHEDULED;
871                 }
872                 // Reset readPending so we can still keep track if we might need to cancel the multi-shot read or
873                 // not.
874                 readPending = false;
875             } else if (--numOutstandingReads == 0) {
876                 // We received all outstanding completions.
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                     // Check if we should consider the read loop to be done.
889                     if (recvBufAllocHandle().isReadComplete()) {
890                         // Reset the handle as we are done with the read-loop.
891                         recvBufAllocHandle().reset(config());
892 
893                         // Check if this was a readComplete(...) triggered by a read or multi-shot read.
894                         if (!multishot) {
895                             if (readPending) {
896                                 // This was a "normal" read and the user did signal we should continue reading.
897                                 // Let's schedule the read now.
898                                 doBeginReadNow();
899                             }
900                         } else {
901                             // The readComplete(...) was triggered by a multi-shot read. Because of this the state
902                             // machine is a bit more complicated.
903 
904                             if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
905                                 // The readComplete(...) was triggered because the previous read was cancelled.
906                                 // In this case we we need to check if the user did signal the desire to read again
907                                 // in the meantime. If this is the case we need to schedule the read to ensure
908                                 // we do not stall.
909                                 if (pending) {
910                                     readPending = true;
911                                     doBeginReadNow();
912                                 }
913                             } else if (rearm) {
914                                 // We need to rearm the multishot as otherwise we might miss some data.
915                                 doBeginReadNow();
916                             } else if (!readPending) {
917                                 // Cancel the multi-shot read now as the user did not signal that we want to keep
918                                 // reading while we handle the completion event.
919                                 cancelOutstandingReads(registration, numOutstandingReads);
920                             }
921                         }
922                     } else if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
923                         // The readComplete(...) was triggered because the previous read was cancelled.
924                         // In this case we we need to check if the user did signal the desire to read again
925                         // in the meantime. If this is the case we need to schedule the read to ensure
926                         // we do not stall.
927                         if (pending) {
928                             readPending = true;
929                             doBeginReadNow();
930                         }
931                     } else if (multishot && rearm) {
932                         // We need to rearm the multishot as otherwise we might miss some data.
933                         doBeginReadNow();
934                     }
935                 } finally {
936                     inReadComplete = false;
937                     socketIsEmpty = false;
938                 }
939             }
940         }
941 
942         /**
943          * Called once a read was completed.
944          */
945         protected abstract void readComplete0(byte op, int res, int flags, short data, int outstandingCompletes);
946 
947         /**
948          * Called once POLLRDHUP event is ready to be processed
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             // Mark that we received a POLLRDHUP and so need to continue reading until all the input ist drained.
958             recvBufAllocHandle().rdHupReceived();
959 
960             if (isActive()) {
961                 scheduleFirstReadIfNeeded();
962             } else {
963                 // Just to be safe make sure the input marked as closed.
964                 shutdownInput(false);
965             }
966         }
967 
968         /**
969          * Called once POLLIN event is ready to be processed
970          */
971         private void pollIn(int res, int flags, short data) {
972             // Check if we need to rearm. This works for both cases, POLL_ADD and POLL_ADD_MULTI.
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                 // We received the POLLIN but the user is not interested yet in reading, just mark socketHasMoreData
983                 // as true so we will trigger a read directly once the user calls read()
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             // This is a new "read loop" so we need to reset the allocHandle.
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             // Only schedule another read if the fd is still open.
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          * Schedule a read and returns the number of {@link #readComplete(byte, int, int, short)}
1016          * calls that are expected because of the scheduled read.
1017          *
1018          * @param first             {@code true} if this is the first read of a read loop.
1019          * @param socketIsEmpty     {@code true} if the socket is guaranteed to be empty, {@code false} otherwise.
1020          * @return                  the number of {@link #readComplete(byte, int, int, short)} calls expected or
1021          *                          {@code -1} if {@link #readComplete(byte, int, int, short)} is called until
1022          *                          the read is cancelled (multi-shot).
1023          */
1024         protected abstract int scheduleRead0(boolean first, boolean socketIsEmpty);
1025 
1026         /**
1027          * Called once POLLOUT event is ready to be processed
1028          *
1029          * @param res   the result.
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             // pending connect
1038             if (connectPromise != null) {
1039                 // Note this method is invoked by the event loop only if the connection attempt was
1040                 // neither cancelled nor timed out.
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                         // Check for null as the connectTimeoutFuture is only created if a connectTimeoutMillis > 0
1057                         // is used
1058                         // See https://github.com/netty/netty/issues/1770
1059                         cancelConnectTimeoutFuture();
1060                         connectPromise = null;
1061                     } else {
1062                         // The connect was not done yet, register for POLLOUT again
1063                         schedulePollOut();
1064                     }
1065                 }
1066             } else if (!socket.isOutputShutdown()) {
1067                 // Try writing again. POLL_OUT_SCHEDULED is clear, so flush0() retains in-flight writes if inactive.
1068                 flush0();
1069             }
1070         }
1071 
1072         /**
1073          * Called once a write was completed.
1074          *
1075          * @param op    the op code.
1076          * @param res   the result.
1077          * @param flags the flags.
1078          * @param data  the data that was passed when submitting the op.
1079          */
1080         private void writeComplete(byte op, int res, int flags, long data) {
1081             // UDP connect and ordinary writes can be in flight together,
1082             // so CONNECT_SCHEDULED alone cannot identify TFO.
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                 // We were not able to write everything, let's register for POLLOUT
1100                 schedulePollOut();
1101             }
1102 
1103             // We only reset this once we are done with calling removeBytes(...) as otherwise we may trigger a write
1104             // while still removing messages internally in removeBytes(...) which then may corrupt state.
1105             if (numOutstandingWrites == 0) {
1106                 retainedWriteBuffers = null;
1107                 ioState &= ~WRITE_SCHEDULED;
1108 
1109                 // If we could write all and we did not schedule a pollout yet let us try to write again
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             // The socket may transfer these references to its zero-copy notification before we release them.
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             // TFO participates in the write count, but completes through the connect path.
1127             assert numOutstandingWrites == 1;
1128             --numOutstandingWrites;
1129             connectId = 0;
1130             freeMsgHdrArray();
1131             try {
1132                 if (res > 0) {
1133                     // shutdownOutput() or an inactive flush may already have failed this batch.
1134                     if (retainedWriteBuffers == null) {
1135                         fastOpenBytes = res;
1136                     }
1137                     // Complete connect before notifying the initial write. Keep WRITE_SCHEDULED set so
1138                     // connect listeners cannot submit the initial data again before it is removed.
1139                     connectComplete(op, 0, flags, data);
1140                     removeFastOpenData();
1141                 } else if (res == ERRNO_EINPROGRESS_NEGATIVE || res == 0) {
1142                     // Without a fast-open cookie, connect normally and send the initial data later.
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                     // There was an error, handle it as a normal connect error.
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             // Write the remaining initial data and anything flushed by the connect or write listeners.
1162             if (res > 0 && (ioState & POLL_OUT_SCHEDULED) == 0) {
1163                 scheduleWriteIfNeeded(outboundBuffer(), false);
1164             }
1165         }
1166 
1167         /**
1168          * Called once a write was completed.
1169          * @param op            the op code
1170          * @param res           the result.
1171          * @param flags         the flags.
1172          * @param data          the data that was passed when submitting the op.
1173          * @param outstanding   the outstanding write completions.
1174          */
1175         abstract boolean writeComplete0(byte op, int res, int flags, long data, int outstanding);
1176 
1177         /**
1178          * Called once a cancel was completed.
1179          *
1180          * @param op            the op code
1181          * @param res           the result.
1182          * @param flags         the flags.
1183          * @param data          the data that was passed when submitting the op.
1184          */
1185         void cancelComplete0(byte op, int res, int flags, short data) {
1186             // NOOP
1187         }
1188 
1189         /**
1190          * Called once a connect was completed.
1191          * @param op            the op code.
1192          * @param res           the result.
1193          * @param flags         the flags.
1194          * @param data          the data that was passed when submitting the op.
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                 // connect not complete yet need to wait for poll_out event
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                     // Check for null as the connectTimeoutFuture is only created if a connectTimeoutMillis > 0 is
1220                     // used
1221                     // See https://github.com/netty/netty/issues/1770
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             // Don't mark the connect promise as uncancellable as in fact we can cancel it as it is using
1232             // non-blocking io.
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                     // Check if already connected before trying to connect. This is needed as connect(...) will not#
1255                     // return -1 and set errno to EISCONN if a previous connect(...) attempt was setting errno to
1256                     // EINPROGRESS and finished later.
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             // Schedule connect timeout.
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                     // If the connect future is cancelled we also cancel the timeout and close the
1337                     // underlying socket.
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                // Use an iovec array for CompositeByteBuf and other buffers without a memory address.
1355                // If the shared IovArray has not enough space, the rest is sent after connect.
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                 // A deregistration is already in progress.
1370                 PromiseNotifier.cascade(deregisterPromise, promise);
1371             } else if (!isRegistered()) {
1372                 promise.setSuccess();
1373             } else {
1374                 // We need to store a reference to the original promise as we should only notify it once we
1375                 // have handles all pending completions.
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             // Directly release the memory if submitting failed.
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             // Directly release the memory if submitting failed.
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         // Cancel all previous submitted ops.
1444         if (!ioUringUnsafe().cancelOps(connectPromise != null)) {
1445             // It's possible that we never registered anything and so we did not submit any ASYNC_CANCEL.
1446             // In this case directly call cancel as we will not receive any completion at all.
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      * Return if the socket is guaranteed to be empty when the submitted io was executed and the completion event be
1502      * created.
1503      * @param flags     the flags that were part of the completion
1504      * @return          {@code true} if empty.
1505      */
1506     protected abstract boolean socketIsEmpty(int flags);
1507 
1508     abstract boolean isPollInFirst();
1509 }