package io.netty.channel.kqueue;

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.kqueue.AbstractKQueueChannel;
import io.netty.channel.unix.Errors;
import io.netty.channel.unix.FileDescriptor;
import io.netty.channel.unix.IovArray;
import io.netty.util.IntSupplier;
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.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 KQueueEventLoop extends SingleThreadEventLoop {
    public static final /* synthetic */ boolean $assertionsDisabled = false;
    private static final int KQUEUE_WAKE_UP_IDENT = 0;
    private final boolean allowGrowing;
    private final KQueueEventArray changeList;
    private final KQueueEventArray eventList;
    private volatile int ioRatio;
    private final IovArray iovArray;
    private final NativeLongArray jniChannelPointers;
    private final FileDescriptor kqueueFd;
    private final Callable<Integer> pendingTasksCallable;
    private final IntSupplier selectNowSupplier;
    private final SelectStrategy selectStrategy;
    private volatile int wakenUp;
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) KQueueEventLoop.class);
    private static final AtomicIntegerFieldUpdater<KQueueEventLoop> WAKEN_UP_UPDATER = AtomicIntegerFieldUpdater.newUpdater(KQueueEventLoop.class, "wakenUp");

    static {
        KQueue.ensureAvailability();
    }

    public KQueueEventLoop(EventLoopGroup eventLoopGroup, Executor executor, int i2, SelectStrategy selectStrategy, RejectedExecutionHandler rejectedExecutionHandler) {
        super(eventLoopGroup, executor, false, SingleThreadEventLoop.DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);
        this.iovArray = new IovArray();
        this.selectNowSupplier = new IntSupplier() { // from class: io.netty.channel.kqueue.KQueueEventLoop.1
            @Override // io.netty.util.IntSupplier
            public int get() {
                return KQueueEventLoop.this.kqueueWaitNow();
            }
        };
        this.pendingTasksCallable = new Callable<Integer>() { // from class: io.netty.channel.kqueue.KQueueEventLoop.2
            /* JADX WARN: Can't rename method to resolve collision */
            @Override // java.util.concurrent.Callable
            public Integer call() {
                return Integer.valueOf(KQueueEventLoop.super.pendingTasks());
            }
        };
        this.ioRatio = 50;
        this.selectStrategy = (SelectStrategy) ObjectUtil.checkNotNull(selectStrategy, "strategy");
        FileDescriptor fileDescriptorNewKQueue = Native.newKQueue();
        this.kqueueFd = fileDescriptorNewKQueue;
        if (i2 == 0) {
            this.allowGrowing = true;
            i2 = 4096;
        } else {
            this.allowGrowing = false;
        }
        this.changeList = new KQueueEventArray(i2);
        this.eventList = new KQueueEventArray(i2);
        this.jniChannelPointers = new NativeLongArray(4096);
        int iKeventAddUserEvent = Native.keventAddUserEvent(fileDescriptorNewKQueue.intValue(), 0);
        if (iKeventAddUserEvent >= 0) {
            return;
        }
        cleanup();
        StringBuilder sbF = a.F("kevent failed to add user event with errno: ");
        sbF.append(-iKeventAddUserEvent);
        throw new IllegalStateException(sbF.toString());
    }

    private void closeAll() {
        try {
            kqueueWaitNow();
        } catch (IOException unused) {
        }
    }

    private void deleteJniChannelPointers() {
        if (this.jniChannelPointers.isEmpty()) {
            return;
        }
        KQueueEventArray.deleteGlobalRefs(this.jniChannelPointers.memoryAddress(), this.jniChannelPointers.memoryAddressEnd());
        this.jniChannelPointers.clear();
    }

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

    private int kqueueWait(int i2, int i3) throws Errors.NativeIoException {
        deleteJniChannelPointers();
        int iKeventWait = Native.keventWait(this.kqueueFd.intValue(), this.changeList, this.eventList, i2, i3);
        this.changeList.clear();
        return iKeventWait;
    }

    private int kqueueWait(boolean z2) {
        if (z2 && hasTasks()) {
            return kqueueWaitNow();
        }
        long jDelayNanos = delayNanos(System.nanoTime());
        int iMin = (int) Math.min(jDelayNanos / 1000000000, 2147483647L);
        return kqueueWait(iMin, (int) Math.min(jDelayNanos - (((long) iMin) * 1000000000), 2147483647L));
    }

    /* JADX INFO: Access modifiers changed from: private */
    public int kqueueWaitNow() {
        return kqueueWait(0, 0);
    }

    private void processReady(int i2) {
        for (int i3 = 0; i3 < i2; i3++) {
            short sFilter = this.eventList.filter(i3);
            short sFlags = this.eventList.flags(i3);
            if (sFilter != Native.EVFILT_USER && (Native.EV_ERROR & sFlags) == 0) {
                AbstractKQueueChannel abstractKQueueChannelChannel = this.eventList.channel(i3);
                if (abstractKQueueChannelChannel == null) {
                    logger.warn("events[{}]=[{}, {}] had no channel!", Integer.valueOf(i3), Integer.valueOf(this.eventList.fd(i3)), Short.valueOf(sFilter));
                } else {
                    AbstractKQueueChannel.AbstractKQueueUnsafe abstractKQueueUnsafe = (AbstractKQueueChannel.AbstractKQueueUnsafe) abstractKQueueChannelChannel.unsafe();
                    if (sFilter == Native.EVFILT_WRITE) {
                        abstractKQueueUnsafe.writeReady();
                    } else if (sFilter == Native.EVFILT_READ) {
                        abstractKQueueUnsafe.readReady(this.eventList.data(i3));
                    } else if (sFilter == Native.EVFILT_SOCK && (this.eventList.fflags(i3) & Native.NOTE_RDHUP) != 0) {
                        abstractKQueueUnsafe.readEOF();
                    }
                    if ((Native.EV_EOF & sFlags) != 0) {
                        abstractKQueueUnsafe.readEOF();
                    }
                }
            }
        }
    }

    private void wakeup() {
        Native.keventTriggerUserEvent(this.kqueueFd.intValue(), 0);
    }

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

    @Override // io.netty.util.concurrent.SingleThreadEventExecutor
    public void cleanup() {
        try {
            try {
                this.kqueueFd.close();
            } catch (IOException e2) {
                logger.warn("Failed to close the kqueue fd.", (Throwable) e2);
            }
        } finally {
            deleteJniChannelPointers();
            this.jniChannelPointers.free();
            this.changeList.free();
            this.eventList.free();
        }
    }

    public void evSet(AbstractKQueueChannel abstractKQueueChannel, short s2, short s3, int i2) {
        this.changeList.evSet(abstractKQueueChannel, s2, s3, i2);
    }

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

    public void remove(AbstractKQueueChannel abstractKQueueChannel) {
        long j2 = abstractKQueueChannel.jniSelfPtr;
        if (j2 == 0) {
            return;
        }
        this.jniChannelPointers.add(j2);
        abstractKQueueChannel.jniSelfPtr = 0L;
    }

    /* JADX WARN: Can't wrap try/catch for region: R(8:51|2|(2:59|58)(8:54|4|(4:7|(1:9)(1:10)|11|(1:13))(1:6)|14|15|(2:(2:47|18)|23)(3:24|(2:49|26)|31)|32|(1:36))|52|40|57|(3:55|42|(2:56|44)(1:61))(1:60)|58) */
    /* JADX WARN: Code restructure failed: missing block: B:45:0x008e, code lost:
    
        r0 = move-exception;
     */
    /* JADX WARN: Code restructure failed: missing block: B:46:0x008f, 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() {
        /*
            r7 = this;
        L0:
            io.netty.channel.SelectStrategy r0 = r7.selectStrategy     // Catch: java.lang.Throwable -> L7a
            io.netty.util.IntSupplier r1 = r7.selectNowSupplier     // Catch: java.lang.Throwable -> L7a
            boolean r2 = r7.hasTasks()     // Catch: java.lang.Throwable -> L7a
            int r0 = r0.calculateStrategy(r1, r2)     // Catch: java.lang.Throwable -> L7a
            r1 = -2
            if (r0 == r1) goto L0
            r1 = -1
            r2 = 0
            if (r0 == r1) goto L14
            goto L2b
        L14:
            java.util.concurrent.atomic.AtomicIntegerFieldUpdater<io.netty.channel.kqueue.KQueueEventLoop> r0 = io.netty.channel.kqueue.KQueueEventLoop.WAKEN_UP_UPDATER     // Catch: java.lang.Throwable -> L7a
            int r0 = r0.getAndSet(r7, r2)     // Catch: java.lang.Throwable -> L7a
            r1 = 1
            if (r0 != r1) goto L1f
            r0 = r1
            goto L20
        L1f:
            r0 = r2
        L20:
            int r0 = r7.kqueueWait(r0)     // Catch: java.lang.Throwable -> L7a
            int r3 = r7.wakenUp     // Catch: java.lang.Throwable -> L7a
            if (r3 != r1) goto L2b
            r7.wakeup()     // Catch: java.lang.Throwable -> L7a
        L2b:
            int r1 = r7.ioRatio     // Catch: java.lang.Throwable -> L7a
            r3 = 100
            if (r1 != r3) goto L40
            if (r0 <= 0) goto L3c
            r7.processReady(r0)     // Catch: java.lang.Throwable -> L37
            goto L3c
        L37:
            r0 = move-exception
            r7.runAllTasks()     // Catch: java.lang.Throwable -> L7a
            throw r0     // Catch: java.lang.Throwable -> L7a
        L3c:
            r7.runAllTasks()     // Catch: java.lang.Throwable -> L7a
            goto L68
        L40:
            long r3 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L7a
            if (r0 <= 0) goto L5a
            r7.processReady(r0)     // Catch: java.lang.Throwable -> L4a
            goto L5a
        L4a:
            r0 = move-exception
            long r5 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L7a
            long r5 = r5 - r3
            int r2 = 100 - r1
            long r2 = (long) r2     // Catch: java.lang.Throwable -> L7a
            long r5 = r5 * r2
            long r1 = (long) r1     // Catch: java.lang.Throwable -> L7a
            long r5 = r5 / r1
            r7.runAllTasks(r5)     // Catch: java.lang.Throwable -> L7a
            throw r0     // Catch: java.lang.Throwable -> L7a
        L5a:
            long r5 = java.lang.System.nanoTime()     // Catch: java.lang.Throwable -> L7a
            long r5 = r5 - r3
            int r3 = 100 - r1
            long r3 = (long) r3     // Catch: java.lang.Throwable -> L7a
            long r5 = r5 * r3
            long r3 = (long) r1     // Catch: java.lang.Throwable -> L7a
            long r5 = r5 / r3
            r7.runAllTasks(r5)     // Catch: java.lang.Throwable -> L7a
        L68:
            boolean r1 = r7.allowGrowing     // Catch: java.lang.Throwable -> L7a
            if (r1 == 0) goto L7e
            io.netty.channel.kqueue.KQueueEventArray r1 = r7.eventList     // Catch: java.lang.Throwable -> L7a
            int r1 = r1.capacity()     // Catch: java.lang.Throwable -> L7a
            if (r0 != r1) goto L7e
            io.netty.channel.kqueue.KQueueEventArray r0 = r7.eventList     // Catch: java.lang.Throwable -> L7a
            r0.realloc(r2)     // Catch: java.lang.Throwable -> L7a
            goto L7e
        L7a:
            r0 = move-exception
            handleLoopException(r0)
        L7e:
            boolean r0 = r7.isShuttingDown()     // Catch: java.lang.Throwable -> L8e
            if (r0 == 0) goto L0
            r7.closeAll()     // Catch: java.lang.Throwable -> L8e
            boolean r0 = r7.confirmShutdown()     // Catch: java.lang.Throwable -> L8e
            if (r0 == 0) goto L0
            return
        L8e:
            r0 = move-exception
            handleLoopException(r0)
            goto L0
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.channel.kqueue.KQueueEventLoop.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;
        }
        wakeup();
    }
}
