View Javadoc
1   /*
2    * Copyright 2014 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.epoll;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.buffer.Unpooled;
21  import io.netty.channel.AddressedEnvelope;
22  import io.netty.channel.ChannelFuture;
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.DefaultAddressedEnvelope;
28  import io.netty.channel.socket.DatagramChannel;
29  import io.netty.channel.socket.DatagramPacket;
30  import io.netty.channel.socket.InternetProtocolFamily;
31  import io.netty.channel.unix.Errors;
32  import io.netty.channel.unix.Errors.NativeIoException;
33  import io.netty.channel.unix.UnixChannelUtil;
34  import io.netty.util.ReferenceCountUtil;
35  import io.netty.util.UncheckedBooleanSupplier;
36  import io.netty.util.internal.ObjectUtil;
37  import io.netty.util.internal.RecyclableArrayList;
38  import io.netty.util.internal.StringUtil;
39  
40  import java.io.IOException;
41  import java.net.Inet4Address;
42  import java.net.InetAddress;
43  import java.net.InetSocketAddress;
44  import java.net.NetworkInterface;
45  import java.net.PortUnreachableException;
46  import java.net.SocketAddress;
47  import java.net.SocketException;
48  import java.nio.ByteBuffer;
49  import java.nio.channels.UnresolvedAddressException;
50  
51  import static io.netty.channel.epoll.LinuxSocket.newSocketDgram;
52  
53  /**
54   * {@link DatagramChannel} implementation that uses linux EPOLL Edge-Triggered Mode for
55   * maximal performance.
56   */
57  public final class EpollDatagramChannel extends AbstractEpollChannel implements DatagramChannel {
58      private static final ChannelMetadata METADATA = new ChannelMetadata(true, 16);
59      private static final String EXPECTED_TYPES =
60              " (expected: " + StringUtil.simpleClassName(DatagramPacket.class) + ", " +
61              StringUtil.simpleClassName(AddressedEnvelope.class) + '<' +
62              StringUtil.simpleClassName(ByteBuf.class) + ", " +
63              StringUtil.simpleClassName(InetSocketAddress.class) + ">, " +
64              StringUtil.simpleClassName(ByteBuf.class) + ')';
65  
66      private final EpollDatagramChannelConfig config;
67      private volatile boolean connected;
68  
69      /**
70       * Returns {@code true} if {@link io.netty.channel.unix.SegmentedDatagramPacket} is supported natively.
71       *
72       * @return {@code true} if supported, {@code false} otherwise.
73       */
74      public static boolean isSegmentedDatagramPacketSupported() {
75          return Epoll.isAvailable() &&
76                  // We only support it together with sendmmsg(...)
77                  Native.IS_SUPPORTING_SENDMMSG && Native.IS_SUPPORTING_UDP_SEGMENT;
78      }
79  
80      /**
81       * Create a new instance which selects the {@link InternetProtocolFamily} to use depending
82       * on the Operation Systems default which will be chosen.
83       */
84      public EpollDatagramChannel() {
85          this(null);
86      }
87  
88      /**
89       * Create a new instance using the given {@link InternetProtocolFamily}. If {@code null} is used it will depend
90       * on the Operation Systems default which will be chosen.
91       */
92      public EpollDatagramChannel(InternetProtocolFamily family) {
93          this(newSocketDgram(family), false);
94      }
95  
96      /**
97       * Create a new instance which selects the {@link InternetProtocolFamily} to use depending
98       * on the Operation Systems default which will be chosen.
99       */
100     public EpollDatagramChannel(int fd) {
101         this(new LinuxSocket(fd), true);
102     }
103 
104     private EpollDatagramChannel(LinuxSocket fd, boolean active) {
105         super(null, fd, active);
106         config = new EpollDatagramChannelConfig(this);
107     }
108 
109     @Override
110     public InetSocketAddress remoteAddress() {
111         return (InetSocketAddress) super.remoteAddress();
112     }
113 
114     @Override
115     public InetSocketAddress localAddress() {
116         return (InetSocketAddress) super.localAddress();
117     }
118 
119     @Override
120     public ChannelMetadata metadata() {
121         return METADATA;
122     }
123 
124     @Override
125     public boolean isActive() {
126         return socket.isOpen() && (config.getActiveOnOpen() && isRegistered() || active);
127     }
128 
129     @Override
130     public boolean isConnected() {
131         return connected;
132     }
133 
134     @Override
135     public ChannelFuture joinGroup(InetAddress multicastAddress) {
136         return joinGroup(multicastAddress, newPromise());
137     }
138 
139     @Override
140     public ChannelFuture joinGroup(InetAddress multicastAddress, ChannelPromise promise) {
141         try {
142             return joinGroup(multicastAddress, defaultMulticastInterface(), null, promise);
143         } catch (IOException e) {
144             promise.setFailure(e);
145         }
146         return promise;
147     }
148 
149     /**
150      * Returns the interface to use when none was given: the one set via
151      * {@link io.netty.channel.ChannelOption#IP_MULTICAST_IF} or, if unset, the interface of the local address.
152      */
153     private NetworkInterface defaultMulticastInterface() throws SocketException {
154         NetworkInterface iface = config().getNetworkInterface();
155         if (iface == null) {
156             iface = NetworkInterface.getByInetAddress(localAddress().getAddress());
157         }
158         return iface;
159     }
160 
161     @Override
162     public ChannelFuture joinGroup(
163             InetSocketAddress multicastAddress, NetworkInterface networkInterface) {
164         return joinGroup(multicastAddress, networkInterface, newPromise());
165     }
166 
167     @Override
168     public ChannelFuture joinGroup(
169             InetSocketAddress multicastAddress, NetworkInterface networkInterface,
170             ChannelPromise promise) {
171         return joinGroup(multicastAddress.getAddress(), networkInterface, null, promise);
172     }
173 
174     @Override
175     public ChannelFuture joinGroup(
176             InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source) {
177         return joinGroup(multicastAddress, networkInterface, source, newPromise());
178     }
179 
180     @Override
181     public ChannelFuture joinGroup(
182             final InetAddress multicastAddress, final NetworkInterface networkInterface,
183             final InetAddress source, final ChannelPromise promise) {
184 
185         ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
186         ObjectUtil.checkNotNull(networkInterface, "networkInterface");
187 
188         if (eventLoop().inEventLoop()) {
189             joinGroup0(multicastAddress, networkInterface, source, promise);
190         } else {
191             eventLoop().execute(new Runnable() {
192                 @Override
193                 public void run() {
194                     joinGroup0(multicastAddress, networkInterface, source, promise);
195                 }
196             });
197         }
198         return promise;
199     }
200 
201     private void joinGroup0(
202             final InetAddress multicastAddress, final NetworkInterface networkInterface,
203             final InetAddress source, final ChannelPromise promise) {
204         assert eventLoop().inEventLoop();
205 
206         try {
207             socket.joinGroup(multicastAddress, networkInterface, source);
208             promise.setSuccess();
209         } catch (IOException e) {
210             promise.setFailure(e);
211         }
212     }
213 
214     @Override
215     public ChannelFuture leaveGroup(InetAddress multicastAddress) {
216         return leaveGroup(multicastAddress, newPromise());
217     }
218 
219     @Override
220     public ChannelFuture leaveGroup(InetAddress multicastAddress, ChannelPromise promise) {
221         try {
222             return leaveGroup(multicastAddress, defaultMulticastInterface(), null, promise);
223         } catch (IOException e) {
224             promise.setFailure(e);
225         }
226         return promise;
227     }
228 
229     @Override
230     public ChannelFuture leaveGroup(
231             InetSocketAddress multicastAddress, NetworkInterface networkInterface) {
232         return leaveGroup(multicastAddress, networkInterface, newPromise());
233     }
234 
235     @Override
236     public ChannelFuture leaveGroup(
237             InetSocketAddress multicastAddress,
238             NetworkInterface networkInterface, ChannelPromise promise) {
239         return leaveGroup(multicastAddress.getAddress(), networkInterface, null, promise);
240     }
241 
242     @Override
243     public ChannelFuture leaveGroup(
244             InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source) {
245         return leaveGroup(multicastAddress, networkInterface, source, newPromise());
246     }
247 
248     @Override
249     public ChannelFuture leaveGroup(
250             final InetAddress multicastAddress, final NetworkInterface networkInterface, final InetAddress source,
251             final ChannelPromise promise) {
252         ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
253         ObjectUtil.checkNotNull(networkInterface, "networkInterface");
254 
255         if (eventLoop().inEventLoop()) {
256             leaveGroup0(multicastAddress, networkInterface, source, promise);
257         } else {
258             eventLoop().execute(new Runnable() {
259                 @Override
260                 public void run() {
261                     leaveGroup0(multicastAddress, networkInterface, source, promise);
262                 }
263             });
264         }
265         return promise;
266     }
267 
268     private void leaveGroup0(
269             final InetAddress multicastAddress, final NetworkInterface networkInterface, final InetAddress source,
270             final ChannelPromise promise) {
271         assert eventLoop().inEventLoop();
272 
273         try {
274             socket.leaveGroup(multicastAddress, networkInterface, source);
275             promise.setSuccess();
276         } catch (IOException e) {
277             promise.setFailure(e);
278         }
279     }
280 
281     @Override
282     public ChannelFuture block(
283             InetAddress multicastAddress, NetworkInterface networkInterface,
284             InetAddress sourceToBlock) {
285         return block(multicastAddress, networkInterface, sourceToBlock, newPromise());
286     }
287 
288     @Override
289     public ChannelFuture block(
290             final InetAddress multicastAddress, final NetworkInterface networkInterface,
291             final InetAddress sourceToBlock, final ChannelPromise promise) {
292         ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
293         ObjectUtil.checkNotNull(sourceToBlock, "sourceToBlock");
294         ObjectUtil.checkNotNull(networkInterface, "networkInterface");
295 
296         promise.setFailure(new UnsupportedOperationException("Multicast block not supported"));
297         return promise;
298     }
299 
300     @Override
301     public ChannelFuture block(InetAddress multicastAddress, InetAddress sourceToBlock) {
302         return block(multicastAddress, sourceToBlock, newPromise());
303     }
304 
305     @Override
306     public ChannelFuture block(
307             InetAddress multicastAddress, InetAddress sourceToBlock, ChannelPromise promise) {
308         try {
309             return block(multicastAddress, defaultMulticastInterface(), sourceToBlock, promise);
310         } catch (Throwable e) {
311             promise.setFailure(e);
312         }
313         return promise;
314     }
315 
316     @Override
317     protected AbstractEpollUnsafe newUnsafe() {
318         return new EpollDatagramChannelUnsafe();
319     }
320 
321     @Override
322     protected void doBind(SocketAddress localAddress) throws Exception {
323         if (localAddress instanceof InetSocketAddress) {
324             InetSocketAddress socketAddress = (InetSocketAddress) localAddress;
325             if (socketAddress.getAddress().isAnyLocalAddress() &&
326                     socketAddress.getAddress() instanceof Inet4Address) {
327                 if (socket.family() == InternetProtocolFamily.IPv6) {
328                     localAddress = new InetSocketAddress(Native.INET6_ANY, socketAddress.getPort());
329                 }
330             }
331         }
332         super.doBind(localAddress);
333         active = true;
334     }
335 
336     @Override
337     protected void doWrite(ChannelOutboundBuffer in) throws Exception {
338         int maxMessagesPerWrite = maxMessagesPerWrite();
339         while (maxMessagesPerWrite > 0) {
340             Object msg = in.current();
341             if (msg == null) {
342                 // Wrote all messages.
343                 break;
344             }
345 
346             try {
347                 // Check if sendmmsg(...) is supported which is only the case for GLIBC 2.14+
348                 if (Native.IS_SUPPORTING_SENDMMSG && in.size() > 1 ||
349                         // We only handle UDP_SEGMENT in sendmmsg.
350                         in.current() instanceof io.netty.channel.unix.SegmentedDatagramPacket) {
351                     NativeDatagramPacketArray array = cleanDatagramPacketArray();
352                     array.add(in, isConnected(), maxMessagesPerWrite);
353                     int cnt = array.count();
354 
355                     if (cnt >= 1) {
356                         // Try to use gathering writes via sendmmsg(...) syscall.
357                         int offset = 0;
358                         NativeDatagramPacketArray.NativeDatagramPacket[] packets = array.packets();
359 
360                         int send = socket.sendmmsg(packets, offset, cnt);
361                         if (send == 0) {
362                             // Did not write all messages.
363                             break;
364                         }
365                         for (int i = 0; i < send; i++) {
366                             in.remove();
367                         }
368                         maxMessagesPerWrite -= send;
369                         continue;
370                     }
371                 }
372                 boolean done = false;
373                 for (int i = config().getWriteSpinCount(); i > 0; --i) {
374                     if (doWriteMessage(msg)) {
375                         done = true;
376                         break;
377                     }
378                 }
379 
380                 if (done) {
381                     in.remove();
382                     maxMessagesPerWrite --;
383                 } else {
384                     break;
385                 }
386             } catch (IOException e) {
387                 maxMessagesPerWrite --;
388                 // Continue on write error as a DatagramChannel can write to multiple remote peers
389                 //
390                 // See https://github.com/netty/netty/issues/2665
391                 in.remove(e);
392             }
393         }
394 
395         if (in.isEmpty()) {
396             // Did write all messages.
397             clearFlag(Native.EPOLLOUT);
398         } else {
399             // Did not write all messages.
400             setFlag(Native.EPOLLOUT);
401         }
402     }
403 
404     private boolean doWriteMessage(Object msg) throws Exception {
405         final ByteBuf data;
406         final InetSocketAddress remoteAddress;
407         if (msg instanceof AddressedEnvelope) {
408             @SuppressWarnings("unchecked")
409             AddressedEnvelope<ByteBuf, InetSocketAddress> envelope =
410                     (AddressedEnvelope<ByteBuf, InetSocketAddress>) msg;
411             data = envelope.content();
412             remoteAddress = envelope.recipient();
413         } else {
414             data = (ByteBuf) msg;
415             remoteAddress = null;
416         }
417 
418         final int dataLen = data.readableBytes();
419         try {
420             // A zero-length datagram is valid; sendto() returns 0 for it.
421             return doWriteOrSendBytes(data, remoteAddress, false) > 0 || dataLen == 0;
422         } catch (NativeIoException e) {
423             if (remoteAddress == null) {
424                 throw translateForConnected(e);
425             }
426             throw e;
427         }
428     }
429 
430     private static void checkUnresolved(AddressedEnvelope<?, ?> envelope) {
431         if (envelope.recipient() instanceof InetSocketAddress
432                 && (((InetSocketAddress) envelope.recipient()).isUnresolved())) {
433             throw new UnresolvedAddressException();
434         }
435     }
436 
437     @Override
438     protected Object filterOutboundMessage(Object msg) {
439         if (msg instanceof io.netty.channel.unix.SegmentedDatagramPacket) {
440             if (!Native.IS_SUPPORTING_UDP_SEGMENT) {
441                 throw new UnsupportedOperationException(
442                         "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
443             }
444             io.netty.channel.unix.SegmentedDatagramPacket packet = (io.netty.channel.unix.SegmentedDatagramPacket) msg;
445             checkUnresolved(packet);
446 
447             ByteBuf content = packet.content();
448             return UnixChannelUtil.isBufferCopyNeededForWrite(content) ?
449                     packet.replace(newDirectBuffer(packet, content)) : msg;
450         }
451         if (msg instanceof DatagramPacket) {
452             DatagramPacket packet = (DatagramPacket) msg;
453             checkUnresolved(packet);
454 
455             ByteBuf content = packet.content();
456             return UnixChannelUtil.isBufferCopyNeededForWrite(content) ?
457                     new DatagramPacket(newDirectBuffer(packet, content), packet.recipient()) : msg;
458         }
459 
460         if (msg instanceof ByteBuf) {
461             ByteBuf buf = (ByteBuf) msg;
462             return UnixChannelUtil.isBufferCopyNeededForWrite(buf)? newDirectBuffer(buf) : buf;
463         }
464 
465         if (msg instanceof AddressedEnvelope) {
466             @SuppressWarnings("unchecked")
467             AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg;
468             checkUnresolved(e);
469 
470             if (e.content() instanceof ByteBuf &&
471                 (e.recipient() == null || e.recipient() instanceof InetSocketAddress)) {
472 
473                 ByteBuf content = (ByteBuf) e.content();
474                 return UnixChannelUtil.isBufferCopyNeededForWrite(content)?
475                         new DefaultAddressedEnvelope<ByteBuf, InetSocketAddress>(
476                             newDirectBuffer(e, content), (InetSocketAddress) e.recipient()) : e;
477             }
478         }
479 
480         throw new UnsupportedOperationException(
481                 "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
482     }
483 
484     @Override
485     public EpollDatagramChannelConfig config() {
486         return config;
487     }
488 
489     @Override
490     protected void doDisconnect() throws Exception {
491         socket.disconnect();
492         connected = active = false;
493         resetCachedAddresses();
494     }
495 
496     @Override
497     protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
498         if (super.doConnect(remoteAddress, localAddress)) {
499             connected = true;
500             return true;
501         }
502         return false;
503     }
504 
505     @Override
506     protected void doClose() throws Exception {
507         super.doClose();
508         connected = false;
509     }
510 
511     final class EpollDatagramChannelUnsafe extends AbstractEpollUnsafe {
512 
513         @Override
514         void epollInReady() {
515             assert eventLoop().inEventLoop();
516             EpollDatagramChannelConfig config = config();
517             if (shouldBreakEpollInReady(config)) {
518                 clearEpollIn0();
519                 return;
520             }
521             final EpollRecvByteAllocatorHandle allocHandle = recvBufAllocHandle();
522             allocHandle.edgeTriggered(isFlagSet(Native.EPOLLET));
523 
524             final ChannelPipeline pipeline = pipeline();
525             final ByteBufAllocator allocator = config.getAllocator();
526             allocHandle.reset(config);
527             epollInBefore();
528 
529             Throwable exception = null;
530             try {
531                 try {
532                     boolean connected = isConnected();
533                     do {
534                         final boolean read;
535                         int datagramSize = config().getMaxDatagramPayloadSize();
536 
537                         ByteBuf byteBuf = allocHandle.allocate(allocator);
538                         // Only try to use recvmmsg if its really supported by the running system.
539                         int numDatagram = Native.IS_SUPPORTING_RECVMMSG ?
540                                 datagramSize == 0 ? 1 : byteBuf.writableBytes() / datagramSize :
541                                 0;
542                         try {
543                             if (numDatagram <= 1) {
544                                 if (!connected || config.isUdpGro()) {
545                                     read = recvmsg(allocHandle, cleanDatagramPacketArray(), byteBuf);
546                                 } else {
547                                     read = connectedRead(allocHandle, byteBuf, datagramSize);
548                                 }
549                             } else {
550                                 // Try to use scattering reads via recvmmsg(...) syscall.
551                                 read = scatteringRead(allocHandle, cleanDatagramPacketArray(),
552                                         byteBuf, datagramSize, numDatagram);
553                             }
554                         } catch (NativeIoException e) {
555                             if (connected) {
556                                 throw translateForConnected(e);
557                             }
558                             throw e;
559                         }
560 
561                         if (read) {
562                             readPending = false;
563                         } else {
564                             break;
565                         }
566                     // We use the TRUE_SUPPLIER as it is also ok to read less then what we did try to read (as long
567                     // as we read anything).
568                     } while (allocHandle.continueReading(UncheckedBooleanSupplier.TRUE_SUPPLIER));
569                 } catch (Throwable t) {
570                     exception = t;
571                 }
572 
573                 allocHandle.readComplete();
574                 pipeline.fireChannelReadComplete();
575 
576                 if (exception != null) {
577                     pipeline.fireExceptionCaught(exception);
578                 }
579             } finally {
580                 epollInFinally(config);
581             }
582         }
583     }
584 
585     private boolean connectedRead(EpollRecvByteAllocatorHandle allocHandle, ByteBuf byteBuf, int maxDatagramPacketSize)
586             throws Exception {
587         try {
588             int writable = maxDatagramPacketSize != 0 ? Math.min(byteBuf.writableBytes(), maxDatagramPacketSize)
589                     : byteBuf.writableBytes();
590             allocHandle.attemptedBytesRead(writable);
591 
592             int writerIndex = byteBuf.writerIndex();
593             int localReadAmount;
594             if (byteBuf.hasMemoryAddress()) {
595                 localReadAmount = socket.recvAddress(byteBuf.memoryAddress(), writerIndex, writerIndex + writable);
596             } else {
597                 ByteBuffer buf = byteBuf.internalNioBuffer(writerIndex, writable);
598                 localReadAmount = socket.recv(buf, buf.position(), buf.limit());
599             }
600 
601             if (localReadAmount <= 0) {
602                 allocHandle.lastBytesRead(localReadAmount);
603 
604                 // nothing was read, release the buffer.
605                 return false;
606             }
607             byteBuf.writerIndex(writerIndex + localReadAmount);
608 
609             allocHandle.lastBytesRead(maxDatagramPacketSize <= 0 ?
610                     localReadAmount : writable);
611 
612             DatagramPacket packet = new DatagramPacket(byteBuf, localAddress(), remoteAddress());
613             allocHandle.incMessagesRead(1);
614 
615             pipeline().fireChannelRead(packet);
616             byteBuf = null;
617             return true;
618         } finally {
619             if (byteBuf != null) {
620                 byteBuf.release();
621             }
622         }
623     }
624 
625     private IOException translateForConnected(NativeIoException e) {
626         // We need to correctly translate connect errors to match NIO behaviour.
627         if (e.expectedErr() == Errors.ERROR_ECONNREFUSED_NEGATIVE) {
628             PortUnreachableException error = new PortUnreachableException(e.getMessage());
629             error.initCause(e);
630             return error;
631         }
632         return e;
633     }
634 
635     private static void addDatagramPacketToOut(DatagramPacket packet,
636                                               RecyclableArrayList out) {
637         if (packet instanceof io.netty.channel.unix.SegmentedDatagramPacket) {
638             io.netty.channel.unix.SegmentedDatagramPacket segmentedDatagramPacket =
639                     (io.netty.channel.unix.SegmentedDatagramPacket) packet;
640             ByteBuf content = segmentedDatagramPacket.content();
641             InetSocketAddress recipient = segmentedDatagramPacket.recipient();
642             InetSocketAddress sender = segmentedDatagramPacket.sender();
643             int segmentSize = segmentedDatagramPacket.segmentSize();
644             do {
645                 out.add(new DatagramPacket(content.readRetainedSlice(Math.min(content.readableBytes(),
646                         segmentSize)), recipient, sender));
647             } while (content.isReadable());
648 
649             segmentedDatagramPacket.release();
650         } else {
651             out.add(packet);
652         }
653     }
654 
655     private static void releaseAndRecycle(ByteBuf byteBuf, RecyclableArrayList packetList) {
656         if (byteBuf != null) {
657             byteBuf.release();
658         }
659         if (packetList != null) {
660             for (int i = 0; i < packetList.size(); i++) {
661                 ReferenceCountUtil.release(packetList.get(i));
662             }
663             packetList.recycle();
664         }
665     }
666 
667     private static void processPacket(ChannelPipeline pipeline, EpollRecvByteAllocatorHandle handle,
668                                       int bytesRead, DatagramPacket packet) {
669         handle.lastBytesRead(Math.max(1, bytesRead)); // Avoid signalling end-of-data for zero-sized datagrams.
670         handle.incMessagesRead(1);
671         pipeline.fireChannelRead(packet);
672     }
673 
674     private static void processPacketList(ChannelPipeline pipeline, EpollRecvByteAllocatorHandle handle,
675                                           int bytesRead, RecyclableArrayList packetList) {
676         int messagesRead = packetList.size();
677         handle.lastBytesRead(Math.max(1, bytesRead)); // Avoid signalling end-of-data for zero-sized datagrams.
678         handle.incMessagesRead(messagesRead);
679         for (int i = 0; i < messagesRead; i++) {
680             pipeline.fireChannelRead(packetList.set(i, Unpooled.EMPTY_BUFFER));
681         }
682     }
683 
684     private boolean recvmsg(EpollRecvByteAllocatorHandle allocHandle,
685                             NativeDatagramPacketArray array, ByteBuf byteBuf) throws IOException {
686         RecyclableArrayList datagramPackets = null;
687         try {
688             int writable = byteBuf.writableBytes();
689 
690             boolean added = array.addWritable(byteBuf, byteBuf.writerIndex(), writable);
691             assert added;
692 
693             allocHandle.attemptedBytesRead(writable);
694 
695             NativeDatagramPacketArray.NativeDatagramPacket msg = array.packets()[0];
696 
697             int bytesReceived = socket.recvmsg(msg);
698             if (!msg.hasSender()) {
699                 allocHandle.lastBytesRead(-1);
700                 return false;
701             }
702             byteBuf.writerIndex(bytesReceived);
703             InetSocketAddress local = localAddress();
704             DatagramPacket packet = msg.newDatagramPacket(byteBuf, local);
705             if (!(packet instanceof io.netty.channel.unix.SegmentedDatagramPacket)) {
706                 processPacket(pipeline(), allocHandle, bytesReceived, packet);
707             } else {
708                 // Its important that we process all received data out of the NativeDatagramPacketArray
709                 // before we call fireChannelRead(...). This is because the user may call flush()
710                 // in a channelRead(...) method and so may re-use the NativeDatagramPacketArray again.
711                 datagramPackets = RecyclableArrayList.newInstance();
712                 addDatagramPacketToOut(packet, datagramPackets);
713 
714                 processPacketList(pipeline(), allocHandle, bytesReceived, datagramPackets);
715                 datagramPackets.recycle();
716                 datagramPackets = null;
717             }
718 
719             return true;
720         } finally {
721             releaseAndRecycle(byteBuf, datagramPackets);
722         }
723     }
724 
725     private boolean scatteringRead(EpollRecvByteAllocatorHandle allocHandle, NativeDatagramPacketArray array,
726             ByteBuf byteBuf, int datagramSize, int numDatagram) throws IOException {
727         RecyclableArrayList datagramPackets = null;
728         try {
729             int offset = byteBuf.writerIndex();
730             for (int i = 0; i < numDatagram;  i++, offset += datagramSize) {
731                 if (!array.addWritable(byteBuf, offset, datagramSize)) {
732                     break;
733                 }
734             }
735 
736             allocHandle.attemptedBytesRead(offset - byteBuf.writerIndex());
737 
738             NativeDatagramPacketArray.NativeDatagramPacket[] packets = array.packets();
739 
740             int received = socket.recvmmsg(packets, 0, array.count());
741             if (received == 0) {
742                 allocHandle.lastBytesRead(-1);
743                 return false;
744             }
745 
746             InetSocketAddress local = localAddress();
747 
748             // Set the writerIndex too the maximum number of bytes we might have read.
749             int bytesReceived = received * datagramSize;
750             byteBuf.writerIndex(byteBuf.writerIndex() + bytesReceived);
751 
752             if (received == 1) {
753                 // Single packet fast-path
754                 DatagramPacket packet = packets[0].newDatagramPacket(byteBuf, local);
755                 if (!(packet instanceof io.netty.channel.unix.SegmentedDatagramPacket)) {
756                     processPacket(pipeline(), allocHandle, datagramSize, packet);
757                     return true;
758                 }
759                 // A UDP_GRO batch is split up by the loop below, which creates the packet again, so release this one.
760                 packet.release();
761             }
762             // Its important that we process all received data out of the NativeDatagramPacketArray
763             // before we call fireChannelRead(...). This is because the user may call flush()
764             // in a channelRead(...) method and so may re-use the NativeDatagramPacketArray again.
765             datagramPackets = RecyclableArrayList.newInstance();
766             for (int i = 0; i < received; i++) {
767                 DatagramPacket packet = packets[i].newDatagramPacket(byteBuf, local);
768 
769                 // We need to skip the maximum datagram size to ensure we have the readerIndex in the right position
770                 // for the next one.
771                 byteBuf.skipBytes(datagramSize);
772                 addDatagramPacketToOut(packet, datagramPackets);
773             }
774             // Ass we did use readRetainedSlice(...) before we should now release the byteBuf and null it out.
775             byteBuf.release();
776             byteBuf = null;
777 
778             processPacketList(pipeline(), allocHandle, bytesReceived, datagramPackets);
779             datagramPackets.recycle();
780             datagramPackets = null;
781             return true;
782         } finally {
783             releaseAndRecycle(byteBuf, datagramPackets);
784         }
785     }
786 
787     private NativeDatagramPacketArray cleanDatagramPacketArray() {
788         return ((EpollEventLoop) eventLoop()).cleanDatagramPacketArray();
789     }
790 }