View Javadoc
1   /*
2    * Copyright 2016 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.kqueue;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.channel.Channel;
21  import io.netty.channel.ChannelConfig;
22  import io.netty.channel.ChannelFuture;
23  import io.netty.channel.ChannelFutureListener;
24  import io.netty.channel.ChannelMetadata;
25  import io.netty.channel.ChannelOutboundBuffer;
26  import io.netty.channel.ChannelPipeline;
27  import io.netty.channel.ChannelPromise;
28  import io.netty.channel.DefaultFileRegion;
29  import io.netty.channel.EventLoop;
30  import io.netty.channel.FileRegion;
31  import io.netty.channel.internal.ChannelUtils;
32  import io.netty.channel.socket.DuplexChannel;
33  import io.netty.channel.unix.IovArray;
34  import io.netty.channel.unix.SocketWritableByteChannel;
35  import io.netty.channel.unix.UnixChannelUtil;
36  import io.netty.util.internal.StringUtil;
37  import io.netty.util.internal.UnstableApi;
38  import io.netty.util.internal.logging.InternalLogger;
39  import io.netty.util.internal.logging.InternalLoggerFactory;
40  
41  import java.io.IOException;
42  import java.net.SocketAddress;
43  import java.nio.ByteBuffer;
44  import java.nio.channels.FileChannel;
45  import java.nio.channels.WritableByteChannel;
46  import java.util.concurrent.Executor;
47  
48  import static io.netty.channel.internal.ChannelUtils.MAX_BYTES_PER_GATHERING_WRITE_ATTEMPTED_LOW_THRESHOLD;
49  import static io.netty.channel.internal.ChannelUtils.WRITE_STATUS_SNDBUF_FULL;
50  
51  public abstract class AbstractKQueueStreamChannel extends AbstractKQueueChannel implements DuplexChannel {
52      private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractKQueueStreamChannel.class);
53      private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
54      private static final String EXPECTED_TYPES =
55              " (expected: " + StringUtil.simpleClassName(ByteBuf.class) + ", " +
56                      StringUtil.simpleClassName(DefaultFileRegion.class) + ')';
57      private WritableByteChannel byteChannel;
58      private final Runnable flushTask = new Runnable() {
59          @Override
60          public void run() {
61              // Calling flush0 directly to ensure we not try to flush messages that were added via write(...) in the
62              // meantime.
63              ((AbstractKQueueUnsafe) unsafe()).flush0();
64          }
65      };
66  
67      AbstractKQueueStreamChannel(Channel parent, BsdSocket fd, boolean active) {
68          super(parent, fd, active);
69      }
70  
71      AbstractKQueueStreamChannel(Channel parent, BsdSocket fd, SocketAddress remote) {
72          super(parent, fd, remote);
73      }
74  
75      AbstractKQueueStreamChannel(BsdSocket fd) {
76          this(null, fd, isSoErrorZero(fd));
77      }
78  
79      @Override
80      protected AbstractKQueueUnsafe newUnsafe() {
81          return new KQueueStreamUnsafe();
82      }
83  
84      @Override
85      public ChannelMetadata metadata() {
86          return METADATA;
87      }
88  
89      /**
90       * Write bytes form the given {@link ByteBuf} to the underlying {@link java.nio.channels.Channel}.
91       * @param in the collection which contains objects to write.
92       * @param buf the {@link ByteBuf} from which the bytes should be written
93       * @return The value that should be decremented from the write quantum which starts at
94       * {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
95       * <ul>
96       *     <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
97       *     is encountered</li>
98       *     <li>1 - if a single call to write data was made to the OS</li>
99       *     <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but no
100      *     data was accepted</li>
101      * </ul>
102      */
103     private int writeBytes(ChannelOutboundBuffer in, ByteBuf buf) throws Exception {
104         int readableBytes = buf.readableBytes();
105         if (readableBytes == 0) {
106             in.remove();
107             return 0;
108         }
109 
110         if (buf.hasMemoryAddress() || buf.nioBufferCount() == 1) {
111             return doWriteBytes(in, buf);
112         } else {
113             ByteBuffer[] nioBuffers = buf.nioBuffers();
114             return writeBytesMultiple(in, nioBuffers, nioBuffers.length, readableBytes,
115                     config().getMaxBytesPerGatheringWrite());
116         }
117     }
118 
119     private void adjustMaxBytesPerGatheringWrite(long attempted, long written, long oldMaxBytesPerGatheringWrite) {
120         // By default we track the SO_SNDBUF when ever it is explicitly set. However some OSes may dynamically change
121         // SO_SNDBUF (and other characteristics that determine how much data can be written at once) so we should try
122         // make a best effort to adjust as OS behavior changes.
123         if (attempted == written) {
124             if (attempted << 1 > oldMaxBytesPerGatheringWrite) {
125                 config().setMaxBytesPerGatheringWrite(attempted << 1);
126             }
127         } else if (attempted > MAX_BYTES_PER_GATHERING_WRITE_ATTEMPTED_LOW_THRESHOLD && written < attempted >>> 1) {
128             config().setMaxBytesPerGatheringWrite(attempted >>> 1);
129         }
130     }
131 
132     /**
133      * Write multiple bytes via {@link IovArray}.
134      * @param in the collection which contains objects to write.
135      * @param array The array which contains the content to write.
136      * @return The value that should be decremented from the write quantum which starts at
137      * {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
138      * <ul>
139      *     <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
140      *     is encountered</li>
141      *     <li>1 - if a single call to write data was made to the OS</li>
142      *     <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but
143      *     no data was accepted</li>
144      * </ul>
145      * @throws IOException If an I/O exception occurs during write.
146      */
147     private int writeBytesMultiple(ChannelOutboundBuffer in, IovArray array) throws IOException {
148         final long expectedWrittenBytes = array.size();
149         assert expectedWrittenBytes != 0;
150         final int cnt = array.count();
151         assert cnt != 0;
152 
153         final long localWrittenBytes = socket.writevAddresses(array.memoryAddress(0), cnt);
154         if (localWrittenBytes > 0) {
155             adjustMaxBytesPerGatheringWrite(expectedWrittenBytes, localWrittenBytes, array.maxBytes());
156             in.removeBytes(localWrittenBytes);
157             return 1;
158         }
159         return WRITE_STATUS_SNDBUF_FULL;
160     }
161 
162     /**
163      * Write multiple bytes via {@link ByteBuffer} array.
164      * @param in the collection which contains objects to write.
165      * @param nioBuffers The buffers to write.
166      * @param nioBufferCnt The number of buffers to write.
167      * @param expectedWrittenBytes The number of bytes we expect to write.
168      * @param maxBytesPerGatheringWrite The maximum number of bytes we should attempt to write.
169      * @return The value that should be decremented from the write quantum which starts at
170      * {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
171      * <ul>
172      *     <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
173      *     is encountered</li>
174      *     <li>1 - if a single call to write data was made to the OS</li>
175      *     <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but
176      *     no data was accepted</li>
177      * </ul>
178      * @throws IOException If an I/O exception occurs during write.
179      */
180     private int writeBytesMultiple(
181             ChannelOutboundBuffer in, ByteBuffer[] nioBuffers, int nioBufferCnt, long expectedWrittenBytes,
182             long maxBytesPerGatheringWrite) throws IOException {
183         assert expectedWrittenBytes != 0;
184         if (expectedWrittenBytes > maxBytesPerGatheringWrite) {
185             expectedWrittenBytes = maxBytesPerGatheringWrite;
186         }
187 
188         final long localWrittenBytes = socket.writev(nioBuffers, 0, nioBufferCnt, expectedWrittenBytes);
189         if (localWrittenBytes > 0) {
190             adjustMaxBytesPerGatheringWrite(expectedWrittenBytes, localWrittenBytes, maxBytesPerGatheringWrite);
191             in.removeBytes(localWrittenBytes);
192             return 1;
193         }
194         return WRITE_STATUS_SNDBUF_FULL;
195     }
196 
197     /**
198      * Write a {@link DefaultFileRegion}
199      * @param in the collection which contains objects to write.
200      * @param region the {@link DefaultFileRegion} from which the bytes should be written
201      * @return The value that should be decremented from the write quantum which starts at
202      * {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
203      * <ul>
204      *     <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
205      *     is encountered</li>
206      *     <li>1 - if a single call to write data was made to the OS</li>
207      *     <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but
208      *     no data was accepted</li>
209      * </ul>
210      */
211     private int writeDefaultFileRegion(ChannelOutboundBuffer in, DefaultFileRegion region) throws Exception {
212         final long regionCount = region.count();
213         final long offset = region.transferred();
214 
215         if (offset >= regionCount) {
216             in.remove();
217             return 0;
218         }
219 
220         final long flushedAmount = socket.sendFile(region, region.position(), offset, regionCount - offset);
221         if (flushedAmount > 0) {
222             in.progress(flushedAmount);
223             if (region.transferred() >= regionCount) {
224                 in.remove();
225             }
226             return 1;
227         } else if (flushedAmount == 0) {
228             validateFileRegion(region, offset);
229         }
230         return WRITE_STATUS_SNDBUF_FULL;
231     }
232 
233     /**
234      * Write a {@link FileRegion}
235      * @param in the collection which contains objects to write.
236      * @param region the {@link FileRegion} from which the bytes should be written
237      * @return The value that should be decremented from the write quantum which starts at
238      * {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
239      * <ul>
240      *     <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
241      *     is encountered</li>
242      *     <li>1 - if a single call to write data was made to the OS</li>
243      *     <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but no
244      *     data was accepted</li>
245      * </ul>
246      */
247     private int writeFileRegion(ChannelOutboundBuffer in, FileRegion region) throws Exception {
248         if (region.transferred() >= region.count()) {
249             in.remove();
250             return 0;
251         }
252 
253         if (byteChannel == null) {
254             byteChannel = new KQueueSocketWritableByteChannel();
255         }
256         final long flushedAmount = region.transferTo(byteChannel, region.transferred());
257         if (flushedAmount > 0) {
258             in.progress(flushedAmount);
259             if (region.transferred() >= region.count()) {
260                 in.remove();
261             }
262             return 1;
263         }
264         return WRITE_STATUS_SNDBUF_FULL;
265     }
266 
267     @Override
268     protected void doWrite(ChannelOutboundBuffer in) throws Exception {
269         // Don't write the initial data that was sent by TCP_FASTOPEN_CONNECT a second time.
270         removeFastOpenData();
271         int writeSpinCount = config().getWriteSpinCount();
272         do {
273             final int msgCount = in.size();
274             // Do gathering write if the outbound buffer entries start with more than one ByteBuf.
275             if (msgCount > 1 && in.current() instanceof ByteBuf) {
276                 writeSpinCount -= doWriteMultiple(in);
277             } else if (msgCount == 0) {
278                 // Wrote all messages.
279                 writeFilter(false);
280                 // Return here so we don't set the WRITE flag.
281                 return;
282             } else { // msgCount == 1
283                 writeSpinCount -= doWriteSingle(in);
284             }
285 
286             // We do not break the loop here even if the outbound buffer was flushed completely,
287             // because a user might have triggered another write and flush when we notify his or her
288             // listeners.
289         } while (writeSpinCount > 0);
290 
291         if (writeSpinCount == 0) {
292             // It is possible that we have set the write filter, woken up by KQUEUE because the socket is writable, and
293             // then use our write quantum. In this case we no longer want to set the write filter because the socket is
294             // still writable (as far as we know). We will find out next time we attempt to write if the socket is
295             // writable and set the write filter if necessary.
296             writeFilter(false);
297 
298             // We used our writeSpin quantum, and should try to write again later.
299             eventLoop().execute(flushTask);
300         } else {
301             // Underlying descriptor can not accept all data currently, so set the WRITE flag to be woken up
302             // when it can accept more data.
303             writeFilter(true);
304         }
305     }
306 
307     /**
308      * Attempt to write a single object.
309      * @param in the collection which contains objects to write.
310      * @return The value that should be decremented from the write quantum which starts at
311      * {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
312      * <ul>
313      *     <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
314      *     is encountered</li>
315      *     <li>1 - if a single call to write data was made to the OS</li>
316      *     <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but no
317      *     data was accepted</li>
318      * </ul>
319      * @throws Exception If an I/O error occurs.
320      */
321     protected int doWriteSingle(ChannelOutboundBuffer in) throws Exception {
322         // The outbound buffer contains only one message or it contains a file region.
323         Object msg = in.current();
324         if (msg instanceof ByteBuf) {
325             return writeBytes(in, (ByteBuf) msg);
326         } else if (msg instanceof DefaultFileRegion) {
327             DefaultFileRegion region = (DefaultFileRegion) msg;
328             FileChannel channel = fileChannel(region);
329             // An unopened region uses RandomAccessFile when opened by sendFile.
330             if (channel == null || UnixChannelUtil.isFileChannelImpl(channel)) {
331                 return writeDefaultFileRegion(in, region);
332             }
333             return writeFileRegion(in, region);
334         } else if (msg instanceof FileRegion) {
335             return writeFileRegion(in, (FileRegion) msg);
336         } else {
337             // Should never reach here.
338             throw new Error();
339         }
340     }
341 
342     /**
343      * Attempt to write multiple {@link ByteBuf} objects.
344      * @param in the collection which contains objects to write.
345      * @return The value that should be decremented from the write quantum which starts at
346      * {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
347      * <ul>
348      *     <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
349      *     is encountered</li>
350      *     <li>1 - if a single call to write data was made to the OS</li>
351      *     <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but no
352      *     data was accepted</li>
353      * </ul>
354      * @throws Exception If an I/O error occurs.
355      */
356     private int doWriteMultiple(ChannelOutboundBuffer in) throws Exception {
357         final long maxBytesPerGatheringWrite = config().getMaxBytesPerGatheringWrite();
358         IovArray array = ((KQueueEventLoop) eventLoop()).cleanArray();
359         array.maxBytes(maxBytesPerGatheringWrite);
360         in.forEachFlushedMessage(array);
361 
362         if (array.count() >= 1) {
363             // TODO: Handle the case where cnt == 1 specially.
364             return writeBytesMultiple(in, array);
365         }
366         // cnt == 0, which means the outbound buffer contained empty buffers only.
367         in.removeBytes(0);
368         return 0;
369     }
370 
371     @Override
372     protected Object filterOutboundMessage(Object msg) {
373         if (msg instanceof ByteBuf) {
374             ByteBuf buf = (ByteBuf) msg;
375             return UnixChannelUtil.isBufferCopyNeededForWrite(buf)? newDirectBuffer(buf) : buf;
376         }
377 
378         if (msg instanceof FileRegion) {
379             return msg;
380         }
381 
382         throw new UnsupportedOperationException(
383                 "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
384     }
385 
386     @UnstableApi
387     @Override
388     protected final void doShutdownOutput() throws Exception {
389         // The initial data that was sent by TCP_FASTOPEN_CONNECT must not be failed when shutting down the output.
390         removeFastOpenData();
391         socket.shutdown(false, true);
392     }
393 
394     @Override
395     public boolean isOutputShutdown() {
396         return socket.isOutputShutdown();
397     }
398 
399     @Override
400     public boolean isInputShutdown() {
401         return socket.isInputShutdown();
402     }
403 
404     @Override
405     public boolean isShutdown() {
406         return socket.isShutdown();
407     }
408 
409     @Override
410     public ChannelFuture shutdownOutput() {
411         return shutdownOutput(newPromise());
412     }
413 
414     @Override
415     public ChannelFuture shutdownOutput(final ChannelPromise promise) {
416         EventLoop loop = eventLoop();
417         if (loop.inEventLoop()) {
418             ((AbstractUnsafe) unsafe()).shutdownOutput(promise);
419         } else {
420             loop.execute(new Runnable() {
421                 @Override
422                 public void run() {
423                     ((AbstractUnsafe) unsafe()).shutdownOutput(promise);
424                 }
425             });
426         }
427         return promise;
428     }
429 
430     @Override
431     public ChannelFuture shutdownInput() {
432         return shutdownInput(newPromise());
433     }
434 
435     @Override
436     public ChannelFuture shutdownInput(final ChannelPromise promise) {
437         EventLoop loop = eventLoop();
438         if (loop.inEventLoop()) {
439             shutdownInput0(promise);
440         } else {
441             loop.execute(new Runnable() {
442                 @Override
443                 public void run() {
444                     shutdownInput0(promise);
445                 }
446             });
447         }
448         return promise;
449     }
450 
451     private void shutdownInput0(ChannelPromise promise) {
452         try {
453             socket.shutdown(true, false);
454         } catch (Throwable cause) {
455             promise.setFailure(cause);
456             return;
457         }
458         promise.setSuccess();
459     }
460 
461     @Override
462     public ChannelFuture shutdown() {
463         return shutdown(newPromise());
464     }
465 
466     @Override
467     public ChannelFuture shutdown(final ChannelPromise promise) {
468         ChannelFuture shutdownOutputFuture = shutdownOutput();
469         if (shutdownOutputFuture.isDone()) {
470             shutdownOutputDone(shutdownOutputFuture, promise);
471         } else {
472             shutdownOutputFuture.addListener(new ChannelFutureListener() {
473                 @Override
474                 public void operationComplete(final ChannelFuture shutdownOutputFuture) throws Exception {
475                     shutdownOutputDone(shutdownOutputFuture, promise);
476                 }
477             });
478         }
479         return promise;
480     }
481 
482     private void shutdownOutputDone(final ChannelFuture shutdownOutputFuture, final ChannelPromise promise) {
483         ChannelFuture shutdownInputFuture = shutdownInput();
484         if (shutdownInputFuture.isDone()) {
485             shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise);
486         } else {
487             shutdownInputFuture.addListener(new ChannelFutureListener() {
488                 @Override
489                 public void operationComplete(ChannelFuture shutdownInputFuture) throws Exception {
490                     shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise);
491                 }
492             });
493         }
494     }
495 
496     private static void shutdownDone(ChannelFuture shutdownOutputFuture,
497                                      ChannelFuture shutdownInputFuture,
498                                      ChannelPromise promise) {
499         Throwable shutdownOutputCause = shutdownOutputFuture.cause();
500         Throwable shutdownInputCause = shutdownInputFuture.cause();
501         if (shutdownOutputCause != null) {
502             if (shutdownInputCause != null) {
503                 logger.debug("Exception suppressed because a previous exception occurred.",
504                         shutdownInputCause);
505             }
506             promise.setFailure(shutdownOutputCause);
507         } else if (shutdownInputCause != null) {
508             promise.setFailure(shutdownInputCause);
509         } else {
510             promise.setSuccess();
511         }
512     }
513 
514     class KQueueStreamUnsafe extends AbstractKQueueUnsafe {
515         // Overridden here just to be able to access this method from AbstractKQueueStreamChannel
516         @Override
517         protected Executor prepareToClose() {
518             // The initial data that was sent by TCP_FASTOPEN_CONNECT must not be failed when closing.
519             removeFastOpenData();
520             return super.prepareToClose();
521         }
522 
523         @Override
524         void readReady(final KQueueRecvByteAllocatorHandle allocHandle) {
525             final ChannelConfig config = config();
526             if (shouldBreakReadReady(config)) {
527                 clearReadFilter0();
528                 return;
529             }
530             final ChannelPipeline pipeline = pipeline();
531             final ByteBufAllocator allocator = config.getAllocator();
532             allocHandle.reset(config);
533 
534             ByteBuf byteBuf = null;
535             boolean close = false;
536             try {
537                 do {
538                     // we use a direct buffer here as the native implementations only be able
539                     // to handle direct buffers.
540                     byteBuf = allocHandle.allocate(allocator);
541                     allocHandle.lastBytesRead(doReadBytes(byteBuf));
542                     if (allocHandle.lastBytesRead() <= 0) {
543                         // nothing was read, release the buffer.
544                         byteBuf.release();
545                         byteBuf = null;
546                         close = allocHandle.lastBytesRead() < 0;
547                         if (close) {
548                             // There is nothing left to read as we received an EOF.
549                             readPending = false;
550                         }
551                         break;
552                     }
553                     allocHandle.incMessagesRead(1);
554                     readPending = false;
555                     pipeline.fireChannelRead(byteBuf);
556                     byteBuf = null;
557 
558                     if (shouldBreakReadReady(config)) {
559                         // We need to do this for two reasons:
560                         //
561                         // - If the input was shutdown in between (which may be the case when the user did it in the
562                         //   fireChannelRead(...) method we should not try to read again to not produce any
563                         //   miss-leading exceptions.
564                         //
565                         // - If the user closes the channel we need to ensure we not try to read from it again as
566                         //   the filedescriptor may be re-used already by the OS if the system is handling a lot of
567                         //   concurrent connections and so needs a lot of filedescriptors. If not do this we risk
568                         //   reading data from a filedescriptor that belongs to another socket then the socket that
569                         //   was "wrapped" by this Channel implementation.
570                         break;
571                     }
572                 } while (allocHandle.continueReading());
573 
574                 allocHandle.readComplete();
575                 pipeline.fireChannelReadComplete();
576 
577                 if (close || allocHandle.isReadEOF()) {
578                     shutdownInput(false);
579                 }
580             } catch (Throwable t) {
581                 handleReadException(pipeline, byteBuf, t, close, allocHandle);
582             } finally {
583                 if (shouldStopReading(config)) {
584                     clearReadFilter0();
585                 }
586             }
587         }
588 
589         private void handleReadException(ChannelPipeline pipeline, ByteBuf byteBuf, Throwable cause, boolean close,
590                                          KQueueRecvByteAllocatorHandle allocHandle) {
591             if (byteBuf != null) {
592                 if (byteBuf.isReadable()) {
593                     readPending = false;
594                     pipeline.fireChannelRead(byteBuf);
595                 } else {
596                     byteBuf.release();
597                 }
598             }
599             if (!failConnectPromise(cause)) {
600                 allocHandle.readComplete();
601                 pipeline.fireChannelReadComplete();
602                 pipeline.fireExceptionCaught(cause);
603 
604                 // If oom will close the read event, release connection.
605                 // See https://github.com/netty/netty/issues/10434
606                 if (close || cause instanceof OutOfMemoryError || cause instanceof IOException) {
607                     shutdownInput(false);
608                 }
609             }
610         }
611     }
612 
613     private final class KQueueSocketWritableByteChannel extends SocketWritableByteChannel {
614         KQueueSocketWritableByteChannel() {
615             super(socket);
616         }
617 
618         @Override
619         protected ByteBufAllocator alloc() {
620             return AbstractKQueueStreamChannel.this.alloc();
621         }
622     }
623 }