package io.netty.buffer;

import g.a.a.a.a;
import io.netty.buffer.PoolArena;
import io.netty.util.Recycler;
import io.netty.util.internal.MathUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.nio.ByteBuffer;
import java.util.Queue;

/* JADX INFO: loaded from: classes.dex */
public final class PoolThreadCache {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) PoolThreadCache.class);
    private int allocations;
    public final PoolArena<ByteBuffer> directArena;
    private final int freeSweepAllocationThreshold;
    public final PoolArena<byte[]> heapArena;
    private final MemoryRegionCache<ByteBuffer>[] normalDirectCaches;
    private final MemoryRegionCache<byte[]>[] normalHeapCaches;
    private final int numShiftsNormalDirect;
    private final int numShiftsNormalHeap;
    private final MemoryRegionCache<ByteBuffer>[] smallSubPageDirectCaches;
    private final MemoryRegionCache<byte[]>[] smallSubPageHeapCaches;
    private final MemoryRegionCache<ByteBuffer>[] tinySubPageDirectCaches;
    private final MemoryRegionCache<byte[]>[] tinySubPageHeapCaches;

    /* JADX INFO: renamed from: io.netty.buffer.PoolThreadCache$1, reason: invalid class name */
    public static /* synthetic */ class AnonymousClass1 {
        public static final /* synthetic */ int[] $SwitchMap$io$netty$buffer$PoolArena$SizeClass;

        static {
            PoolArena.SizeClass.values();
            int[] iArr = new int[3];
            $SwitchMap$io$netty$buffer$PoolArena$SizeClass = iArr;
            try {
                iArr[PoolArena.SizeClass.Normal.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$io$netty$buffer$PoolArena$SizeClass[PoolArena.SizeClass.Small.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$io$netty$buffer$PoolArena$SizeClass[PoolArena.SizeClass.Tiny.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
        }
    }

    public static abstract class MemoryRegionCache<T> {
        private static final Recycler<Entry> RECYCLER = new Recycler<Entry>() { // from class: io.netty.buffer.PoolThreadCache.MemoryRegionCache.1
            /* JADX WARN: Can't rename method to resolve collision */
            @Override // io.netty.util.Recycler
            public Entry newObject(Recycler.Handle<Entry> handle) {
                return new Entry(handle);
            }
        };
        private int allocations;
        private final Queue<Entry<T>> queue;
        private final int size;
        private final PoolArena.SizeClass sizeClass;

        public static final class Entry<T> {
            public PoolChunk<T> chunk;
            public long handle = -1;
            public final Recycler.Handle<Entry<?>> recyclerHandle;

            public Entry(Recycler.Handle<Entry<?>> handle) {
                this.recyclerHandle = handle;
            }

            public void recycle() {
                this.chunk = null;
                this.handle = -1L;
                this.recyclerHandle.recycle(this);
            }
        }

        public MemoryRegionCache(int i2, PoolArena.SizeClass sizeClass) {
            int iSafeFindNextPositivePowerOfTwo = MathUtil.safeFindNextPositivePowerOfTwo(i2);
            this.size = iSafeFindNextPositivePowerOfTwo;
            this.queue = PlatformDependent.newFixedMpscQueue(iSafeFindNextPositivePowerOfTwo);
            this.sizeClass = sizeClass;
        }

        private int free(int i2) {
            int i3 = 0;
            while (i3 < i2) {
                Entry<T> entryPoll = this.queue.poll();
                if (entryPoll == null) {
                    break;
                }
                freeEntry(entryPoll);
                i3++;
            }
            return i3;
        }

        private void freeEntry(Entry entry) {
            PoolChunk<T> poolChunk = entry.chunk;
            long j2 = entry.handle;
            entry.recycle();
            poolChunk.arena.freeChunk(poolChunk, j2, this.sizeClass);
        }

        /* JADX WARN: Multi-variable type inference failed */
        private static Entry newEntry(PoolChunk<?> poolChunk, long j2) {
            Entry entry = RECYCLER.get();
            entry.chunk = poolChunk;
            entry.handle = j2;
            return entry;
        }

        public final boolean add(PoolChunk<T> poolChunk, long j2) {
            Entry<T> entryNewEntry = newEntry(poolChunk, j2);
            boolean zOffer = this.queue.offer(entryNewEntry);
            if (!zOffer) {
                entryNewEntry.recycle();
            }
            return zOffer;
        }

        public final boolean allocate(PooledByteBuf<T> pooledByteBuf, int i2) {
            Entry<T> entryPoll = this.queue.poll();
            if (entryPoll == null) {
                return false;
            }
            initBuf(entryPoll.chunk, entryPoll.handle, pooledByteBuf, i2);
            entryPoll.recycle();
            this.allocations++;
            return true;
        }

        public final int free() {
            return free(Integer.MAX_VALUE);
        }

        public abstract void initBuf(PoolChunk<T> poolChunk, long j2, PooledByteBuf<T> pooledByteBuf, int i2);

        public final void trim() {
            int i2 = this.size - this.allocations;
            this.allocations = 0;
            if (i2 > 0) {
                free(i2);
            }
        }
    }

    public static final class NormalMemoryRegionCache<T> extends MemoryRegionCache<T> {
        public NormalMemoryRegionCache(int i2) {
            super(i2, PoolArena.SizeClass.Normal);
        }

        @Override // io.netty.buffer.PoolThreadCache.MemoryRegionCache
        public void initBuf(PoolChunk<T> poolChunk, long j2, PooledByteBuf<T> pooledByteBuf, int i2) {
            poolChunk.initBuf(pooledByteBuf, j2, i2);
        }
    }

    public static final class SubPageMemoryRegionCache<T> extends MemoryRegionCache<T> {
        public SubPageMemoryRegionCache(int i2, PoolArena.SizeClass sizeClass) {
            super(i2, sizeClass);
        }

        @Override // io.netty.buffer.PoolThreadCache.MemoryRegionCache
        public void initBuf(PoolChunk<T> poolChunk, long j2, PooledByteBuf<T> pooledByteBuf, int i2) {
            poolChunk.initBufWithSubpage(pooledByteBuf, j2, i2);
        }
    }

    public PoolThreadCache(PoolArena<byte[]> poolArena, PoolArena<ByteBuffer> poolArena2, int i2, int i3, int i4, int i5, int i6) {
        if (i5 < 0) {
            throw new IllegalArgumentException(a.n("maxCachedBufferCapacity: ", i5, " (expected: >= 0)"));
        }
        this.freeSweepAllocationThreshold = i6;
        this.heapArena = poolArena;
        this.directArena = poolArena2;
        if (poolArena2 != null) {
            this.tinySubPageDirectCaches = createSubPageCaches(i2, 32, PoolArena.SizeClass.Tiny);
            this.smallSubPageDirectCaches = createSubPageCaches(i3, poolArena2.numSmallSubpagePools, PoolArena.SizeClass.Small);
            this.numShiftsNormalDirect = log2(poolArena2.pageSize);
            this.normalDirectCaches = createNormalCaches(i4, i5, poolArena2);
            poolArena2.numThreadCaches.getAndIncrement();
        } else {
            this.tinySubPageDirectCaches = null;
            this.smallSubPageDirectCaches = null;
            this.normalDirectCaches = null;
            this.numShiftsNormalDirect = -1;
        }
        if (poolArena != null) {
            this.tinySubPageHeapCaches = createSubPageCaches(i2, 32, PoolArena.SizeClass.Tiny);
            this.smallSubPageHeapCaches = createSubPageCaches(i3, poolArena.numSmallSubpagePools, PoolArena.SizeClass.Small);
            this.numShiftsNormalHeap = log2(poolArena.pageSize);
            this.normalHeapCaches = createNormalCaches(i4, i5, poolArena);
            poolArena.numThreadCaches.getAndIncrement();
        } else {
            this.tinySubPageHeapCaches = null;
            this.smallSubPageHeapCaches = null;
            this.normalHeapCaches = null;
            this.numShiftsNormalHeap = -1;
        }
        if (!(this.tinySubPageDirectCaches == null && this.smallSubPageDirectCaches == null && this.normalDirectCaches == null && this.tinySubPageHeapCaches == null && this.smallSubPageHeapCaches == null && this.normalHeapCaches == null) && i6 < 1) {
            throw new IllegalArgumentException(a.n("freeSweepAllocationThreshold: ", i6, " (expected: > 0)"));
        }
    }

    private boolean allocate(MemoryRegionCache<?> memoryRegionCache, PooledByteBuf pooledByteBuf, int i2) {
        if (memoryRegionCache == null) {
            return false;
        }
        boolean zAllocate = memoryRegionCache.allocate(pooledByteBuf, i2);
        int i3 = this.allocations + 1;
        this.allocations = i3;
        if (i3 >= this.freeSweepAllocationThreshold) {
            this.allocations = 0;
            trim();
        }
        return zAllocate;
    }

    private MemoryRegionCache<?> cache(PoolArena<?> poolArena, int i2, PoolArena.SizeClass sizeClass) {
        int iOrdinal = sizeClass.ordinal();
        if (iOrdinal == 0) {
            return cacheForTiny(poolArena, i2);
        }
        if (iOrdinal == 1) {
            return cacheForSmall(poolArena, i2);
        }
        if (iOrdinal == 2) {
            return cacheForNormal(poolArena, i2);
        }
        throw new Error();
    }

    private static <T> MemoryRegionCache<T> cache(MemoryRegionCache<T>[] memoryRegionCacheArr, int i2) {
        if (memoryRegionCacheArr == null || i2 > memoryRegionCacheArr.length - 1) {
            return null;
        }
        return memoryRegionCacheArr[i2];
    }

    private MemoryRegionCache<?> cacheForNormal(PoolArena<?> poolArena, int i2) {
        if (poolArena.isDirect()) {
            return cache(this.normalDirectCaches, log2(i2 >> this.numShiftsNormalDirect));
        }
        return cache(this.normalHeapCaches, log2(i2 >> this.numShiftsNormalHeap));
    }

    private MemoryRegionCache<?> cacheForSmall(PoolArena<?> poolArena, int i2) {
        int iSmallIdx = PoolArena.smallIdx(i2);
        return poolArena.isDirect() ? cache(this.smallSubPageDirectCaches, iSmallIdx) : cache(this.smallSubPageHeapCaches, iSmallIdx);
    }

    private MemoryRegionCache<?> cacheForTiny(PoolArena<?> poolArena, int i2) {
        int iTinyIdx = PoolArena.tinyIdx(i2);
        return poolArena.isDirect() ? cache(this.tinySubPageDirectCaches, iTinyIdx) : cache(this.tinySubPageHeapCaches, iTinyIdx);
    }

    private static <T> MemoryRegionCache<T>[] createNormalCaches(int i2, int i3, PoolArena<T> poolArena) {
        if (i2 <= 0 || i3 <= 0) {
            return null;
        }
        int iMax = Math.max(1, log2(Math.min(poolArena.chunkSize, i3) / poolArena.pageSize) + 1);
        MemoryRegionCache<T>[] memoryRegionCacheArr = new MemoryRegionCache[iMax];
        for (int i4 = 0; i4 < iMax; i4++) {
            memoryRegionCacheArr[i4] = new NormalMemoryRegionCache(i2);
        }
        return memoryRegionCacheArr;
    }

    private static <T> MemoryRegionCache<T>[] createSubPageCaches(int i2, int i3, PoolArena.SizeClass sizeClass) {
        if (i2 <= 0 || i3 <= 0) {
            return null;
        }
        MemoryRegionCache<T>[] memoryRegionCacheArr = new MemoryRegionCache[i3];
        for (int i4 = 0; i4 < i3; i4++) {
            memoryRegionCacheArr[i4] = new SubPageMemoryRegionCache(i2, sizeClass);
        }
        return memoryRegionCacheArr;
    }

    private static int free(MemoryRegionCache<?> memoryRegionCache) {
        if (memoryRegionCache == null) {
            return 0;
        }
        return memoryRegionCache.free();
    }

    private static int free(MemoryRegionCache<?>[] memoryRegionCacheArr) {
        if (memoryRegionCacheArr == null) {
            return 0;
        }
        int iFree = 0;
        for (MemoryRegionCache<?> memoryRegionCache : memoryRegionCacheArr) {
            iFree += free(memoryRegionCache);
        }
        return iFree;
    }

    private static int log2(int i2) {
        int i3 = 0;
        while (i2 > 1) {
            i2 >>= 1;
            i3++;
        }
        return i3;
    }

    private static void trim(MemoryRegionCache<?> memoryRegionCache) {
        if (memoryRegionCache == null) {
            return;
        }
        memoryRegionCache.trim();
    }

    private static void trim(MemoryRegionCache<?>[] memoryRegionCacheArr) {
        if (memoryRegionCacheArr == null) {
            return;
        }
        for (MemoryRegionCache<?> memoryRegionCache : memoryRegionCacheArr) {
            trim(memoryRegionCache);
        }
    }

    public boolean add(PoolArena<?> poolArena, PoolChunk poolChunk, long j2, int i2, PoolArena.SizeClass sizeClass) {
        MemoryRegionCache<?> memoryRegionCacheCache = cache(poolArena, i2, sizeClass);
        if (memoryRegionCacheCache == null) {
            return false;
        }
        return memoryRegionCacheCache.add(poolChunk, j2);
    }

    public boolean allocateNormal(PoolArena<?> poolArena, PooledByteBuf<?> pooledByteBuf, int i2, int i3) {
        return allocate(cacheForNormal(poolArena, i3), pooledByteBuf, i2);
    }

    public boolean allocateSmall(PoolArena<?> poolArena, PooledByteBuf<?> pooledByteBuf, int i2, int i3) {
        return allocate(cacheForSmall(poolArena, i3), pooledByteBuf, i2);
    }

    public boolean allocateTiny(PoolArena<?> poolArena, PooledByteBuf<?> pooledByteBuf, int i2, int i3) {
        return allocate(cacheForTiny(poolArena, i3), pooledByteBuf, i2);
    }

    public void free() {
        int iFree = free(this.tinySubPageDirectCaches) + free(this.smallSubPageDirectCaches) + free(this.normalDirectCaches) + free((MemoryRegionCache<?>[]) this.tinySubPageHeapCaches) + free((MemoryRegionCache<?>[]) this.smallSubPageHeapCaches) + free((MemoryRegionCache<?>[]) this.normalHeapCaches);
        if (iFree > 0) {
            InternalLogger internalLogger = logger;
            if (internalLogger.isDebugEnabled()) {
                internalLogger.debug("Freed {} thread-local buffer(s) from thread: {}", Integer.valueOf(iFree), Thread.currentThread().getName());
            }
        }
        PoolArena<ByteBuffer> poolArena = this.directArena;
        if (poolArena != null) {
            poolArena.numThreadCaches.getAndDecrement();
        }
        PoolArena<byte[]> poolArena2 = this.heapArena;
        if (poolArena2 != null) {
            poolArena2.numThreadCaches.getAndDecrement();
        }
    }

    public void trim() {
        trim(this.tinySubPageDirectCaches);
        trim(this.smallSubPageDirectCaches);
        trim(this.normalDirectCaches);
        trim((MemoryRegionCache<?>[]) this.tinySubPageHeapCaches);
        trim((MemoryRegionCache<?>[]) this.smallSubPageHeapCaches);
        trim((MemoryRegionCache<?>[]) this.normalHeapCaches);
    }
}
