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