package io.netty.channel.epoll;

import g.a.a.a.a;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SelectStrategy;
import io.netty.channel.SingleThreadEventLoop;
import io.netty.channel.epoll.AbstractEpollChannel;
import io.netty.channel.unix.FileDescriptor;
import io.netty.channel.unix.IovArray;
import io.netty.util.IntSupplier;
import io.netty.util.collection.IntObjectHashMap;
import io.netty.util.collection.IntObjectMap;
import io.netty.util.concurrent.RejectedExecutionHandler;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/* JADX INFO: loaded from: classes.dex */
public final class EpollEventLoop extends SingleThreadEventLoop {
    public static final /* synthetic */ boolean $assertionsDisabled = false;
    private final boolean allowGrowing;
    private final IntObjectMap<AbstractEpollChannel> channels;
    private final FileDescriptor epollFd;
    private final FileDescriptor eventFd;
    private final EpollEventArray events;
    private volatile int ioRatio;
    private final IovArray iovArray;
    private final Callable<Integer> pendingTasksCallable;
    private final IntSupplier selectNowSupplier;
    private final SelectStrategy selectStrategy;
    private final FileDescriptor timerFd;
    private volatile int wakenUp;
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) EpollEventLoop.class);
    private static final AtomicIntegerFieldUpdater<EpollEventLoop> WAKEN_UP_UPDATER = AtomicIntegerFieldUpdater.newUpdater(EpollEventLoop.class, "wakenUp");

    static {
        Epoll.ensureAvailability();
    }

    public EpollEventLoop(EventLoopGroup eventLoopGroup, Executor executor, int i2, SelectStrategy selectStrategy, RejectedExecutionHandler rejectedExecutionHandler) throws Throwable {
        EpollEventArray epollEventArray;
        FileDescriptor fileDescriptor;
        FileDescriptor fileDescriptorNewEventFd;
        FileDescriptor fileDescriptorNewEpollCreate;
        super(eventLoopGroup, executor, false, SingleThreadEventLoop.DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);
        this.channels = new IntObjectHashMap(4096);
        this.iovArray = new IovArray();
        this.selectNowSupplier = new IntSupplier() { // from class: io.netty.channel.epoll.EpollEventLoop.1
            @Override // io.netty.util.IntSupplier
            public int get() {
                return EpollEventLoop.this.epollWaitNow();
            }
        };
        this.pendingTasksCallable = new Callable<Integer>() { // from class: io.netty.channel.epoll.EpollEventLoop.2
            /* JADX WARN: Can't rename method to resolve collision */
            @Override // java.util.concurrent.Callable
            public Integer call() {
                return Integer.valueOf(EpollEventLoop.super.pendingTasks());
            }
        };
        this.ioRatio = 50;
        this.selectStrategy = (SelectStrategy) ObjectUtil.checkNotNull(selectStrategy, "strategy");
        if (i2 == 0) {
            this.allowGrowing = true;
            epollEventArray = new EpollEventArray(4096);
        } else {
            this.allowGrowing = false;
            epollEventArray = new EpollEventArray(i2);
        }
        this.events = epollEventArray;
        FileDescriptor fileDescriptorNewTimerFd = null;
        try {
            fileDescriptorNewEpollCreate = Native.newEpollCreate();
            try {
                this.epollFd = fileDescriptorNewEpollCreate;
                fileDescriptorNewEventFd = Native.newEventFd();
            } catch (Throwable th) {
                th = th;
                fileDescriptorNewEventFd = null;
                fileDescriptorNewTimerFd = fileDescriptorNewEpollCreate;
                fileDescriptor = null;
            }
        } catch (Throwable th2) {
            th = th2;
            fileDescriptor = null;
            fileDescriptorNewEventFd = null;
        }
        try {
            this.eventFd = fileDescriptorNewEventFd;
            try {
                int iIntValue = fileDescriptorNewEpollCreate.intValue();
                int iIntValue2 = fileDescriptorNewEventFd.intValue();
                int i3 = Native.EPOLLIN;
                Native.epollCtlAdd(iIntValue, iIntValue2, i3);
                fileDescriptorNewTimerFd = Native.newTimerFd();
                this.timerFd = fileDescriptorNewTimerFd;
                try {
                    Native.epollCtlAdd(fileDescriptorNewEpollCreate.intValue(), fileDescriptorNewTimerFd.intValue(), i3 | Native.EPOLLET);
                } catch (IOException e2) {
                    throw new IllegalStateException("Unable to add timerFd filedescriptor to epoll", e2);
                }
            } catch (IOException e3) {
                throw new IllegalStateException("Unable to add eventFd filedescriptor to epoll", e3);
            }
        } catch (Throwable th3) {
            th = th3;
            fileDescriptor = fileDescriptorNewTimerFd;
            fileDescriptorNewTimerFd = fileDescriptorNewEpollCreate;
            if (fileDescriptorNewTimerFd != null) {
                try {
                    fileDescriptorNewTimerFd.close();
                } catch (Exception unused) {
                }
            }
            if (fileDescriptorNewEventFd != null) {
                try {
                    fileDescriptorNewEventFd.close();
                } catch (Exception unused2) {
                }
            }
            if (fileDescriptor == null) {
                throw th;
            }
            try {
                fileDescriptor.close();
                throw th;
            } catch (Exception unused3) {
                throw th;
            }
        }
    }

    private void closeAll() {
        try {
            epollWaitNow();
        } catch (IOException unused) {
        }
        ArrayList<AbstractEpollChannel> arrayList = new ArrayList(this.channels.size());
        Iterator<AbstractEpollChannel> it = this.channels.values().iterator();
        while (it.hasNext()) {
            arrayList.add(it.next());
        }
        for (AbstractEpollChannel abstractEpollChannel : arrayList) {
            abstractEpollChannel.unsafe().close(abstractEpollChannel.unsafe().voidPromise());
        }
    }

    private int epollWait(boolean z2) {
        if (z2 && hasTasks()) {
            return epollWaitNow();
        }
        long jDelayNanos = delayNanos(System.nanoTime());
        int iMin = (int) Math.min(jDelayNanos / 1000000000, 2147483647L);
        return Native.epollWait(this.epollFd, this.events, this.timerFd, iMin, (int) Math.min(jDelayNanos - (((long) iMin) * 1000000000), 2147483647L));
    }

    /* JADX INFO: Access modifiers changed from: private */
    public int epollWaitNow() {
        return Native.epollWait(this.epollFd, this.events, this.timerFd, 0, 0);
    }

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

    private void processReady(EpollEventArray epollEventArray, int i2) {
        for (int i3 = 0; i3 < i2; i3++) {
            int iFd = epollEventArray.fd(i3);
            if (iFd == this.eventFd.intValue()) {
                Native.eventFdRead(iFd);
            } else if (iFd == this.timerFd.intValue()) {
                Native.timerFdRead(iFd);
            } else {
                long jEvents = epollEventArray.events(i3);
                AbstractEpollChannel abstractEpollChannel = this.channels.get(iFd);
                if (abstractEpollChannel != null) {
                    AbstractEpollChannel.AbstractEpollUnsafe abstractEpollUnsafe = (AbstractEpollChannel.AbstractEpollUnsafe) abstractEpollChannel.unsafe();
                    int i4 = Native.EPOLLERR;
                    if ((((long) (Native.EPOLLOUT | i4)) & jEvents) != 0) {
                        abstractEpollUnsafe.epollOutReady();
                    }
                    if ((((long) (i4 | Native.EPOLLIN)) & jEvents) != 0) {
                        abstractEpollUnsafe.epollInReady();
                    }
                    if ((jEvents & ((long) Native.EPOLLRDHUP)) != 0) {
                        abstractEpollUnsafe.epollRdHupReady();
                    }
                } else {
                    try {
                        Native.epollCtlDel(this.epollFd.intValue(), iFd);
                    } catch (IOException unused) {
                    }
                }
            }
        }
    }

    public void add(AbstractEpollChannel abstractEpollChannel) {
        int iIntValue = abstractEpollChannel.socket.intValue();
        Native.epollCtlAdd(this.epollFd.intValue(), iIntValue, abstractEpollChannel.flags);
        this.channels.put(iIntValue, abstractEpollChannel);
    }

    public IovArray cleanArray() {
        this.iovArray.clear();
        return this.iovArray;
    }

    @Override // io.netty.util.concurrent.SingleThreadEventExecutor
    public void cleanup() {
        try {
            try {
                this.epollFd.close();
            } catch (IOException e2) {
                logger.warn("Failed to close the epoll fd.", (Throwable) e2);
            }
            try {
                this.eventFd.close();
            } catch (IOException e3) {
                logger.warn("Failed to close the event fd.", (Throwable) e3);
            }
            try {
                this.timerFd.close();
            } catch (IOException e4) {
                logger.warn("Failed to close the timer fd.", (Throwable) e4);
            }
        } finally {
            this.iovArray.release();
            this.events.free();
        }
    }

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

    public void modify(AbstractEpollChannel abstractEpollChannel) {
        Native.epollCtlMod(this.epollFd.intValue(), abstractEpollChannel.socket.intValue(), abstractEpollChannel.flags);
    }

    @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();
    }

    public void remove(AbstractEpollChannel abstractEpollChannel) {
        if (abstractEpollChannel.isOpen()) {
            if (this.channels.remove(abstractEpollChannel.socket.intValue()) != null) {
                Native.epollCtlDel(this.epollFd.intValue(), abstractEpollChannel.fd().intValue());
            }
        }
    }

    /* JADX WARN: Can't wrap try/catch for region: R(8:48|2|(2:58|57)(8:53|4|(1:6)(4:7|(1:9)|10|(1:12))|13|14|(2:(2:51|17)|22)(3:23|(2:46|25)|30)|31|(1:35))|49|39|56|(3:54|41|(2:55|43)(1:60))(1:59)|57) */
    /* JADX WARN: Code restructure failed: missing block: B:44:0x0098, code lost:
    
        r0 = move-exception;
     */
    /* JADX WARN: Code restructure failed: missing block: B:45:0x0099, 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 -> L84
            io.netty.util.IntSupplier r1 = r6.selectNowSupplier     // Catch: java.lang.Throwable -> L84
            boolean r2 = r6.hasTasks()     // Catch: java.lang.Throwable -> L84
            int r0 = r0.calculateStrategy(r1, r2)     // Catch: java.lang.Throwable -> L84
            r1 = -2
            if (r0 == r1) goto L0
            r1 = -1
            if (r0 == r1) goto L13
            goto L31
        L13:
            java.util.concurrent.atomic.AtomicIntegerFieldUpdater<io.netty.channel.epoll.EpollEventLoop> r0 = io.netty.channel.epoll.EpollEventLoop.WAKEN_UP_UPDATER     // Catch: java.lang.Throwable -> L84
            r1 = 0
            int r0 = r0.getAndSet(r6, r1)     // Catch: java.lang.Throwable -> L84
            r2 = 1
            if (r0 != r2) goto L1e
            r1 = r2
        L1e:
            int r0 = r6.epollWait(r1)     // Catch: java.lang.Throwable -> L84
            int r1 = r6.wakenUp     // Catch: java.lang.Throwable -> L84
            if (r1 != r2) goto L31
            io.netty.channel.unix.FileDescriptor r1 = r6.eventFd     // Catch: java.lang.Throwable -> L84
            int r1 = r1.intValue()     // Catch: java.lang.Throwable -> L84
            r2 = 1
            io.netty.channel.epoll.Native.eventFdWrite(r1, r2)     // Catch: java.lang.Throwable -> L84
        L31:
            int r1 = r6.ioRatio     // Catch: java.lang.Throwable -> L84
            r2 = 100
            if (r1 != r2) goto L48
            if (r0 <= 0) goto L44
            io.netty.channel.epoll.EpollEventArray r1 = r6.events     // Catch: java.lang.Throwable -> L3f
            r6.processReady(r1, r0)     // Catch: java.lang.Throwable -> L3f
            goto L44
        L3f:
            r0 = move-exception
            r6.runAllTasks()     // Catch: java.lang.Throwable -> L84
            throw r0     // Catch: java.lang.Throwable -> L84
        L44:
            r6.runAllTasks()     // Catch: java.lang.Throwable -> L84
            goto L72
        L48:
            long r2 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L84
            if (r0 <= 0) goto L64
            io.netty.channel.epoll.EpollEventArray r4 = r6.events     // Catch: java.lang.Throwable -> L54
            r6.processReady(r4, r0)     // Catch: java.lang.Throwable -> L54
            goto L64
        L54:
            r0 = move-exception
            long r4 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L84
            long r4 = r4 - r2
            int r2 = 100 - r1
            long r2 = (long) r2     // Catch: java.lang.Throwable -> L84
            long r4 = r4 * r2
            long r1 = (long) r1     // Catch: java.lang.Throwable -> L84
            long r4 = r4 / r1
            r6.runAllTasks(r4)     // Catch: java.lang.Throwable -> L84
            throw r0     // Catch: java.lang.Throwable -> L84
        L64:
            long r4 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L84
            long r4 = r4 - r2
            int r2 = 100 - r1
            long r2 = (long) r2     // Catch: java.lang.Throwable -> L84
            long r4 = r4 * r2
            long r1 = (long) r1     // Catch: java.lang.Throwable -> L84
            long r4 = r4 / r1
            r6.runAllTasks(r4)     // Catch: java.lang.Throwable -> L84
        L72:
            boolean r1 = r6.allowGrowing     // Catch: java.lang.Throwable -> L84
            if (r1 == 0) goto L88
            io.netty.channel.epoll.EpollEventArray r1 = r6.events     // Catch: java.lang.Throwable -> L84
            int r1 = r1.length()     // Catch: java.lang.Throwable -> L84
            if (r0 != r1) goto L88
            io.netty.channel.epoll.EpollEventArray r0 = r6.events     // Catch: java.lang.Throwable -> L84
            r0.increase()     // Catch: java.lang.Throwable -> L84
            goto L88
        L84:
            r0 = move-exception
            handleLoopException(r0)
        L88:
            boolean r0 = r6.isShuttingDown()     // Catch: java.lang.Throwable -> L98
            if (r0 == 0) goto L0
            r6.closeAll()     // Catch: java.lang.Throwable -> L98
            boolean r0 = r6.confirmShutdown()     // Catch: java.lang.Throwable -> L98
            if (r0 == 0) goto L0
            return
        L98:
            r0 = move-exception
            handleLoopException(r0)
            goto L0
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.channel.epoll.EpollEventLoop.run():void");
    }

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

    @Override // io.netty.util.concurrent.SingleThreadEventExecutor
    public void wakeup(boolean z2) {
        if (z2 || !WAKEN_UP_UPDATER.compareAndSet(this, 0, 1)) {
            return;
        }
        Native.eventFdWrite(this.eventFd.intValue(), 1L);
    }
}
