1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.channel.uring;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.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
56
57
58
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
64 byte writeOpCode;
65
66 long writeId;
67 byte readOpCode;
68 long readId;
69
70
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
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
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
254 if (fileChannel == null || UnixChannelUtil.isFileChannelImpl(fileChannel)) {
255 return new IoUringFileRegion(region);
256 }
257 }
258
259 if (msg instanceof FileRegion) {
260
261 return msg;
262 }
263
264 return super.filterOutboundMessage(msg);
265 }
266
267
268
269
270
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
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
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
339 return scheduleWriteSingle(in.current());
340 }
341 long iovArrayAddress = iovArray.memoryAddress(offset);
342 int iovArrayLength = iovArray.count() - offset;
343
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
388
389
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
400
401
402
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
423
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
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
461
462
463
464
465
466 if (first) {
467 return 0;
468 }
469 return Native.MSG_DONTWAIT;
470 }
471
472 private short calculateRecvIoPrio(boolean first, boolean socketIsEmpty) {
473
474
475
476 if (first) {
477
478
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
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
533
534 ioPrio = calculateRecvIoPrio(first, socketIsEmpty);
535 recvFlags = calculateRecvFlags(first);
536 }
537 if (IoUring.isRecvsendBundleEnabled()) {
538
539
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
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
572
573 if (byteBuf != null) {
574
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
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
599 if (!bufferRing.expand()) {
600
601
602
603 pipeline.fireUserEventTriggered(bufferRing.getExhaustedEvent());
604 }
605
606
607
608
609 scheduleRead(allocHandle.isFirstRead());
610 return;
611 }
612
613
614
615 allocHandle.lastBytesRead(ioResult("io_uring read", res));
616 } else if (res > 0) {
617 if (useBufferRing) {
618
619
620
621
622
623 int read = res;
624 for (;;) {
625 int attemptedBytesRead = bufferRing.attemptedBytesRead(bid);
626
627
628
629
630
631
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
641
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
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
663 allocHandle.lastBytesRead(-1);
664 }
665 if (allocHandle.lastBytesRead() <= 0) {
666
667 if (byteBuf != null) {
668
669 byteBuf.release();
670 byteBuf = null;
671 }
672 allDataRead = allocHandle.lastBytesRead() < 0;
673 if (allDataRead) {
674
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
696
697 scheduleRead(false);
698 }
699 } else {
700
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
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
752
753
754
755 writeId = 0;
756 writeOpCode = 0;
757 }
758 ChannelOutboundBuffer channelOutboundBuffer = unsafe().outboundBuffer();
759 if (channelOutboundBuffer == null) {
760
761 releaseFileRegionChunkBuf();
762 return true;
763 }
764 Object current = channelOutboundBuffer.current();
765 if (current instanceof IoUringFileRegion) {
766 IoUringFileRegion fileRegion = (IoUringFileRegion) current;
767
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
793
794
795
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
810 releaseFileRegionChunkBuf();
811 if (region.transferred() >= region.count()) {
812 channelOutboundBuffer.remove();
813 }
814 } else {
815
816 return false;
817 }
818 } else {
819
820
821
822
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
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
865
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
890
891
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
925 }
926 }
927 }