package io.netty.channel.epoll;

import g.a.a.a.a;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.AbstractChannel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.EventLoop;
import io.netty.channel.FileRegion;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.epoll.AbstractEpollChannel;
import io.netty.channel.socket.DuplexChannel;
import io.netty.channel.unix.FileDescriptor;
import io.netty.channel.unix.IovArray;
import io.netty.channel.unix.SocketWritableByteChannel;
import io.netty.channel.unix.UnixChannelUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.WritableByteChannel;
import java.util.Queue;
import java.util.concurrent.Executor;

/* JADX INFO: loaded from: classes.dex */
public abstract class AbstractEpollStreamChannel extends AbstractEpollChannel implements DuplexChannel {
    public static final /* synthetic */ boolean $assertionsDisabled = false;
    private static final ClosedChannelException CLEAR_SPLICE_QUEUE_CLOSED_CHANNEL_EXCEPTION;
    private static final String EXPECTED_TYPES;
    private static final ClosedChannelException FAIL_SPLICE_IF_CLOSED_CLOSED_CHANNEL_EXCEPTION;
    private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
    private static final ClosedChannelException SPLICE_TO_CLOSED_CHANNEL_EXCEPTION;
    private static final InternalLogger logger;
    private WritableByteChannel byteChannel;
    private final Runnable flushTask;
    private FileDescriptor pipeIn;
    private FileDescriptor pipeOut;
    private Queue<SpliceInTask> spliceQueue;

    public final class EpollSocketWritableByteChannel extends SocketWritableByteChannel {
        public EpollSocketWritableByteChannel() {
            super(AbstractEpollStreamChannel.this.socket);
        }

        @Override // io.netty.channel.unix.SocketWritableByteChannel
        public ByteBufAllocator alloc() {
            return AbstractEpollStreamChannel.this.alloc();
        }
    }

    public class EpollStreamUnsafe extends AbstractEpollChannel.AbstractEpollUnsafe {
        public EpollStreamUnsafe() {
            super();
        }

        private void handleReadException(ChannelPipeline channelPipeline, ByteBuf byteBuf, Throwable th, boolean z2, EpollRecvByteAllocatorHandle epollRecvByteAllocatorHandle) {
            if (byteBuf != null) {
                if (byteBuf.isReadable()) {
                    this.readPending = false;
                    channelPipeline.fireChannelRead((Object) byteBuf);
                } else {
                    byteBuf.release();
                }
            }
            epollRecvByteAllocatorHandle.readComplete();
            channelPipeline.fireChannelReadComplete();
            channelPipeline.fireExceptionCaught(th);
            if (z2 || (th instanceof IOException)) {
                shutdownInput(false);
            }
        }

        /* JADX WARN: Removed duplicated region for block: B:38:0x00a7 A[Catch: all -> 0x00ab, TRY_LEAVE, TryCatch #3 {all -> 0x00ab, blocks: (B:36:0x009f, B:38:0x00a7, B:27:0x0084), top: B:59:0x0084 }] */
        @Override // io.netty.channel.epoll.AbstractEpollChannel.AbstractEpollUnsafe
        /*
            Code decompiled incorrectly, please refer to instructions dump.
            To view partially-correct add '--show-bad-code' argument
        */
        public void epollInReady() {
            /*
                r9 = this;
                io.netty.channel.epoll.AbstractEpollStreamChannel r0 = io.netty.channel.epoll.AbstractEpollStreamChannel.this
                io.netty.channel.epoll.EpollChannelConfig r0 = r0.config()
                io.netty.channel.epoll.AbstractEpollStreamChannel r1 = io.netty.channel.epoll.AbstractEpollStreamChannel.this
                boolean r1 = r1.shouldBreakEpollInReady(r0)
                if (r1 == 0) goto L12
                r9.clearEpollIn0()
                return
            L12:
                io.netty.channel.epoll.EpollRecvByteAllocatorHandle r7 = r9.recvBufAllocHandle()
                io.netty.channel.epoll.AbstractEpollStreamChannel r1 = io.netty.channel.epoll.AbstractEpollStreamChannel.this
                int r2 = io.netty.channel.epoll.Native.EPOLLET
                boolean r1 = r1.isFlagSet(r2)
                r7.edgeTriggered(r1)
                io.netty.channel.epoll.AbstractEpollStreamChannel r1 = io.netty.channel.epoll.AbstractEpollStreamChannel.this
                io.netty.channel.ChannelPipeline r3 = r1.pipeline()
                io.netty.buffer.ByteBufAllocator r1 = r0.getAllocator()
                r7.reset(r0)
                r9.epollInBefore()
            L31:
                r2 = 0
                r4 = 0
                io.netty.channel.epoll.AbstractEpollStreamChannel r5 = io.netty.channel.epoll.AbstractEpollStreamChannel.this     // Catch: java.lang.Throwable -> Lb5
                java.util.Queue r5 = io.netty.channel.epoll.AbstractEpollStreamChannel.access$400(r5)     // Catch: java.lang.Throwable -> Lb5
                if (r5 == 0) goto L63
                io.netty.channel.epoll.AbstractEpollStreamChannel r5 = io.netty.channel.epoll.AbstractEpollStreamChannel.this     // Catch: java.lang.Throwable -> Lb5
                java.util.Queue r5 = io.netty.channel.epoll.AbstractEpollStreamChannel.access$400(r5)     // Catch: java.lang.Throwable -> Lb5
                java.lang.Object r5 = r5.peek()     // Catch: java.lang.Throwable -> Lb5
                io.netty.channel.epoll.AbstractEpollStreamChannel$SpliceInTask r5 = (io.netty.channel.epoll.AbstractEpollStreamChannel.SpliceInTask) r5     // Catch: java.lang.Throwable -> Lb5
                if (r5 == 0) goto L63
                boolean r5 = r5.spliceIn(r7)     // Catch: java.lang.Throwable -> Lb5
                if (r5 == 0) goto L61
                io.netty.channel.epoll.AbstractEpollStreamChannel r5 = io.netty.channel.epoll.AbstractEpollStreamChannel.this     // Catch: java.lang.Throwable -> Lb5
                boolean r5 = r5.isActive()     // Catch: java.lang.Throwable -> Lb5
                if (r5 == 0) goto L98
                io.netty.channel.epoll.AbstractEpollStreamChannel r5 = io.netty.channel.epoll.AbstractEpollStreamChannel.this     // Catch: java.lang.Throwable -> Lb5
                java.util.Queue r5 = io.netty.channel.epoll.AbstractEpollStreamChannel.access$400(r5)     // Catch: java.lang.Throwable -> Lb5
                r5.remove()     // Catch: java.lang.Throwable -> Lb5
                goto L98
            L61:
                r8 = r4
                goto L9f
            L63:
                io.netty.buffer.ByteBuf r5 = r7.allocate(r1)     // Catch: java.lang.Throwable -> Lb5
                io.netty.channel.epoll.AbstractEpollStreamChannel r6 = io.netty.channel.epoll.AbstractEpollStreamChannel.this     // Catch: java.lang.Throwable -> Lb0
                int r6 = r6.doReadBytes(r5)     // Catch: java.lang.Throwable -> Lb0
                r7.lastBytesRead(r6)     // Catch: java.lang.Throwable -> Lb0
                int r6 = r7.lastBytesRead()     // Catch: java.lang.Throwable -> Lb0
                r8 = 1
                if (r6 > 0) goto L87
                r5.release()     // Catch: java.lang.Throwable -> Lb0
                int r1 = r7.lastBytesRead()     // Catch: java.lang.Throwable -> Lb5
                if (r1 >= 0) goto L81
                goto L82
            L81:
                r8 = r4
            L82:
                if (r8 == 0) goto L9f
                r9.readPending = r4     // Catch: java.lang.Throwable -> Lab
                goto L9f
            L87:
                r7.incMessagesRead(r8)     // Catch: java.lang.Throwable -> Lb0
                r9.readPending = r4     // Catch: java.lang.Throwable -> Lb0
                r3.fireChannelRead(r5)     // Catch: java.lang.Throwable -> Lb0
                io.netty.channel.epoll.AbstractEpollStreamChannel r5 = io.netty.channel.epoll.AbstractEpollStreamChannel.this     // Catch: java.lang.Throwable -> Lb5
                boolean r5 = r5.shouldBreakEpollInReady(r0)     // Catch: java.lang.Throwable -> Lb5
                if (r5 == 0) goto L98
                goto L61
            L98:
                boolean r5 = r7.continueReading()     // Catch: java.lang.Throwable -> Lb5
                if (r5 != 0) goto L31
                goto L61
            L9f:
                r7.readComplete()     // Catch: java.lang.Throwable -> Lab
                r3.fireChannelReadComplete()     // Catch: java.lang.Throwable -> Lab
                if (r8 == 0) goto Lbd
                r9.shutdownInput(r4)     // Catch: java.lang.Throwable -> Lab
                goto Lbd
            Lab:
                r1 = move-exception
                r5 = r1
                r4 = r2
                r6 = r8
                goto Lb9
            Lb0:
                r1 = move-exception
                r6 = r4
                r4 = r5
                r5 = r1
                goto Lb9
            Lb5:
                r1 = move-exception
                r5 = r1
                r6 = r4
                r4 = r2
            Lb9:
                r2 = r9
                r2.handleReadException(r3, r4, r5, r6, r7)     // Catch: java.lang.Throwable -> Lc1
            Lbd:
                r9.epollInFinally(r0)
                return
            Lc1:
                r1 = move-exception
                r9.epollInFinally(r0)
                throw r1
            */
            throw new UnsupportedOperationException("Method not decompiled: io.netty.channel.epoll.AbstractEpollStreamChannel.EpollStreamUnsafe.epollInReady():void");
        }

        @Override // io.netty.channel.epoll.AbstractEpollChannel.AbstractEpollUnsafe
        public EpollRecvByteAllocatorHandle newEpollHandle(RecvByteBufAllocator.ExtendedHandle extendedHandle) {
            return new EpollRecvByteAllocatorStreamingHandle(extendedHandle);
        }

        @Override // io.netty.channel.AbstractChannel.AbstractUnsafe
        public Executor prepareToClose() {
            return super.prepareToClose();
        }
    }

    public final class SpliceFdTask extends SpliceInTask {
        public static final /* synthetic */ boolean $assertionsDisabled = false;
        private final FileDescriptor fd;
        private final int offset;
        private final ChannelPromise promise;

        public SpliceFdTask(FileDescriptor fileDescriptor, int i2, int i3, ChannelPromise channelPromise) {
            super(i3, channelPromise);
            this.fd = fileDescriptor;
            this.promise = channelPromise;
            this.offset = i2;
        }

        @Override // io.netty.channel.epoll.AbstractEpollStreamChannel.SpliceInTask
        public boolean spliceIn(RecvByteBufAllocator.Handle handle) {
            if (this.len == 0) {
                this.promise.setSuccess();
                return true;
            }
            try {
                FileDescriptor[] fileDescriptorArrPipe = FileDescriptor.pipe();
                FileDescriptor fileDescriptor = fileDescriptorArrPipe[0];
                FileDescriptor fileDescriptor2 = fileDescriptorArrPipe[1];
                try {
                    int iSpliceIn = spliceIn(fileDescriptor2, handle);
                    if (iSpliceIn > 0) {
                        int i2 = this.len;
                        if (i2 != Integer.MAX_VALUE) {
                            this.len = i2 - iSpliceIn;
                        }
                        do {
                            iSpliceIn -= Native.splice(fileDescriptor.intValue(), -1L, this.fd.intValue(), this.offset, iSpliceIn);
                        } while (iSpliceIn > 0);
                        if (this.len == 0) {
                            this.promise.setSuccess();
                            return true;
                        }
                    }
                    return false;
                } finally {
                    AbstractEpollStreamChannel.safeClosePipe(fileDescriptor);
                    AbstractEpollStreamChannel.safeClosePipe(fileDescriptor2);
                }
            } catch (Throwable th) {
                this.promise.setFailure(th);
                return true;
            }
        }
    }

    public final class SpliceInChannelTask extends SpliceInTask implements ChannelFutureListener {
        public static final /* synthetic */ boolean $assertionsDisabled = false;
        private final AbstractEpollStreamChannel ch;

        public SpliceInChannelTask(AbstractEpollStreamChannel abstractEpollStreamChannel, int i2, ChannelPromise channelPromise) {
            super(i2, channelPromise);
            this.ch = abstractEpollStreamChannel;
        }

        @Override // io.netty.util.concurrent.GenericFutureListener
        public void operationComplete(ChannelFuture channelFuture) {
            if (channelFuture.isSuccess()) {
                return;
            }
            this.promise.setFailure(channelFuture.cause());
        }

        /* JADX WARN: Multi-variable type inference failed */
        /* JADX WARN: Type inference failed for: r0v10, types: [io.netty.channel.ChannelPromise, java.util.concurrent.Future] */
        /* JADX WARN: Type inference failed for: r0v16 */
        /* JADX WARN: Type inference failed for: r0v17 */
        /* JADX WARN: Type inference failed for: r4v1, types: [io.netty.channel.Channel$Unsafe] */
        @Override // io.netty.channel.epoll.AbstractEpollStreamChannel.SpliceInTask
        public boolean spliceIn(RecvByteBufAllocator.Handle handle) {
            if (this.len == 0) {
                this.promise.setSuccess();
                return true;
            }
            try {
                FileDescriptor fileDescriptor = this.ch.pipeOut;
                if (fileDescriptor == null) {
                    FileDescriptor[] fileDescriptorArrPipe = FileDescriptor.pipe();
                    this.ch.pipeIn = fileDescriptorArrPipe[0];
                    fileDescriptor = this.ch.pipeOut = fileDescriptorArrPipe[1];
                }
                int iSpliceIn = spliceIn(fileDescriptor, handle);
                if (iSpliceIn > 0) {
                    int i2 = this.len;
                    if (i2 != Integer.MAX_VALUE) {
                        this.len = i2 - iSpliceIn;
                    }
                    ?? AddListener = this.len == 0 ? this.promise : this.ch.newPromise().addListener((GenericFutureListener<? extends Future<? super Void>>) this);
                    boolean zIsAutoRead = AbstractEpollStreamChannel.this.config().isAutoRead();
                    this.ch.unsafe().write(AbstractEpollStreamChannel.this.new SpliceOutTask(this.ch, iSpliceIn, zIsAutoRead), AddListener);
                    this.ch.unsafe().flush();
                    if (zIsAutoRead && !AddListener.isDone()) {
                        AbstractEpollStreamChannel.this.config().setAutoRead(false);
                    }
                }
                return this.len == 0;
            } catch (Throwable th) {
                this.promise.setFailure(th);
                return true;
            }
        }
    }

    public abstract class SpliceInTask {
        public int len;
        public final ChannelPromise promise;

        public SpliceInTask(int i2, ChannelPromise channelPromise) {
            this.promise = channelPromise;
            this.len = i2;
        }

        public final int spliceIn(FileDescriptor fileDescriptor, RecvByteBufAllocator.Handle handle) {
            int iMin = Math.min(handle.guess(), this.len);
            int i2 = 0;
            while (true) {
                int iSplice = Native.splice(AbstractEpollStreamChannel.this.socket.intValue(), -1L, fileDescriptor.intValue(), -1L, iMin);
                if (iSplice == 0) {
                    return i2;
                }
                i2 += iSplice;
                iMin -= iSplice;
            }
        }

        public abstract boolean spliceIn(RecvByteBufAllocator.Handle handle);
    }

    public final class SpliceOutTask {
        public static final /* synthetic */ boolean $assertionsDisabled = false;
        private final boolean autoRead;
        private final AbstractEpollStreamChannel ch;
        private int len;

        public SpliceOutTask(AbstractEpollStreamChannel abstractEpollStreamChannel, int i2, boolean z2) {
            this.ch = abstractEpollStreamChannel;
            this.len = i2;
            this.autoRead = z2;
        }

        public boolean spliceOut() throws IOException {
            try {
                int iSplice = this.len - Native.splice(this.ch.pipeIn.intValue(), -1L, this.ch.socket.intValue(), -1L, this.len);
                this.len = iSplice;
                if (iSplice != 0) {
                    return false;
                }
                if (this.autoRead) {
                    AbstractEpollStreamChannel.this.config().setAutoRead(true);
                }
                return true;
            } catch (IOException e2) {
                if (this.autoRead) {
                    AbstractEpollStreamChannel.this.config().setAutoRead(true);
                }
                throw e2;
            }
        }
    }

    static {
        StringBuilder sbF = a.F(" (expected: ");
        sbF.append(StringUtil.simpleClassName((Class<?>) ByteBuf.class));
        sbF.append(", ");
        sbF.append(StringUtil.simpleClassName((Class<?>) DefaultFileRegion.class));
        sbF.append(')');
        EXPECTED_TYPES = sbF.toString();
        logger = InternalLoggerFactory.getInstance((Class<?>) AbstractEpollStreamChannel.class);
        CLEAR_SPLICE_QUEUE_CLOSED_CHANNEL_EXCEPTION = (ClosedChannelException) a.N(AbstractEpollStreamChannel.class, "clearSpliceQueue()");
        SPLICE_TO_CLOSED_CHANNEL_EXCEPTION = (ClosedChannelException) a.N(AbstractEpollStreamChannel.class, "spliceTo(...)");
        FAIL_SPLICE_IF_CLOSED_CLOSED_CHANNEL_EXCEPTION = (ClosedChannelException) a.N(AbstractEpollStreamChannel.class, "failSpliceIfClosed(...)");
    }

    public AbstractEpollStreamChannel(int i2) {
        this(new LinuxSocket(i2));
    }

    public AbstractEpollStreamChannel(Channel channel, int i2) {
        this(channel, new LinuxSocket(i2));
    }

    public AbstractEpollStreamChannel(Channel channel, LinuxSocket linuxSocket) {
        super(channel, linuxSocket, Native.EPOLLIN, true);
        this.flushTask = new Runnable() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.1
            @Override // java.lang.Runnable
            public void run() {
                ((AbstractEpollChannel.AbstractEpollUnsafe) AbstractEpollStreamChannel.this.unsafe()).flush0();
            }
        };
        this.flags |= Native.EPOLLRDHUP;
    }

    public AbstractEpollStreamChannel(Channel channel, LinuxSocket linuxSocket, SocketAddress socketAddress) {
        super(channel, linuxSocket, Native.EPOLLIN, socketAddress);
        this.flushTask = new Runnable() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.1
            @Override // java.lang.Runnable
            public void run() {
                ((AbstractEpollChannel.AbstractEpollUnsafe) AbstractEpollStreamChannel.this.unsafe()).flush0();
            }
        };
        this.flags |= Native.EPOLLRDHUP;
    }

    public AbstractEpollStreamChannel(LinuxSocket linuxSocket) {
        this(linuxSocket, AbstractEpollChannel.isSoErrorZero(linuxSocket));
    }

    public AbstractEpollStreamChannel(LinuxSocket linuxSocket, boolean z2) {
        super((Channel) null, linuxSocket, Native.EPOLLIN, z2);
        this.flushTask = new Runnable() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.1
            @Override // java.lang.Runnable
            public void run() {
                ((AbstractEpollChannel.AbstractEpollUnsafe) AbstractEpollStreamChannel.this.unsafe()).flush0();
            }
        };
        this.flags |= Native.EPOLLRDHUP;
    }

    private void addToSpliceQueue(final SpliceInTask spliceInTask) {
        EventLoop eventLoop = eventLoop();
        if (eventLoop.inEventLoop()) {
            addToSpliceQueue0(spliceInTask);
        } else {
            eventLoop.execute(new Runnable() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.8
                @Override // java.lang.Runnable
                public void run() {
                    AbstractEpollStreamChannel.this.addToSpliceQueue0(spliceInTask);
                }
            });
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void addToSpliceQueue0(SpliceInTask spliceInTask) {
        if (this.spliceQueue == null) {
            this.spliceQueue = PlatformDependent.newMpscQueue();
        }
        this.spliceQueue.add(spliceInTask);
    }

    private void adjustMaxBytesPerGatheringWrite(long j2, long j3, long j4) {
        long j5;
        if (j2 == j3) {
            j5 = j2 << 1;
            if (j5 <= j4) {
                return;
            }
        } else {
            if (j2 <= 4096) {
                return;
            }
            j5 = j2 >>> 1;
            if (j3 >= j5) {
                return;
            }
        }
        config().setMaxBytesPerGatheringWrite(j5);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void clearSpliceQueue() {
        if (this.spliceQueue == null) {
            return;
        }
        while (true) {
            SpliceInTask spliceInTaskPoll = this.spliceQueue.poll();
            if (spliceInTaskPoll == null) {
                return;
            } else {
                spliceInTaskPoll.promise.tryFailure(CLEAR_SPLICE_QUEUE_CLOSED_CHANNEL_EXCEPTION);
            }
        }
    }

    private int doWriteMultiple(ChannelOutboundBuffer channelOutboundBuffer) {
        long maxBytesPerGatheringWrite = config().getMaxBytesPerGatheringWrite();
        if (PlatformDependent.hasUnsafe()) {
            IovArray iovArrayCleanArray = ((EpollEventLoop) eventLoop()).cleanArray();
            iovArrayCleanArray.maxBytes(maxBytesPerGatheringWrite);
            channelOutboundBuffer.forEachFlushedMessage(iovArrayCleanArray);
            if (iovArrayCleanArray.count() >= 1) {
                return writeBytesMultiple(channelOutboundBuffer, iovArrayCleanArray);
            }
        } else {
            ByteBuffer[] byteBufferArrNioBuffers = channelOutboundBuffer.nioBuffers();
            int iNioBufferCount = channelOutboundBuffer.nioBufferCount();
            if (iNioBufferCount >= 1) {
                return writeBytesMultiple(channelOutboundBuffer, byteBufferArrNioBuffers, iNioBufferCount, channelOutboundBuffer.nioBufferSize(), maxBytesPerGatheringWrite);
            }
        }
        channelOutboundBuffer.removeBytes(0L);
        return 0;
    }

    private void failSpliceIfClosed(ChannelPromise channelPromise) {
        if (isOpen() || !channelPromise.tryFailure(FAIL_SPLICE_IF_CLOSED_CLOSED_CHANNEL_EXCEPTION)) {
            return;
        }
        eventLoop().execute(new Runnable() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.2
            @Override // java.lang.Runnable
            public void run() {
                AbstractEpollStreamChannel.this.clearSpliceQueue();
            }
        });
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void safeClosePipe(FileDescriptor fileDescriptor) {
        if (fileDescriptor != null) {
            try {
                fileDescriptor.close();
            } catch (IOException e2) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Error while closing a pipe", (Throwable) e2);
                }
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void shutdownDone(ChannelFuture channelFuture, ChannelFuture channelFuture2, ChannelPromise channelPromise) {
        Throwable thCause = channelFuture.cause();
        Throwable thCause2 = channelFuture2.cause();
        if (thCause != null) {
            if (thCause2 != null) {
                logger.debug("Exception suppressed because a previous exception occurred.", thCause2);
            }
            channelPromise.setFailure(thCause);
        } else if (thCause2 != null) {
            channelPromise.setFailure(thCause2);
        } else {
            channelPromise.setSuccess();
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void shutdownInput0(ChannelPromise channelPromise) {
        try {
            this.socket.shutdown(true, false);
            channelPromise.setSuccess();
        } catch (Throwable th) {
            channelPromise.setFailure(th);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void shutdownOutputDone(final ChannelFuture channelFuture, final ChannelPromise channelPromise) {
        ChannelFuture channelFutureShutdownInput = shutdownInput();
        if (channelFutureShutdownInput.isDone()) {
            shutdownDone(channelFuture, channelFutureShutdownInput, channelPromise);
        } else {
            channelFutureShutdownInput.addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelFutureListener() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.7
                @Override // io.netty.util.concurrent.GenericFutureListener
                public void operationComplete(ChannelFuture channelFuture2) {
                    AbstractEpollStreamChannel.shutdownDone(channelFuture, channelFuture2, channelPromise);
                }
            });
        }
    }

    private int writeBytes(ChannelOutboundBuffer channelOutboundBuffer, ByteBuf byteBuf) {
        int i2 = byteBuf.readableBytes();
        if (i2 == 0) {
            channelOutboundBuffer.remove();
            return 0;
        }
        if (byteBuf.hasMemoryAddress() || byteBuf.nioBufferCount() == 1) {
            return doWriteBytes(channelOutboundBuffer, byteBuf);
        }
        ByteBuffer[] byteBufferArrNioBuffers = byteBuf.nioBuffers();
        return writeBytesMultiple(channelOutboundBuffer, byteBufferArrNioBuffers, byteBufferArrNioBuffers.length, i2, config().getMaxBytesPerGatheringWrite());
    }

    private int writeBytesMultiple(ChannelOutboundBuffer channelOutboundBuffer, IovArray iovArray) {
        long size = iovArray.size();
        long jWritevAddresses = this.socket.writevAddresses(iovArray.memoryAddress(0), iovArray.count());
        if (jWritevAddresses <= 0) {
            return Integer.MAX_VALUE;
        }
        adjustMaxBytesPerGatheringWrite(size, jWritevAddresses, iovArray.maxBytes());
        channelOutboundBuffer.removeBytes(jWritevAddresses);
        return 1;
    }

    private int writeBytesMultiple(ChannelOutboundBuffer channelOutboundBuffer, ByteBuffer[] byteBufferArr, int i2, long j2, long j3) {
        if (j2 > j3) {
            j2 = j3;
        }
        long jWritev = this.socket.writev(byteBufferArr, 0, i2, j2);
        if (jWritev <= 0) {
            return Integer.MAX_VALUE;
        }
        adjustMaxBytesPerGatheringWrite(j2, jWritev, j3);
        channelOutboundBuffer.removeBytes(jWritev);
        return 1;
    }

    private int writeDefaultFileRegion(ChannelOutboundBuffer channelOutboundBuffer, DefaultFileRegion defaultFileRegion) {
        long jCount = defaultFileRegion.count();
        if (defaultFileRegion.transferred() >= jCount) {
            channelOutboundBuffer.remove();
            return 0;
        }
        long jTransferred = defaultFileRegion.transferred();
        long jSendFile = this.socket.sendFile(defaultFileRegion, defaultFileRegion.position(), jTransferred, jCount - jTransferred);
        if (jSendFile <= 0) {
            return Integer.MAX_VALUE;
        }
        channelOutboundBuffer.progress(jSendFile);
        if (defaultFileRegion.transferred() < jCount) {
            return 1;
        }
        channelOutboundBuffer.remove();
        return 1;
    }

    private int writeFileRegion(ChannelOutboundBuffer channelOutboundBuffer, FileRegion fileRegion) {
        if (fileRegion.transferred() >= fileRegion.count()) {
            channelOutboundBuffer.remove();
            return 0;
        }
        if (this.byteChannel == null) {
            this.byteChannel = new EpollSocketWritableByteChannel();
        }
        long jTransferTo = fileRegion.transferTo(this.byteChannel, fileRegion.transferred());
        if (jTransferTo <= 0) {
            return Integer.MAX_VALUE;
        }
        channelOutboundBuffer.progress(jTransferTo);
        if (fileRegion.transferred() < fileRegion.count()) {
            return 1;
        }
        channelOutboundBuffer.remove();
        return 1;
    }

    @Override // io.netty.channel.epoll.AbstractEpollChannel, io.netty.channel.AbstractChannel
    public void doClose() {
        try {
            super.doClose();
        } finally {
            safeClosePipe(this.pipeIn);
            safeClosePipe(this.pipeOut);
            clearSpliceQueue();
        }
    }

    @Override // io.netty.channel.AbstractChannel
    public final void doShutdownOutput() {
        this.socket.shutdown(false, true);
    }

    @Override // io.netty.channel.AbstractChannel
    public void doWrite(ChannelOutboundBuffer channelOutboundBuffer) {
        int iDoWriteSingle;
        int writeSpinCount = config().getWriteSpinCount();
        do {
            int size = channelOutboundBuffer.size();
            if (size > 1 && (channelOutboundBuffer.current() instanceof ByteBuf)) {
                iDoWriteSingle = doWriteMultiple(channelOutboundBuffer);
            } else {
                if (size == 0) {
                    clearFlag(Native.EPOLLOUT);
                    return;
                }
                iDoWriteSingle = doWriteSingle(channelOutboundBuffer);
            }
            writeSpinCount -= iDoWriteSingle;
        } while (writeSpinCount > 0);
        int i2 = Native.EPOLLOUT;
        if (writeSpinCount != 0) {
            setFlag(i2);
        } else {
            clearFlag(i2);
            eventLoop().execute(this.flushTask);
        }
    }

    public int doWriteSingle(ChannelOutboundBuffer channelOutboundBuffer) {
        Object objCurrent = channelOutboundBuffer.current();
        if (objCurrent instanceof ByteBuf) {
            return writeBytes(channelOutboundBuffer, (ByteBuf) objCurrent);
        }
        if (objCurrent instanceof DefaultFileRegion) {
            return writeDefaultFileRegion(channelOutboundBuffer, (DefaultFileRegion) objCurrent);
        }
        if (objCurrent instanceof FileRegion) {
            return writeFileRegion(channelOutboundBuffer, (FileRegion) objCurrent);
        }
        if (!(objCurrent instanceof SpliceOutTask)) {
            throw new Error();
        }
        if (!((SpliceOutTask) objCurrent).spliceOut()) {
            return Integer.MAX_VALUE;
        }
        channelOutboundBuffer.remove();
        return 1;
    }

    @Override // io.netty.channel.AbstractChannel
    public Object filterOutboundMessage(Object obj) {
        if (obj instanceof ByteBuf) {
            ByteBuf byteBuf = (ByteBuf) obj;
            return UnixChannelUtil.isBufferCopyNeededForWrite(byteBuf) ? newDirectBuffer(byteBuf) : byteBuf;
        }
        if ((obj instanceof FileRegion) || (obj instanceof SpliceOutTask)) {
            return obj;
        }
        StringBuilder sbF = a.F("unsupported message type: ");
        sbF.append(StringUtil.simpleClassName(obj));
        sbF.append(EXPECTED_TYPES);
        throw new UnsupportedOperationException(sbF.toString());
    }

    @Override // io.netty.channel.epoll.AbstractEpollChannel, io.netty.channel.Channel
    public /* bridge */ /* synthetic */ boolean isActive() {
        return super.isActive();
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public boolean isInputShutdown() {
        return this.socket.isInputShutdown();
    }

    @Override // io.netty.channel.epoll.AbstractEpollChannel, io.netty.channel.Channel
    public /* bridge */ /* synthetic */ boolean isOpen() {
        return super.isOpen();
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public boolean isOutputShutdown() {
        return this.socket.isOutputShutdown();
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public boolean isShutdown() {
        return this.socket.isShutdown();
    }

    @Override // io.netty.channel.epoll.AbstractEpollChannel, io.netty.channel.Channel
    public ChannelMetadata metadata() {
        return METADATA;
    }

    @Override // io.netty.channel.epoll.AbstractEpollChannel, io.netty.channel.AbstractChannel
    public AbstractEpollChannel.AbstractEpollUnsafe newUnsafe() {
        return new EpollStreamUnsafe();
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public ChannelFuture shutdown() {
        return shutdown(newPromise());
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public ChannelFuture shutdown(final ChannelPromise channelPromise) {
        ChannelFuture channelFutureShutdownOutput = shutdownOutput();
        if (channelFutureShutdownOutput.isDone()) {
            shutdownOutputDone(channelFutureShutdownOutput, channelPromise);
        } else {
            channelFutureShutdownOutput.addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelFutureListener() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.6
                @Override // io.netty.util.concurrent.GenericFutureListener
                public void operationComplete(ChannelFuture channelFuture) {
                    AbstractEpollStreamChannel.this.shutdownOutputDone(channelFuture, channelPromise);
                }
            });
        }
        return channelPromise;
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public ChannelFuture shutdownInput() {
        return shutdownInput(newPromise());
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public ChannelFuture shutdownInput(final ChannelPromise channelPromise) {
        Executor executorPrepareToClose = ((EpollStreamUnsafe) unsafe()).prepareToClose();
        if (executorPrepareToClose != null) {
            executorPrepareToClose.execute(new Runnable() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.4
                @Override // java.lang.Runnable
                public void run() {
                    AbstractEpollStreamChannel.this.shutdownInput0(channelPromise);
                }
            });
        } else {
            EventLoop eventLoop = eventLoop();
            if (eventLoop.inEventLoop()) {
                shutdownInput0(channelPromise);
            } else {
                eventLoop.execute(new Runnable() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.5
                    @Override // java.lang.Runnable
                    public void run() {
                        AbstractEpollStreamChannel.this.shutdownInput0(channelPromise);
                    }
                });
            }
        }
        return channelPromise;
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public ChannelFuture shutdownOutput() {
        return shutdownOutput(newPromise());
    }

    @Override // io.netty.channel.socket.DuplexChannel
    public ChannelFuture shutdownOutput(final ChannelPromise channelPromise) {
        EventLoop eventLoop = eventLoop();
        if (eventLoop.inEventLoop()) {
            ((AbstractChannel.AbstractUnsafe) unsafe()).shutdownOutput(channelPromise);
        } else {
            eventLoop.execute(new Runnable() { // from class: io.netty.channel.epoll.AbstractEpollStreamChannel.3
                @Override // java.lang.Runnable
                public void run() {
                    ((AbstractChannel.AbstractUnsafe) AbstractEpollStreamChannel.this.unsafe()).shutdownOutput(channelPromise);
                }
            });
        }
        return channelPromise;
    }

    public final ChannelFuture spliceTo(AbstractEpollStreamChannel abstractEpollStreamChannel, int i2) {
        return spliceTo(abstractEpollStreamChannel, i2, newPromise());
    }

    public final ChannelFuture spliceTo(AbstractEpollStreamChannel abstractEpollStreamChannel, int i2, ChannelPromise channelPromise) {
        if (abstractEpollStreamChannel.eventLoop() != eventLoop()) {
            throw new IllegalArgumentException("EventLoops are not the same.");
        }
        if (i2 < 0) {
            throw new IllegalArgumentException(a.n("len: ", i2, " (expected: >= 0)"));
        }
        EpollMode epollMode = abstractEpollStreamChannel.config().getEpollMode();
        EpollMode epollMode2 = EpollMode.LEVEL_TRIGGERED;
        if (epollMode != epollMode2 || config().getEpollMode() != epollMode2) {
            throw new IllegalStateException("spliceTo() supported only when using " + epollMode2);
        }
        ObjectUtil.checkNotNull(channelPromise, "promise");
        if (isOpen()) {
            addToSpliceQueue(new SpliceInChannelTask(abstractEpollStreamChannel, i2, channelPromise));
            failSpliceIfClosed(channelPromise);
        } else {
            channelPromise.tryFailure(SPLICE_TO_CLOSED_CHANNEL_EXCEPTION);
        }
        return channelPromise;
    }

    public final ChannelFuture spliceTo(FileDescriptor fileDescriptor, int i2, int i3) {
        return spliceTo(fileDescriptor, i2, i3, newPromise());
    }

    public final ChannelFuture spliceTo(FileDescriptor fileDescriptor, int i2, int i3, ChannelPromise channelPromise) {
        if (i3 < 0) {
            throw new IllegalArgumentException(a.n("len: ", i3, " (expected: >= 0)"));
        }
        if (i2 < 0) {
            throw new IllegalArgumentException(a.l("offset must be >= 0 but was ", i2));
        }
        EpollMode epollMode = config().getEpollMode();
        EpollMode epollMode2 = EpollMode.LEVEL_TRIGGERED;
        if (epollMode != epollMode2) {
            throw new IllegalStateException("spliceTo() supported only when using " + epollMode2);
        }
        ObjectUtil.checkNotNull(channelPromise, "promise");
        if (isOpen()) {
            addToSpliceQueue(new SpliceFdTask(fileDescriptor, i2, i3, channelPromise));
            failSpliceIfClosed(channelPromise);
        } else {
            channelPromise.tryFailure(SPLICE_TO_CLOSED_CHANNEL_EXCEPTION);
        }
        return channelPromise;
    }
}
