package io.netty.channel.nio;

import g.a.a.a.a;
import io.netty.channel.ChannelException;
import io.netty.channel.EventLoopException;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SelectStrategy;
import io.netty.channel.SingleThreadEventLoop;
import io.netty.channel.nio.AbstractNioChannel;
import io.netty.util.IntSupplier;
import io.netty.util.concurrent.RejectedExecutionHandler;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.ReflectionUtil;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.spi.AbstractSelector;
import java.nio.channels.spi.SelectorProvider;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;

/* JADX INFO: loaded from: classes.dex */
public final class NioEventLoop extends SingleThreadEventLoop {
    private static final int CLEANUP_INTERVAL = 256;
    private static final int MIN_PREMATURE_SELECTOR_RETURNS = 3;
    private static final int SELECTOR_AUTO_REBUILD_THRESHOLD;
    private int cancelledKeys;
    private volatile int ioRatio;
    private boolean needsToSelectAgain;
    private final Callable<Integer> pendingTasksCallable;
    private final SelectorProvider provider;
    private final IntSupplier selectNowSupplier;
    private final SelectStrategy selectStrategy;
    private SelectedSelectionKeySet selectedKeys;
    private Selector selector;
    private Selector unwrappedSelector;
    private final AtomicBoolean wakenUp;
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) NioEventLoop.class);
    private static final boolean DISABLE_KEYSET_OPTIMIZATION = SystemPropertyUtil.getBoolean("io.netty.noKeySetOptimization", false);

    public static final class SelectorTuple {
        public final Selector selector;
        public final Selector unwrappedSelector;

        public SelectorTuple(Selector selector) {
            this.unwrappedSelector = selector;
            this.selector = selector;
        }

        public SelectorTuple(Selector selector, Selector selector2) {
            this.unwrappedSelector = selector;
            this.selector = selector2;
        }
    }

    static {
        if (SystemPropertyUtil.get("sun.nio.ch.bugLevel") == null) {
            try {
                AccessController.doPrivileged(new PrivilegedAction<Void>() { // from class: io.netty.channel.nio.NioEventLoop.3
                    @Override // java.security.PrivilegedAction
                    public Void run() {
                        System.setProperty("sun.nio.ch.bugLevel", "");
                        return null;
                    }
                });
            } catch (SecurityException e2) {
                logger.debug("Unable to get/set System Property: sun.nio.ch.bugLevel", (Throwable) e2);
            }
        }
        int i2 = SystemPropertyUtil.getInt("io.netty.selectorAutoRebuildThreshold", 512);
        int i3 = i2 >= 3 ? i2 : 0;
        SELECTOR_AUTO_REBUILD_THRESHOLD = i3;
        InternalLogger internalLogger = logger;
        if (internalLogger.isDebugEnabled()) {
            internalLogger.debug("-Dio.netty.noKeySetOptimization: {}", Boolean.valueOf(DISABLE_KEYSET_OPTIMIZATION));
            internalLogger.debug("-Dio.netty.selectorAutoRebuildThreshold: {}", Integer.valueOf(i3));
        }
    }

    public NioEventLoop(NioEventLoopGroup nioEventLoopGroup, Executor executor, SelectorProvider selectorProvider, SelectStrategy selectStrategy, RejectedExecutionHandler rejectedExecutionHandler) {
        super((EventLoopGroup) nioEventLoopGroup, executor, false, SingleThreadEventLoop.DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);
        this.selectNowSupplier = new IntSupplier() { // from class: io.netty.channel.nio.NioEventLoop.1
            @Override // io.netty.util.IntSupplier
            public int get() {
                return NioEventLoop.this.selectNow();
            }
        };
        this.pendingTasksCallable = new Callable<Integer>() { // from class: io.netty.channel.nio.NioEventLoop.2
            /* JADX WARN: Can't rename method to resolve collision */
            @Override // java.util.concurrent.Callable
            public Integer call() {
                return Integer.valueOf(NioEventLoop.super.pendingTasks());
            }
        };
        this.wakenUp = new AtomicBoolean();
        this.ioRatio = 50;
        Objects.requireNonNull(selectorProvider, "selectorProvider");
        Objects.requireNonNull(selectStrategy, "selectStrategy");
        this.provider = selectorProvider;
        SelectorTuple selectorTupleOpenSelector = openSelector();
        this.selector = selectorTupleOpenSelector.selector;
        this.unwrappedSelector = selectorTupleOpenSelector.unwrappedSelector;
        this.selectStrategy = selectStrategy;
    }

    private void closeAll() {
        selectAgain();
        Set<SelectionKey> setKeys = this.selector.keys();
        ArrayList<AbstractNioChannel> arrayList = new ArrayList(setKeys.size());
        for (SelectionKey selectionKey : setKeys) {
            Object objAttachment = selectionKey.attachment();
            if (objAttachment instanceof AbstractNioChannel) {
                arrayList.add((AbstractNioChannel) objAttachment);
            } else {
                selectionKey.cancel();
                invokeChannelUnregistered((NioTask) objAttachment, selectionKey, null);
            }
        }
        for (AbstractNioChannel abstractNioChannel : arrayList) {
            abstractNioChannel.unsafe().close(abstractNioChannel.unsafe().voidPromise());
        }
    }

    private static void handleLoopException(Throwable th) {
        logger.warn("Unexpected exception in the selector loop.", th);
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException unused) {
        }
    }

    private static void invokeChannelUnregistered(NioTask<SelectableChannel> nioTask, SelectionKey selectionKey, Throwable th) {
        try {
            nioTask.channelUnregistered(selectionKey.channel(), th);
        } catch (Exception e2) {
            logger.warn("Unexpected exception while running NioTask.channelUnregistered()", (Throwable) e2);
        }
    }

    private SelectorTuple openSelector() {
        try {
            final AbstractSelector abstractSelectorOpenSelector = this.provider.openSelector();
            if (DISABLE_KEYSET_OPTIMIZATION) {
                return new SelectorTuple(abstractSelectorOpenSelector);
            }
            final SelectedSelectionKeySet selectedSelectionKeySet = new SelectedSelectionKeySet();
            Object objDoPrivileged = AccessController.doPrivileged(new PrivilegedAction<Object>() { // from class: io.netty.channel.nio.NioEventLoop.4
                @Override // java.security.PrivilegedAction
                public Object run() {
                    try {
                        return Class.forName("sun.nio.ch.SelectorImpl", false, PlatformDependent.getSystemClassLoader());
                    } catch (Throwable th) {
                        return th;
                    }
                }
            });
            if (objDoPrivileged instanceof Class) {
                final Class cls = (Class) objDoPrivileged;
                if (cls.isAssignableFrom(abstractSelectorOpenSelector.getClass())) {
                    Object objDoPrivileged2 = AccessController.doPrivileged(new PrivilegedAction<Object>() { // from class: io.netty.channel.nio.NioEventLoop.5
                        @Override // java.security.PrivilegedAction
                        public Object run() {
                            try {
                                Field declaredField = cls.getDeclaredField("selectedKeys");
                                Field declaredField2 = cls.getDeclaredField("publicSelectedKeys");
                                Throwable thTrySetAccessible = ReflectionUtil.trySetAccessible(declaredField, true);
                                if (thTrySetAccessible != null) {
                                    return thTrySetAccessible;
                                }
                                Throwable thTrySetAccessible2 = ReflectionUtil.trySetAccessible(declaredField2, true);
                                if (thTrySetAccessible2 != null) {
                                    return thTrySetAccessible2;
                                }
                                declaredField.set(abstractSelectorOpenSelector, selectedSelectionKeySet);
                                declaredField2.set(abstractSelectorOpenSelector, selectedSelectionKeySet);
                                return null;
                            } catch (IllegalAccessException e2) {
                                return e2;
                            } catch (NoSuchFieldException e3) {
                                return e3;
                            }
                        }
                    });
                    if (!(objDoPrivileged2 instanceof Exception)) {
                        this.selectedKeys = selectedSelectionKeySet;
                        logger.trace("instrumented a special java.util.Set into: {}", abstractSelectorOpenSelector);
                        return new SelectorTuple(abstractSelectorOpenSelector, new SelectedSelectionKeySetSelector(abstractSelectorOpenSelector, selectedSelectionKeySet));
                    }
                    this.selectedKeys = null;
                    logger.trace("failed to instrument a special java.util.Set into: {}", abstractSelectorOpenSelector, (Exception) objDoPrivileged2);
                    return new SelectorTuple(abstractSelectorOpenSelector);
                }
            }
            if (objDoPrivileged instanceof Throwable) {
                logger.trace("failed to instrument a special java.util.Set into: {}", abstractSelectorOpenSelector, (Throwable) objDoPrivileged);
            }
            return new SelectorTuple(abstractSelectorOpenSelector);
        } catch (IOException e2) {
            throw new ChannelException("failed to open a new selector", e2);
        }
    }

    private void processSelectedKey(SelectionKey selectionKey, AbstractNioChannel abstractNioChannel) {
        AbstractNioChannel.NioUnsafe nioUnsafeUnsafe = abstractNioChannel.unsafe();
        if (!selectionKey.isValid()) {
            try {
                NioEventLoop nioEventLoopEventLoop = abstractNioChannel.eventLoop();
                if (nioEventLoopEventLoop != this || nioEventLoopEventLoop == null) {
                    return;
                }
                nioUnsafeUnsafe.close(nioUnsafeUnsafe.voidPromise());
                return;
            } catch (Throwable unused) {
                return;
            }
        }
        try {
            int i2 = selectionKey.readyOps();
            if ((i2 & 8) != 0) {
                selectionKey.interestOps(selectionKey.interestOps() & (-9));
                nioUnsafeUnsafe.finishConnect();
            }
            if ((i2 & 4) != 0) {
                abstractNioChannel.unsafe().forceFlush();
            }
            if ((i2 & 17) != 0 || i2 == 0) {
                nioUnsafeUnsafe.read();
            }
        } catch (CancelledKeyException unused2) {
            nioUnsafeUnsafe.close(nioUnsafeUnsafe.voidPromise());
        }
    }

    private static void processSelectedKey(SelectionKey selectionKey, NioTask<SelectableChannel> nioTask) {
        try {
            try {
                nioTask.channelReady(selectionKey.channel(), selectionKey);
                if (!selectionKey.isValid()) {
                    invokeChannelUnregistered(nioTask, selectionKey, null);
                }
            } catch (Exception e2) {
                selectionKey.cancel();
                invokeChannelUnregistered(nioTask, selectionKey, e2);
            }
        } catch (Throwable th) {
            selectionKey.cancel();
            invokeChannelUnregistered(nioTask, selectionKey, null);
            throw th;
        }
    }

    private void processSelectedKeys() {
        if (this.selectedKeys != null) {
            processSelectedKeysOptimized();
        } else {
            processSelectedKeysPlain(this.selector.selectedKeys());
        }
    }

    private void processSelectedKeysOptimized() {
        int i2 = 0;
        while (true) {
            SelectedSelectionKeySet selectedSelectionKeySet = this.selectedKeys;
            if (i2 >= selectedSelectionKeySet.size) {
                return;
            }
            SelectionKey[] selectionKeyArr = selectedSelectionKeySet.keys;
            SelectionKey selectionKey = selectionKeyArr[i2];
            selectionKeyArr[i2] = null;
            Object objAttachment = selectionKey.attachment();
            if (objAttachment instanceof AbstractNioChannel) {
                processSelectedKey(selectionKey, (AbstractNioChannel) objAttachment);
            } else {
                processSelectedKey(selectionKey, (NioTask<SelectableChannel>) objAttachment);
            }
            if (this.needsToSelectAgain) {
                this.selectedKeys.reset(i2 + 1);
                selectAgain();
                i2 = -1;
            }
            i2++;
        }
    }

    private void processSelectedKeysPlain(Set<SelectionKey> set) {
        if (set.isEmpty()) {
            return;
        }
        do {
            Iterator<SelectionKey> it = set.iterator();
            do {
                SelectionKey next = it.next();
                Object objAttachment = next.attachment();
                it.remove();
                if (objAttachment instanceof AbstractNioChannel) {
                    processSelectedKey(next, (AbstractNioChannel) objAttachment);
                } else {
                    processSelectedKey(next, (NioTask<SelectableChannel>) objAttachment);
                }
                if (!it.hasNext()) {
                    return;
                }
            } while (!this.needsToSelectAgain);
            selectAgain();
            set = this.selector.selectedKeys();
        } while (!set.isEmpty());
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void rebuildSelector0() {
        Selector selector = this.selector;
        if (selector == null) {
            return;
        }
        try {
            SelectorTuple selectorTupleOpenSelector = openSelector();
            int i2 = 0;
            for (SelectionKey selectionKey : selector.keys()) {
                Object objAttachment = selectionKey.attachment();
                try {
                    if (selectionKey.isValid() && selectionKey.channel().keyFor(selectorTupleOpenSelector.unwrappedSelector) == null) {
                        int iInterestOps = selectionKey.interestOps();
                        selectionKey.cancel();
                        SelectionKey selectionKeyRegister = selectionKey.channel().register(selectorTupleOpenSelector.unwrappedSelector, iInterestOps, objAttachment);
                        if (objAttachment instanceof AbstractNioChannel) {
                            ((AbstractNioChannel) objAttachment).selectionKey = selectionKeyRegister;
                        }
                        i2++;
                    }
                } catch (Exception e2) {
                    logger.warn("Failed to re-register a Channel to the new Selector.", (Throwable) e2);
                    if (objAttachment instanceof AbstractNioChannel) {
                        AbstractNioChannel abstractNioChannel = (AbstractNioChannel) objAttachment;
                        abstractNioChannel.unsafe().close(abstractNioChannel.unsafe().voidPromise());
                    } else {
                        invokeChannelUnregistered((NioTask) objAttachment, selectionKey, e2);
                    }
                }
            }
            this.selector = selectorTupleOpenSelector.selector;
            this.unwrappedSelector = selectorTupleOpenSelector.unwrappedSelector;
            try {
                selector.close();
            } catch (Throwable th) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Failed to close the old Selector.", th);
                }
            }
            logger.info("Migrated " + i2 + " channel(s) to the new Selector.");
        } catch (Exception e3) {
            logger.warn("Failed to create a new Selector.", (Throwable) e3);
        }
    }

    /* JADX WARN: Code restructure failed: missing block: B:6:0x001e, code lost:
    
        if (r6 == 0) goto L7;
     */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    private void select(boolean r14) throws java.io.IOException {
        /*
            Method dump skipped, instruction units count: 206
            To view this dump add '--comments-level debug' option
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.channel.nio.NioEventLoop.select(boolean):void");
    }

    private void selectAgain() {
        this.needsToSelectAgain = false;
        try {
            this.selector.selectNow();
        } catch (Throwable th) {
            logger.warn("Failed to update SelectionKeys.", th);
        }
    }

    public void cancel(SelectionKey selectionKey) {
        selectionKey.cancel();
        int i2 = this.cancelledKeys + 1;
        this.cancelledKeys = i2;
        if (i2 >= 256) {
            this.cancelledKeys = 0;
            this.needsToSelectAgain = true;
        }
    }

    @Override // io.netty.util.concurrent.SingleThreadEventExecutor
    public void cleanup() {
        try {
            this.selector.close();
        } catch (IOException e2) {
            logger.warn("Failed to close a selector.", (Throwable) e2);
        }
    }

    public int getIoRatio() {
        return this.ioRatio;
    }

    @Override // io.netty.util.concurrent.SingleThreadEventExecutor
    public Queue<Runnable> newTaskQueue(int i2) {
        return i2 == Integer.MAX_VALUE ? PlatformDependent.newMpscQueue() : PlatformDependent.newMpscQueue(i2);
    }

    @Override // io.netty.channel.SingleThreadEventLoop, io.netty.util.concurrent.SingleThreadEventExecutor
    public int pendingTasks() {
        return inEventLoop() ? super.pendingTasks() : ((Integer) submit((Callable) this.pendingTasksCallable).syncUninterruptibly().getNow()).intValue();
    }

    @Override // io.netty.util.concurrent.SingleThreadEventExecutor
    public Runnable pollTask() {
        Runnable runnablePollTask = super.pollTask();
        if (this.needsToSelectAgain) {
            selectAgain();
        }
        return runnablePollTask;
    }

    public void rebuildSelector() {
        if (inEventLoop()) {
            rebuildSelector0();
        } else {
            execute(new Runnable() { // from class: io.netty.channel.nio.NioEventLoop.6
                @Override // java.lang.Runnable
                public void run() {
                    NioEventLoop.this.rebuildSelector0();
                }
            });
        }
    }

    public void register(SelectableChannel selectableChannel, int i2, NioTask<?> nioTask) {
        Objects.requireNonNull(selectableChannel, "ch");
        if (i2 == 0) {
            throw new IllegalArgumentException("interestOps must be non-zero.");
        }
        if (((~selectableChannel.validOps()) & i2) != 0) {
            StringBuilder sbG = a.G("invalid interestOps: ", i2, "(validOps: ");
            sbG.append(selectableChannel.validOps());
            sbG.append(')');
            throw new IllegalArgumentException(sbG.toString());
        }
        Objects.requireNonNull(nioTask, "task");
        if (isShutdown()) {
            throw new IllegalStateException("event loop shut down");
        }
        try {
            selectableChannel.register(this.selector, i2, nioTask);
        } catch (Exception e2) {
            throw new EventLoopException("failed to register a channel", e2);
        }
    }

    /* JADX WARN: Can't wrap try/catch for region: R(8:35|2|(2:45|44)(6:40|4|(1:6)(2:7|(1:9))|10|11|(3:38|13|14)(4:18|33|19|20))|36|26|43|(3:41|28|(2:42|30)(1:47))(1:46)|44) */
    /* JADX WARN: Code restructure failed: missing block: B:31:0x007a, code lost:
    
        r0 = move-exception;
     */
    /* JADX WARN: Code restructure failed: missing block: B:32:0x007b, code lost:
    
        handleLoopException(r0);
     */
    @Override // io.netty.util.concurrent.SingleThreadEventExecutor
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    public void run() {
        /*
            r6 = this;
        L0:
            io.netty.channel.SelectStrategy r0 = r6.selectStrategy     // Catch: java.lang.Throwable -> L66
            io.netty.util.IntSupplier r1 = r6.selectNowSupplier     // Catch: java.lang.Throwable -> L66
            boolean r2 = r6.hasTasks()     // Catch: java.lang.Throwable -> L66
            int r0 = r0.calculateStrategy(r1, r2)     // Catch: java.lang.Throwable -> L66
            r1 = -2
            if (r0 == r1) goto L0
            r1 = -1
            r2 = 0
            if (r0 == r1) goto L14
            goto L2a
        L14:
            java.util.concurrent.atomic.AtomicBoolean r0 = r6.wakenUp     // Catch: java.lang.Throwable -> L66
            boolean r0 = r0.getAndSet(r2)     // Catch: java.lang.Throwable -> L66
            r6.select(r0)     // Catch: java.lang.Throwable -> L66
            java.util.concurrent.atomic.AtomicBoolean r0 = r6.wakenUp     // Catch: java.lang.Throwable -> L66
            boolean r0 = r0.get()     // Catch: java.lang.Throwable -> L66
            if (r0 == 0) goto L2a
            java.nio.channels.Selector r0 = r6.selector     // Catch: java.lang.Throwable -> L66
            r0.wakeup()     // Catch: java.lang.Throwable -> L66
        L2a:
            r6.cancelledKeys = r2     // Catch: java.lang.Throwable -> L66
            r6.needsToSelectAgain = r2     // Catch: java.lang.Throwable -> L66
            int r0 = r6.ioRatio     // Catch: java.lang.Throwable -> L66
            r1 = 100
            if (r0 != r1) goto L40
            r6.processSelectedKeys()     // Catch: java.lang.Throwable -> L3b
            r6.runAllTasks()     // Catch: java.lang.Throwable -> L66
            goto L6a
        L3b:
            r0 = move-exception
            r6.runAllTasks()     // Catch: java.lang.Throwable -> L66
            throw r0     // Catch: java.lang.Throwable -> L66
        L40:
            long r1 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L66
            r6.processSelectedKeys()     // Catch: java.lang.Throwable -> L56
            long r3 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L66
            long r3 = r3 - r1
            int r1 = 100 - r0
            long r1 = (long) r1     // Catch: java.lang.Throwable -> L66
            long r3 = r3 * r1
            long r0 = (long) r0     // Catch: java.lang.Throwable -> L66
            long r3 = r3 / r0
            r6.runAllTasks(r3)     // Catch: java.lang.Throwable -> L66
            goto L6a
        L56:
            r3 = move-exception
            long r4 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L66
            long r4 = r4 - r1
            int r1 = 100 - r0
            long r1 = (long) r1     // Catch: java.lang.Throwable -> L66
            long r4 = r4 * r1
            long r0 = (long) r0     // Catch: java.lang.Throwable -> L66
            long r4 = r4 / r0
            r6.runAllTasks(r4)     // Catch: java.lang.Throwable -> L66
            throw r3     // Catch: java.lang.Throwable -> L66
        L66:
            r0 = move-exception
            handleLoopException(r0)
        L6a:
            boolean r0 = r6.isShuttingDown()     // Catch: java.lang.Throwable -> L7a
            if (r0 == 0) goto L0
            r6.closeAll()     // Catch: java.lang.Throwable -> L7a
            boolean r0 = r6.confirmShutdown()     // Catch: java.lang.Throwable -> L7a
            if (r0 == 0) goto L0
            return
        L7a:
            r0 = move-exception
            handleLoopException(r0)
            goto L0
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.channel.nio.NioEventLoop.run():void");
    }

    public int selectNow() {
        try {
            return this.selector.selectNow();
        } finally {
            if (this.wakenUp.get()) {
                this.selector.wakeup();
            }
        }
    }

    public SelectorProvider selectorProvider() {
        return this.provider;
    }

    public void setIoRatio(int i2) {
        if (i2 <= 0 || i2 > 100) {
            throw new IllegalArgumentException(a.n("ioRatio: ", i2, " (expected: 0 < ioRatio <= 100)"));
        }
        this.ioRatio = i2;
    }

    public Selector unwrappedSelector() {
        return this.unwrappedSelector;
    }

    @Override // io.netty.util.concurrent.SingleThreadEventExecutor
    public void wakeup(boolean z2) {
        if (z2 || !this.wakenUp.compareAndSet(false, true)) {
            return;
        }
        this.selector.wakeup();
    }
}
