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.channel.Channel;
20  import io.netty.channel.ChannelException;
21  import io.netty.channel.ChannelFuture;
22  import io.netty.channel.ChannelFutureListener;
23  import io.netty.channel.ChannelMetadata;
24  import io.netty.channel.ChannelOutboundBuffer;
25  import io.netty.channel.ChannelPipeline;
26  import io.netty.channel.ChannelPromise;
27  import io.netty.channel.DefaultFileRegion;
28  import io.netty.channel.EventLoop;
29  import io.netty.channel.FileRegion;
30  import io.netty.channel.IoRegistration;
31  import io.netty.channel.socket.DuplexChannel;
32  import io.netty.channel.unix.IovArray;
33  import io.netty.channel.unix.UnixChannelUtil;
34  import io.netty.util.ReferenceCounted;
35  import io.netty.util.internal.SystemPropertyUtil;
36  import io.netty.util.internal.logging.InternalLogger;
37  import io.netty.util.internal.logging.InternalLoggerFactory;
38  
39  import java.io.IOException;
40  import java.net.SocketAddress;
41  import java.nio.ByteBuffer;
42  import java.nio.channels.FileChannel;
43  import java.nio.channels.WritableByteChannel;
44  import java.util.ArrayList;
45  import java.util.Collections;
46  import java.util.List;
47  
48  import static io.netty.channel.unix.Errors.ioResult;
49  
50  abstract class AbstractIoUringStreamChannel extends AbstractIoUringChannel implements DuplexChannel {
51      private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractIoUringStreamChannel.class);
52      private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
53  
54      /**
55       * Maximum bytes per chunk when converting a generic {@link FileRegion} to a {@link ByteBuf}
56       * for the io_uring async send path. Overridable via the {@code io.netty.iouring.fileRegionChunkSize}
57       * system property; capped at 16 MiB to guard against pathological configurations that would
58       * risk direct-memory OOM.
59       */
60      private static final int FILE_REGION_MAX_CHUNK_SIZE = Math.min(16 * 1024 * 1024,
61              Math.max(1, SystemPropertyUtil.getInt("io.netty.iouring.fileRegionChunkSize", 64 * 1024)));
62  
63      // Store the opCode so we know if we used WRITE or WRITEV.
64      byte writeOpCode;
65      // Keep track of the ids used for write and read so we can cancel these when needed.
66      long writeId;
67      byte readOpCode;
68      long readId;
69  
70      // The configured buffer ring if any
71      private IoUringBufferRing bufferRing;
72  
73      AbstractIoUringStreamChannel(Channel parent, LinuxSocket socket, boolean active) {
74          super(parent, socket, active);
75      }
76  
77      AbstractIoUringStreamChannel(Channel parent, LinuxSocket socket, SocketAddress remote) {
78          super(parent, socket, remote);
79      }
80  
81      @Override
82      protected final boolean isStreamSocket() {
83          return true;
84      }
85  
86      @Override
87      public ChannelMetadata metadata() {
88          return METADATA;
89      }
90  
91      @Override
92      protected AbstractUringUnsafe newUnsafe() {
93          return new IoUringStreamUnsafe();
94      }
95  
96      @Override
97      public final ChannelFuture shutdown() {
98          return shutdown(newPromise());
99      }
100 
101     @Override
102     public final ChannelFuture shutdown(final ChannelPromise promise) {
103         ChannelFuture shutdownOutputFuture = shutdownOutput();
104         if (shutdownOutputFuture.isDone()) {
105             shutdownOutputDone(shutdownOutputFuture, promise);
106         } else {
107             shutdownOutputFuture.addListener(new ChannelFutureListener() {
108                 @Override
109                 public void operationComplete(final ChannelFuture shutdownOutputFuture) throws Exception {
110                     shutdownOutputDone(shutdownOutputFuture, promise);
111                 }
112             });
113         }
114         return promise;
115     }
116 
117     @Override
118     protected final void doShutdownOutput0() throws Exception {
119         socket.shutdown(false, true);
120     }
121 
122     private void shutdownInput0(final ChannelPromise promise) {
123         try {
124             socket.shutdown(true, false);
125             promise.setSuccess();
126         } catch (Throwable cause) {
127             promise.setFailure(cause);
128         }
129     }
130 
131     @Override
132     public final boolean isOutputShutdown() {
133         return socket.isOutputShutdown();
134     }
135 
136     @Override
137     public final boolean isInputShutdown() {
138         return socket.isInputShutdown();
139     }
140 
141     @Override
142     public final boolean isShutdown() {
143         return socket.isShutdown();
144     }
145 
146     @Override
147     public final ChannelFuture shutdownOutput() {
148         return shutdownOutput(newPromise());
149     }
150 
151     @Override
152     public final ChannelFuture shutdownOutput(final ChannelPromise promise) {
153         EventLoop loop = eventLoop();
154         if (loop.inEventLoop()) {
155             ((AbstractUnsafe) unsafe()).shutdownOutput(promise);
156         } else {
157             loop.execute(new Runnable() {
158                 @Override
159                 public void run() {
160                     ((AbstractUnsafe) unsafe()).shutdownOutput(promise);
161                 }
162             });
163         }
164 
165         return promise;
166     }
167 
168     @Override
169     public final ChannelFuture shutdownInput() {
170         return shutdownInput(newPromise());
171     }
172 
173     @Override
174     public final ChannelFuture shutdownInput(final ChannelPromise promise) {
175         EventLoop loop = eventLoop();
176         if (loop.inEventLoop()) {
177             shutdownInput0(promise);
178         } else {
179             loop.execute(new Runnable() {
180                 @Override
181                 public void run() {
182                     shutdownInput0(promise);
183                 }
184             });
185         }
186         return promise;
187     }
188 
189     private void shutdownOutputDone(final ChannelFuture shutdownOutputFuture, final ChannelPromise promise) {
190         ChannelFuture shutdownInputFuture = shutdownInput();
191         if (shutdownInputFuture.isDone()) {
192             shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise);
193         } else {
194             shutdownInputFuture.addListener(new ChannelFutureListener() {
195                 @Override
196                 public void operationComplete(ChannelFuture shutdownInputFuture) throws Exception {
197                     shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise);
198                 }
199             });
200         }
201     }
202 
203     private static void shutdownDone(ChannelFuture shutdownOutputFuture,
204                                      ChannelFuture shutdownInputFuture,
205                                      ChannelPromise promise) {
206         Throwable shutdownOutputCause = shutdownOutputFuture.cause();
207         Throwable shutdownInputCause = shutdownInputFuture.cause();
208         if (shutdownOutputCause != null) {
209             if (shutdownInputCause != null) {
210                 logger.info("Exception suppressed because a previous exception occurred.",
211                              shutdownInputCause);
212             }
213             promise.setFailure(shutdownOutputCause);
214         } else if (shutdownInputCause != null) {
215             promise.setFailure(shutdownInputCause);
216         } else {
217             promise.setSuccess();
218         }
219     }
220 
221     @Override
222     protected final void doRegister(ChannelPromise promise) {
223         ChannelPromise registerPromise = this.newPromise();
224         // Ensure that the buffer group is properly set before channel::read
225         registerPromise.addListener(f -> {
226             if (f.isSuccess()) {
227                try {
228                    short bgid = ((IoUringStreamChannelConfig) config()).getBufferGroupId();
229                    if (bgid >= 0) {
230                        final IoUringIoHandler ioUringIoHandler = registration().attachment();
231                        bufferRing = ioUringIoHandler.findBufferRing(bgid);
232                    }
233                    if (active) {
234                        // Register for POLLRDHUP if this channel is already considered active.
235                        schedulePollRdHup();
236                    }
237                } finally {
238                    promise.setSuccess();
239                }
240             } else {
241                 promise.setFailure(f.cause());
242             }
243         });
244 
245         super.doRegister(registerPromise);
246     }
247 
248     @Override
249     protected Object filterOutboundMessage(Object msg) {
250         if (IoUring.isSpliceSupported() && msg instanceof DefaultFileRegion) {
251             DefaultFileRegion region = (DefaultFileRegion) msg;
252             FileChannel fileChannel = fileChannel(region);
253             // An unopened region uses RandomAccessFile when opened. Keep opening it deferred until the write.
254             if (fileChannel == null || UnixChannelUtil.isFileChannelImpl(fileChannel)) {
255                 return new IoUringFileRegion(region);
256             }
257         }
258 
259         if (msg instanceof FileRegion) {
260             // Generic FileRegion -- pass through to the write path for chunked conversion.
261             return msg;
262         }
263 
264         return super.filterOutboundMessage(msg);
265     }
266 
267     /**
268      * Collects and retains the messages backing a submitted iov prefix. Keep the non-empty NIO segment
269      * counting aligned with {@link IovArray#add(ByteBuf, int, int)}. The readable ranges must still match
270      * those used at submission; the shared iov memory itself may already have been reused.
271      */
272     static final class IovBufferCollector implements ChannelOutboundBuffer.MessageProcessor {
273         private List<ReferenceCounted> buffers;
274         private int remaining;
275 
276         List<ReferenceCounted> collect(ChannelOutboundBuffer buffer, int count) {
277             if (count == 0) {
278                 return Collections.emptyList();
279             }
280             ByteBuf first = (ByteBuf) buffer.current();
281             // A single message or iov only needs one retained owner, even for a partial composite write.
282             if (buffer.size() == 1 || count == 1 && first.isReadable()) {
283                 return Collections.<ReferenceCounted>singletonList(first.retain());
284             }
285             buffers = new ArrayList<>(Math.min(count, buffer.size()));
286             remaining = count;
287             try {
288                 buffer.forEachFlushedMessage(this);
289                 return buffers;
290             } catch (Exception e) {
291                 throw new IllegalStateException(e);
292             }
293         }
294 
295         @Override
296         public boolean processMessage(Object msg) {
297             ByteBuf buf = (ByteBuf) msg;
298             if (buf.isReadable()) {
299                 buffers.add(buf.retain());
300                 remaining = remainingIovs(buf, remaining);
301             }
302             return remaining != 0;
303         }
304 
305         static int remainingIovs(ByteBuf buf, int remaining) {
306             if (buf.nioBufferCount() == 1) {
307                 return remaining - 1;
308             }
309             for (ByteBuffer nioBuffer : buf.nioBuffers(buf.readerIndex(), buf.readableBytes())) {
310                 if (nioBuffer.remaining() != 0 && --remaining == 0) {
311                     break;
312                 }
313             }
314             return remaining;
315         }
316     }
317 
318     protected class IoUringStreamUnsafe extends AbstractUringUnsafe {
319 
320         private ByteBuf readBuffer;
321 
322         // Chunk buffer for generic FileRegion writes. Non-null while a send is in flight.
323         private ByteBuf fileRegionChunkBuf;
324 
325         @Override
326         protected int scheduleWriteMultiple(ChannelOutboundBuffer in) {
327             assert writeId == 0;
328 
329             int fd = fd().intValue();
330             IoRegistration registration = registration();
331             IoUringIoHandler handler = registration.attachment();
332             IovArray iovArray = handler.iovArray();
333             int offset = iovArray.count();
334 
335             try {
336                 in.forEachFlushedMessage(iovArray);
337             } catch (Exception e) {
338                 // This should never happen, anyway fallback to single write.
339                 return scheduleWriteSingle(in.current());
340             }
341             long iovArrayAddress = iovArray.memoryAddress(offset);
342             int iovArrayLength = iovArray.count() - offset;
343             // Should not use sendmsg_zc, just use normal writev.
344             IoUringIoOps ops = IoUringIoOps.newWritev(fd, (byte) 0, 0, iovArrayAddress, iovArrayLength, nextOpsId());
345             byte opCode = ops.opcode();
346             writeId = submitWrite(ops);
347             writeOpCode = opCode;
348             if (writeId == 0) {
349                 return 0;
350             }
351             return 1;
352         }
353 
354         @Override
355         protected int scheduleWriteSingle(Object msg) {
356             assert writeId == 0;
357 
358             int fd = fd().intValue();
359             IoRegistration registration = registration();
360             final IoUringIoOps ops;
361             if (msg instanceof IoUringFileRegion) {
362                 IoUringFileRegion fileRegion = (IoUringFileRegion) msg;
363                 try {
364                     fileRegion.open();
365                 } catch (IOException e) {
366                     this.handleWriteError(e);
367                     return 0;
368                 }
369                 ops = fileRegion.splice(fd);
370             } else if (msg instanceof FileRegion) {
371                 return scheduleWriteFileRegion(fd, registration, (FileRegion) msg);
372             } else {
373                 ByteBuf buf = (ByteBuf) msg;
374                 long address = IoUring.memoryAddress(buf) + buf.readerIndex();
375                 int length = buf.readableBytes();
376                 ops = IoUringIoOps.newSend(fd, (byte) 0, 0, address, length, nextOpsId());
377             }
378             byte opCode = ops.opcode();
379             writeId = submitWrite(ops);
380             writeOpCode = opCode;
381             if (writeId == 0) {
382                 return 0;
383             }
384             return 1;
385         }
386 
387         // Read a chunk from a generic FileRegion into a direct ByteBuf and submit it as an
388         // io_uring async send. If fileRegionChunkBuf is non-null, re-submits the remaining
389         // bytes from a previous partial/failed send.
390         private int scheduleWriteFileRegion(int fd, IoRegistration registration, FileRegion region) {
391             ByteBuf buf = fileRegionChunkBuf;
392             if (buf == null) {
393                 long remaining = region.count() - region.transferred();
394                 if (remaining > 0) {
395                     int chunkSize = (int) Math.min(remaining, FILE_REGION_MAX_CHUNK_SIZE);
396                     buf = alloc().directBuffer(chunkSize);
397                     try {
398                         ByteBufWritableByteChannel ch = new ByteBufWritableByteChannel(buf);
399                         // Mirror epoll's writeFileRegion(): stop calling transferTo() once
400                         // the region reports it has been fully transferred. The FileRegion
401                         // contract permits implementations to assume no further invocations
402                         // past transferred() == count().
403                         while (buf.writableBytes() > 0 && region.transferred() < region.count()) {
404                             long t = region.transferTo(ch, region.transferred());
405                             if (t <= 0) {
406                                 break;
407                             }
408                         }
409                         if (buf.readableBytes() == 0) {
410                             buf.release();
411                             handleWriteError(new ChannelException(
412                                     "FileRegion.transferTo(...) produced 0 bytes (count="
413                                             + region.count() + ", transferred=" + region.transferred() + ')'));
414                             return 0;
415                         }
416                     } catch (Exception e) {
417                         buf.release();
418                         handleWriteError(e);
419                         return 0;
420                     }
421                 } else {
422                     // Empty or fully-transferred region. Submit a 0-byte send so the completion
423                     // path removes it from the outbound buffer via the normal async flow.
424                     buf = alloc().directBuffer(0);
425                 }
426                 fileRegionChunkBuf = buf;
427             }
428             long address = IoUring.memoryAddress(buf) + buf.readerIndex();
429             int length = buf.readableBytes();
430             IoUringIoOps ops = IoUringIoOps.newSend(fd, (byte) 0, 0, address, length, nextOpsId());
431             try {
432                 byte opCode = ops.opcode();
433                 writeId = submitWrite(ops);
434                 writeOpCode = opCode;
435                 if (writeId == 0) {
436                     return 0;
437                 }
438                 return 1;
439             } finally {
440                 if (writeId == 0) {
441                     releaseFileRegionChunkBuf();
442                 }
443             }
444         }
445 
446         @Override
447         List<ReferenceCounted> retainWriteBuffers(ChannelOutboundBuffer buffer) {
448             if (currentWrite.opcode() == Native.IORING_OP_WRITEV) {
449                 return new IovBufferCollector().collect(buffer, currentWrite.len());
450             }
451             Object msg = buffer.current();
452             // A generic FileRegion owns an independent chunk buffer until its SEND completes.
453             if (msg instanceof ByteBuf || msg instanceof IoUringFileRegion) {
454                 return Collections.singletonList(((ReferenceCounted) msg).retain());
455             }
456             return Collections.emptyList();
457         }
458 
459         private int calculateRecvFlags(boolean first) {
460             // Depending on if this is the first read or not we will use Native.MSG_DONTWAIT.
461             // The idea is that if the socket is blocking we can do the first read in a blocking fashion
462             // and so not need to also register POLLIN. As we can not 100 % sure if reads after the first will
463             // be possible directly we schedule these with Native.MSG_DONTWAIT. This allows us to still be
464             // able to signal the fireChannelReadComplete() in a timely manner and be consistent with other
465             // transports.
466             if (first) {
467                 return 0;
468             }
469             return Native.MSG_DONTWAIT;
470         }
471 
472         private short calculateRecvIoPrio(boolean first, boolean socketIsEmpty) {
473             // Depending on if socketIsEmpty is true we will arm the poll upfront and skip the initial transfer
474             // attempt.
475             // See https://github.com/axboe/liburing/wiki/io_uring-and-networking-in-2023#socket-state
476             if (first) {
477                 // IORING_RECVSEND_POLL_FIRST and IORING_CQE_F_SOCK_NONEMPTY were added in the same release (5.19).
478                 // We need to check if it's supported as otherwise providing these would result in an -EINVAL.
479                 return socketIsEmpty && IoUring.isCqeFSockNonEmptySupported() ?
480                         Native.IORING_RECVSEND_POLL_FIRST : 0;
481             }
482             return 0;
483         }
484 
485         @Override
486         protected int scheduleRead0(boolean first, boolean socketIsEmpty) {
487             assert readBuffer == null;
488             assert readId == 0 : readId;
489             final IoUringRecvByteAllocatorHandle allocHandle = recvBufAllocHandle();
490 
491             if (bufferRing != null && bufferRing.isUsable()) {
492                 return scheduleReadProviderBuffer(bufferRing, first, socketIsEmpty);
493             }
494 
495             // We either have no buffer ring configured or we force a recv without using a buffer ring.
496             ByteBuf byteBuf = allocHandle.allocate(alloc());
497             try {
498                 int fd = fd().intValue();
499                 IoRegistration registration = registration();
500                 short ioPrio = calculateRecvIoPrio(first, socketIsEmpty);
501                 int recvFlags = calculateRecvFlags(first);
502                 short opsId = nextOpsId();
503 
504                 IoUringIoOps ops = IoUringIoOps.newRecv(fd, (byte) 0, ioPrio, recvFlags,
505                         IoUring.memoryAddress(byteBuf) + byteBuf.writerIndex(), byteBuf.writableBytes(), opsId);
506                 readId = registration.submit(ops);
507                 readOpCode = Native.IORING_OP_RECV;
508                 if (readId == 0) {
509                     return 0;
510                 }
511                 readBuffer = byteBuf;
512                 byteBuf = null;
513                 return 1;
514             } finally {
515                 if (byteBuf != null) {
516                     byteBuf.release();
517                 }
518             }
519         }
520 
521         private int scheduleReadProviderBuffer(IoUringBufferRing bufferRing, boolean first, boolean socketIsEmpty) {
522             short bgId = bufferRing.bufferGroupId();
523             try {
524                 boolean multishot = IoUring.isRecvMultishotEnabled();
525                 byte flags = (byte) Native.IOSQE_BUFFER_SELECT;
526                 short ioPrio;
527                 final int recvFlags;
528                 if (multishot) {
529                     ioPrio = Native.IORING_RECV_MULTISHOT;
530                     recvFlags = 0;
531                 } else {
532                     // We should only use the calculate*() methods if this is not a multishot recv, as otherwise
533                     // the would be applied until the multishot will be re-armed.
534                     ioPrio = calculateRecvIoPrio(first, socketIsEmpty);
535                     recvFlags = calculateRecvFlags(first);
536                 }
537                 if (IoUring.isRecvsendBundleEnabled()) {
538                     // See https://github.com/axboe/liburing/wiki/
539                     // What's-new-with-io_uring-in-6.10#add-support-for-sendrecv-bundles
540                     ioPrio |= Native.IORING_RECVSEND_BUNDLE;
541                 }
542                 IoRegistration registration = registration();
543                 int fd = fd().intValue();
544                 short opsId = nextOpsId();
545                 IoUringIoOps ops = IoUringIoOps.newRecv(
546                         fd, flags, ioPrio, recvFlags, 0,
547                         0, opsId, bgId
548                 );
549                 readId = registration.submit(ops);
550                 readOpCode = Native.IORING_OP_RECV;
551                 if (readId == 0) {
552                     return 0;
553                 }
554                 if (multishot) {
555                     // Return -1 to signal we used multishot and so expect multiple recvComplete(...) calls.
556                     return -1;
557                 }
558                 return 1;
559             } catch (IllegalArgumentException illegalArgumentException) {
560                 this.handleReadException(pipeline(), null, illegalArgumentException, false, recvBufAllocHandle());
561                 return 0;
562             }
563         }
564 
565         @Override
566         protected void readComplete0(byte op, int res, int flags, short data, int outstanding) {
567             ByteBuf byteBuf = readBuffer;
568             readBuffer = null;
569             if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
570                 readId = 0;
571                 // In case of cancellation we should reset the last used buffer ring to null as we will select a new one
572                 // when calling scheduleRead(..)
573                 if (byteBuf != null) {
574                     //recv without buffer ring
575                     byteBuf.release();
576                 }
577                 return;
578             }
579             boolean rearm = (flags & Native.IORING_CQE_F_MORE) == 0;
580             boolean useBufferRing = (flags & Native.IORING_CQE_F_BUFFER) != 0;
581             short bid = (short) (flags >> Native.IORING_CQE_BUFFER_SHIFT);
582             boolean more = (flags & Native.IORING_CQE_F_BUF_MORE) != 0;
583 
584             boolean completeRead = shouldCompleteReadLoop(flags, isReadMultishot());
585             if (rearm) {
586                 // Only reset if we don't use multi-shot or we need to re-arm because the multi-shot was cancelled.
587                 readId = 0;
588             }
589 
590             boolean allDataRead = false;
591 
592             final IoUringRecvByteAllocatorHandle allocHandle = recvBufAllocHandle();
593             final ChannelPipeline pipeline = pipeline();
594 
595             try {
596                 if (res < 0) {
597                     if (res == Native.ERRNO_NOBUFS_NEGATIVE) {
598                         // try to expand the buffer ring by adding more buffers to it if there is any space left.
599                         if (!bufferRing.expand()) {
600                             // We couldn't expand the ring anymore so notify the user that we did run out of buffers
601                             // without the ability to expand it.
602                             // If this happens to often the user should most likely increase the buffer ring size.
603                             pipeline.fireUserEventTriggered(bufferRing.getExhaustedEvent());
604                         }
605 
606                         // Let's trigger a read again without consulting the RecvByteBufAllocator.Handle as
607                         // we can't count this as a "real" read operation.
608                         // Because of how our BufferRing works we should have it filled again.
609                         scheduleRead(allocHandle.isFirstRead());
610                         return;
611                     }
612 
613                     // If res is negative we should pass it to ioResult(...) which will either throw
614                     // or convert it to 0 if we could not read because the socket was not readable.
615                     allocHandle.lastBytesRead(ioResult("io_uring read", res));
616                 } else if (res > 0) {
617                     if (useBufferRing) {
618                         // If RECVSEND_BUNDLE is used we need to do a bit more work here.
619                         // In this case we might need to obtain multiple buffers out of the buffer ring as
620                         // multiple of them might have been filled for one recv operation.
621                         // See https://github.com/axboe/liburing/wiki/
622                         // What's-new-with-io_uring-in-6.10#add-support-for-sendrecv-bundles
623                         int read = res;
624                         for (;;) {
625                             int attemptedBytesRead = bufferRing.attemptedBytesRead(bid);
626                             // Snapshot the number of allocated buffers before calling useBuffer(...) as that call
627                             // might grow the ring (and so change allocatedBuffers) once the last posted buffer is
628                             // consumed. The bundle completion we are walking here was produced by the kernel using
629                             // the ring size as it was *before* any such growth, so the wrap-around for the next bid
630                             // in this bundle must be computed with that same (old) size to stay in sync with the
631                             // kernel.
632                             int allocatedBuffers = bufferRing.allocatedBuffers();
633                             byteBuf = bufferRing.useBuffer(bid, read, more);
634                             read -= byteBuf.readableBytes();
635                             allocHandle.attemptedBytesRead(attemptedBytesRead);
636                             allocHandle.lastBytesRead(byteBuf.readableBytes());
637 
638                             assert read >= 0;
639                             if (read == 0) {
640                                 // Just break here, we will handle the byteBuf below and also fill the bufferRing
641                                 // if needed later.
642                                 break;
643                             }
644                             allocHandle.incMessagesRead(1);
645                             pipeline.fireChannelRead(byteBuf);
646                             byteBuf = null;
647                             bid = bufferRing.nextBid(bid, allocatedBuffers);
648                             if (!allocHandle.continueReading()) {
649                                 // We should call fireChannelReadComplete() to mimic a normal read loop.
650                                 allocHandle.readComplete();
651                                 pipeline.fireChannelReadComplete();
652                                 allocHandle.reset(config());
653                             }
654                         }
655                     } else {
656                         int attemptedBytesRead = byteBuf.writableBytes();
657                         byteBuf.writerIndex(byteBuf.writerIndex() + res);
658                         allocHandle.attemptedBytesRead(attemptedBytesRead);
659                         allocHandle.lastBytesRead(res);
660                     }
661                 } else {
662                     // EOF which we signal with -1.
663                     allocHandle.lastBytesRead(-1);
664                 }
665                 if (allocHandle.lastBytesRead() <= 0) {
666                     // byteBuf might be null if we used a buffer ring.
667                     if (byteBuf != null) {
668                         // nothing was read, release the buffer.
669                         byteBuf.release();
670                         byteBuf = null;
671                     }
672                     allDataRead = allocHandle.lastBytesRead() < 0;
673                     if (allDataRead) {
674                         // There is nothing left to read as we received an EOF.
675                         shutdownInput(true);
676                     }
677                     allocHandle.readComplete();
678                     pipeline.fireChannelReadComplete();
679                     return;
680                 }
681 
682                 allocHandle.incMessagesRead(1);
683                 pipeline.fireChannelRead(byteBuf);
684                 byteBuf = null;
685                 scheduleNextRead(pipeline, allocHandle, rearm, completeRead);
686             } catch (Throwable t) {
687                 handleReadException(pipeline, byteBuf, t, allDataRead, allocHandle);
688             }
689         }
690 
691         private void scheduleNextRead(ChannelPipeline pipeline, IoUringRecvByteAllocatorHandle allocHandle,
692                                       boolean rearm, boolean completeRead) {
693             if (allocHandle.continueReading() && !completeRead) {
694                 if (rearm) {
695                     // We only should schedule another read if we need to rearm.
696                     // See https://github.com/axboe/liburing/wiki/io_uring-and-networking-in-2023#multi-shot
697                     scheduleRead(false);
698                 }
699             } else {
700                 // We did not fill the whole ByteBuf so we should break the "read loop" and try again later.
701                 allocHandle.readComplete();
702                 pipeline.fireChannelReadComplete();
703             }
704         }
705 
706         protected final void handleReadException(ChannelPipeline pipeline, ByteBuf byteBuf,
707                                          Throwable cause, boolean allDataRead,
708                                          IoUringRecvByteAllocatorHandle allocHandle) {
709             if (byteBuf != null) {
710                 if (byteBuf.isReadable()) {
711                     pipeline.fireChannelRead(byteBuf);
712                 } else {
713                     byteBuf.release();
714                 }
715             }
716             allocHandle.readComplete();
717             pipeline.fireChannelReadComplete();
718             pipeline.fireExceptionCaught(cause);
719             if (allDataRead || cause instanceof IOException) {
720                 shutdownInput(true);
721             }
722         }
723 
724         private boolean handleWriteCompleteFileRegion(ChannelOutboundBuffer channelOutboundBuffer,
725                                                       IoUringFileRegion fileRegion, int res, short data) {
726             try {
727                 if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
728                     return true;
729                 }
730                 int result = res >= 0 ? res : ioResult("io_uring splice", res);
731                 if (result == 0 && fileRegion.count() > 0) {
732                     validateFileRegion(fileRegion.fileRegion, fileRegion.transfered());
733                     return false;
734                 }
735                 int progress = fileRegion.handleResult(result, data);
736                 if (progress == -1) {
737                     // Done with writing
738                     channelOutboundBuffer.remove();
739                 } else if (progress > 0) {
740                     channelOutboundBuffer.progress(progress);
741                 }
742             } catch (Throwable cause) {
743                 handleWriteError(cause);
744             }
745             return true;
746         }
747 
748         @Override
749         boolean writeComplete0(byte op, int res, int flags, long data, int outstanding) {
750             if ((flags & Native.IORING_CQE_F_NOTIF) == 0) {
751                 // We only want to reset these if IORING_CQE_F_NOTIF is not set.
752                 // If it's set we know this is only an extra notification for a write but we already handled
753                 // the write completions before.
754                 // See https://man7.org/linux/man-pages/man2/io_uring_enter.2.html section: IORING_OP_SEND_ZC
755                 writeId = 0;
756                 writeOpCode = 0;
757             }
758             ChannelOutboundBuffer channelOutboundBuffer = unsafe().outboundBuffer();
759             if (channelOutboundBuffer == null) {
760                 // The completion may arrive after close() or shutdownOutput() already dropped the buffer.
761                 releaseFileRegionChunkBuf();
762                 return true;
763             }
764             Object current = channelOutboundBuffer.current();
765             if (current instanceof IoUringFileRegion) {
766                 IoUringFileRegion fileRegion = (IoUringFileRegion) current;
767                 // A splice picks its own data to tell its two stages apart, so narrowing here can not drop bits.
768                 return handleWriteCompleteFileRegion(channelOutboundBuffer, fileRegion, res, (short) data);
769             }
770 
771             if (current instanceof FileRegion) {
772                 return handleWriteCompleteGenericFileRegion(
773                         channelOutboundBuffer, (FileRegion) current, res);
774             }
775 
776             if (res >= 0) {
777                 channelOutboundBuffer.removeBytes(res);
778             } else if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
779                 return true;
780             } else {
781                 try {
782                     if (ioResult("io_uring write", res) == 0) {
783                         return false;
784                     }
785                 } catch (Throwable cause) {
786                     handleWriteError(cause);
787                 }
788             }
789             return true;
790         }
791 
792         // Returns true when the completion can be treated as "written all" for this SQE
793         // (the framework may still schedule further writes from the outbound buffer); returns
794         // false to signal the framework that POLLOUT should be armed so the chunk buffer is
795         // resubmitted once the socket becomes writable again.
796         private boolean handleWriteCompleteGenericFileRegion(
797                 ChannelOutboundBuffer channelOutboundBuffer, FileRegion region, int res) {
798             try {
799                 if (res == Native.ERRNO_ECANCELED_NEGATIVE) {
800                     releaseFileRegionChunkBuf();
801                     return true;
802                 }
803                 if (res >= 0) {
804                     ByteBuf buf = fileRegionChunkBuf;
805                     assert buf != null;
806                     buf.skipBytes(res);
807                     channelOutboundBuffer.progress(res);
808                     if (!buf.isReadable()) {
809                         // Chunk fully sent.
810                         releaseFileRegionChunkBuf();
811                         if (region.transferred() >= region.count()) {
812                             channelOutboundBuffer.remove();
813                         }
814                     } else {
815                         // Partial send -- schedule POLLOUT to re-send the remainder.
816                         return false;
817                     }
818                 } else {
819                     // Keep the chunk buffer -- on retryable errors (EAGAIN) ioResult returns 0
820                     // and scheduleWriteFileRegion() will re-submit the same fileRegionChunkBuf
821                     // once POLLOUT fires. On a non-retryable error ioResult throws, and the
822                     // outer catch releases the buffer.
823                     if (ioResult("io_uring write", res) == 0) {
824                         return false;
825                     }
826                 }
827             } catch (Throwable cause) {
828                 releaseFileRegionChunkBuf();
829                 handleWriteError(cause);
830             }
831             return true;
832         }
833 
834         private void releaseFileRegionChunkBuf() {
835             if (fileRegionChunkBuf != null) {
836                 fileRegionChunkBuf.release();
837                 fileRegionChunkBuf = null;
838             }
839         }
840 
841         @Override
842         public void unregistered() {
843             super.unregistered();
844             assert readBuffer == null;
845             releaseFileRegionChunkBuf();
846         }
847     }
848 
849     @Override
850     protected final void cancelOutstandingReads(IoRegistration registration, int numOutstandingReads) {
851         if (readId != 0) {
852             // Let's try to cancel outstanding reads as these might be submitted and waiting for data (via fastpoll).
853             assert numOutstandingReads == 1 || numOutstandingReads == -1;
854             IoUringIoOps ops = IoUringIoOps.newAsyncCancel((byte) 0, readId, readOpCode);
855             long id = registration.submit(ops);
856             assert id != 0;
857             readId = 0;
858         }
859     }
860 
861     @Override
862     protected final void cancelOutstandingWrites(IoRegistration registration, int numOutstandingWrites) {
863         if (writeId != 0) {
864             // Let's try to cancel outstanding writes as these might be submitted and waiting to finish writing
865             // (via fastpoll).
866             assert numOutstandingWrites == 1;
867             assert writeOpCode != 0;
868             long id = registration.submit(IoUringIoOps.newAsyncCancel((byte) 0, writeId, writeOpCode));
869             assert id != 0;
870             writeId = 0;
871         }
872     }
873 
874     @Override
875     protected boolean socketIsEmpty(int flags) {
876         return IoUring.isCqeFSockNonEmptySupported() && (flags & Native.IORING_CQE_F_SOCK_NONEMPTY) == 0;
877     }
878 
879     protected boolean shouldCompleteReadLoop(int flags, boolean multishot) {
880         return socketIsEmpty(flags);
881     }
882 
883     @Override
884     boolean isPollInFirst() {
885         return bufferRing == null || !bufferRing.isUsable();
886     }
887 
888     /**
889      * A {@link WritableByteChannel} backed by a {@link ByteBuf}.
890      * Writes are capped to {@link ByteBuf#writableBytes()} to prevent overflow
891      * when {@link FileRegion#transferTo} writes more than the chunk size.
892      */
893     private static final class ByteBufWritableByteChannel implements WritableByteChannel {
894         private final ByteBuf buf;
895 
896         ByteBufWritableByteChannel(ByteBuf buf) {
897             this.buf = buf;
898         }
899 
900         @Override
901         public int write(ByteBuffer src) {
902             int toWrite = Math.min(src.remaining(), buf.writableBytes());
903             if (toWrite == 0) {
904                 return 0;
905             }
906             if (toWrite < src.remaining()) {
907                 int oldLimit = src.limit();
908                 src.limit(src.position() + toWrite);
909                 buf.writeBytes(src);
910                 src.limit(oldLimit);
911                 return toWrite;
912             }
913             buf.writeBytes(src);
914             return toWrite;
915         }
916 
917         @Override
918         public boolean isOpen() {
919             return true;
920         }
921 
922         @Override
923         public void close() {
924             // NOOP
925         }
926     }
927 }