// File: /workspace/github_c_makefile_star2_O3/nilyang[P]redis-tdd-annotation/src/redis.c
// Function: freeMemoryIfNeeded
int freeMemoryIfNeeded(void) {
    size_t mem_used, mem_tofree, mem_freed;
    int slaves = listLength(server.slaves);

    /* Remove the size of slaves output buffers and AOF buffer from the
     * count of used memory. */
    // 计算出 Redis 目前占用的内存总数，但有两个方面的内存不会计算在内：
    // 1）从服务器的输出缓冲区的内存
    // 2）AOF 缓冲区的内存
    mem_used = zmalloc_used_memory();
    if (slaves) {
        listIter li;
        listNode *ln;

        listRewind(server.slaves,&li);
        while((ln = listNext(&li))) {
            redisClient *slave = listNodeValue(ln);
            unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave);
            if (obuf_bytes > mem_used)
                mem_used = 0;
            else
                mem_used -= obuf_bytes;
        }
    }
    if (server.aof_state != REDIS_AOF_OFF) {
        mem_used -= sdslen(server.aof_buf);
        mem_used -= aofRewriteBufferSize();
    }

    /* Check if we are over the memory limit. */
    // 如果目前使用的内存大小比设置的 maxmemory 要小，那么无须执行进一步操作
    if (mem_used <= server.maxmemory) return REDIS_OK;

    // 如果占用内存比 maxmemory 要大，但是 maxmemory 策略为不淘汰，那么直接返回
    if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION)
        return REDIS_ERR; /* We need to free memory, but policy forbids. */

    /* Compute how much memory we need to free. */
    // 计算需要释放多少字节的内存
    mem_tofree = mem_used - server.maxmemory;

    // 初始化已释放内存的字节数为 0
    mem_freed = 0;

    // 根据 maxmemory 策略，
    // 遍历字典，释放内存并记录被释放内存的字节数
    while (mem_freed < mem_tofree) {
        int j, k, keys_freed = 0;

        // 遍历所有字典
        for (j = 0; j < server.dbnum; j++) {
            long bestval = 0; /* just to prevent warning */
            sds bestkey = NULL;
            dictEntry *de;
            redisDb *db = server.db+j;
            dict *dict;

            if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
                server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
            {
                // 如果策略是 allkeys-lru 或者 allkeys-random 
                // 那么淘汰的目标为所有数据库键
                dict = server.db[j].dict;
            } else {
                // 如果策略是 volatile-lru 、 volatile-random 或者 volatile-ttl 
                // 那么淘汰的目标为带过期时间的数据库键
                dict = server.db[j].expires;
            }

            // 跳过空字典
            if (dictSize(dict) == 0) continue;

            /* volatile-random and allkeys-random policy */
            // 如果使用的是随机策略，那么从目标字典中随机选出键
            if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
                server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
            {
                de = dictGetRandomKey(dict);
                bestkey = dictGetKey(de);
            }

            /* volatile-lru and allkeys-lru policy */
            // 如果使用的是 LRU 策略，
            // 那么从一集 sample 键中选出 IDLE 时间最长的那个键
            else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
                server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
            {
                struct evictionPoolEntry *pool = db->eviction_pool;

                while(bestkey == NULL) {
                    evictionPoolPopulate(dict, db->dict, db->eviction_pool);
                    /* Go backward from best to worst element to evict. */
                    for (k = REDIS_EVICTION_POOL_SIZE-1; k >= 0; k--) {
                        if (pool[k].key == NULL) continue;
                        de = dictFind(dict,pool[k].key);

                        /* Remove the entry from the pool. */
                        sdsfree(pool[k].key);
                        /* Shift all elements on its right to left. */
                        memmove(pool+k,pool+k+1,
                            sizeof(pool[0])*(REDIS_EVICTION_POOL_SIZE-k-1));
                        /* Clear the element on the right which is empty
                         * since we shifted one position to the left.  */
                        pool[REDIS_EVICTION_POOL_SIZE-1].key = NULL;
                        pool[REDIS_EVICTION_POOL_SIZE-1].idle = 0;

                        /* If the key exists, is our pick. Otherwise it is
                         * a ghost and we need to try the next element. */
                        if (de) {
                            bestkey = dictGetKey(de);
                            break;
                        } else {
                            /* Ghost... */
                            continue;
                        }
                    }
                }
            }

            /* volatile-ttl */
            // 策略为 volatile-ttl ，从一集 sample 键中选出过期时间距离当前时间最接近的键
            else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
                for (k = 0; k < server.maxmemory_samples; k++) {
                    sds thiskey;
                    long thisval;

                    de = dictGetRandomKey(dict);
                    thiskey = dictGetKey(de);
                    thisval = (long) dictGetVal(de);

                    /* Expire sooner (minor expire unix timestamp) is better
                     * candidate for deletion */
                    if (bestkey == NULL || thisval < bestval) {
                        bestkey = thiskey;
                        bestval = thisval;
                    }
                }
            }

            /* Finally remove the selected key. */
            // 删除被选中的键
            if (bestkey) {
                long long delta;

                robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
                propagateExpire(db,keyobj);
                /* We compute the amount of memory freed by dbDelete() alone.
                 * It is possible that actually the memory needed to propagate
                 * the DEL in AOF and replication link is greater than the one
                 * we are freeing removing the key, but we can't account for
                 * that otherwise we would never exit the loop.
                 *
                 * AOF and Output buffer memory will be freed eventually so
                 * we only care about memory used by the key space. */
                // 计算删除键所释放的内存数量
                delta = (long long) zmalloc_used_memory();
                dbDelete(db,keyobj);
                delta -= (long long) zmalloc_used_memory();
                mem_freed += delta;
                
                // 对淘汰键的计数器增一
                server.stat_evictedkeys++;

                notifyKeyspaceEvent(REDIS_NOTIFY_EVICTED, "evicted",
                    keyobj, db->id);
                decrRefCount(keyobj);
                keys_freed++;

                /* When the memory to free starts to be big enough, we may
                 * start spending so much time here that is impossible to
                 * deliver data to the slaves fast enough, so we force the
                 * transmission here inside the loop. */
                if (slaves) flushSlavesOutputBuffers();
            }
        }

        if (!keys_freed) return REDIS_ERR; /* nothing to free... */
    }

    return REDIS_OK;
}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x48, %rsp
movq 0xa3c5c(%rip), %rax     # 0xca168
movl 0x28(%rax), %ebx
callq 0x29b5e
movq %rbx, 0x28(%rsp)
testq %rbx, %rbx
je 0x26569
movq %rax, %r15
movq 0xa3c40(%rip), %rdi     # 0xca168
leaq 0x38(%rsp), %rbx
movq %rbx, %rsi
callq 0x20637
movq %rbx, %rdi
callq 0x20654
testq %rax, %rax
je 0x26566
xorl %ebx, %ebx
leaq 0x38(%rsp), %r14
movq 0x10(%rax), %rdi
callq 0x2f4fe
subq %rax, %r15
cmovbq %rbx, %r15
movq %r14, %rdi
callq 0x20654
testq %rax, %rax
jne 0x26549
movq %r15, %rax
cmpl $0x0, 0xa3f08(%rip)     # 0xca478
je 0x2658e
movq %rax, %r14
movq 0xa3f3c(%rip), %rax     # 0xca4b8
movslq -0x8(%rax), %rbx
callq 0x48e7e
addq %rbx, %rax
subq %rax, %r14
movq %r14, %rax
xorl %ecx, %ecx
subq 0xa4131(%rip), %rax     # 0xca6c8
jbe 0x267c5
movl $0xffffffff, %ecx       # imm = 0xFFFFFFFF
cmpl $0x5, 0xa4127(%rip)     # 0xca6d0
je 0x267c5
movq $0x0, 0x18(%rsp)
movq %rax, 0x20(%rsp)
cmpq %rax, 0x18(%rsp)
jae 0x267c3
cmpl $0x0, 0xa3e59(%rip)     # 0xca428
jle 0x267c5
xorl %esi, %esi
movl $0x0, 0x4(%rsp)
movq %rsi, %rdi
shlq $0x6, %rdi
addq 0xa39cb(%rip), %rdi     # 0xc9fb8
movl 0xa40dd(%rip), %eax     # 0xca6d0
leal -0x3(%rax), %ecx
xorl %edx, %edx
cmpl $0x2, %ecx
setae %dl
movq %rdi, 0x10(%rsp)
movq (%rdi,%rdx,8), %r12
movq 0x28(%r12), %rcx
addq 0x48(%r12), %rcx
je 0x26799
cmpl $0x4, %eax
ja 0x26799
movl %eax, %eax
leaq 0x6dc5b(%rip), %rcx     # 0x94284
movslq (%rcx,%rax,4), %rax
addq %rcx, %rax
movq %rsi, 0x8(%rsp)
jmpq *%rax
movq 0x10(%rsp), %rax
movq 0x28(%rax), %rax
leaq 0xf0(%rax), %r15
addq $0x100, %rax            # imm = 0x100
movq %rax, 0x30(%rsp)
movq 0x10(%rsp), %rax
movq (%rax), %rsi
movq 0x28(%rax), %rdx
movq %r12, %rdi
callq 0x278e7
movq 0x30(%rsp), %rbp
xorl %r13d, %r13d
leaq -0x10(%rbp), %r14
movq -0x8(%rbp), %rsi
testq %rsi, %rsi
je 0x266a9
movq %r12, %rdi
callq 0x226ac
movq %rax, %rbx
movq -0x8(%rbp), %rdi
callq 0x2850d
movq %r14, %rdi
movq %rbp, %rsi
movq %r13, %rdx
callq 0x1f780
xorps %xmm0, %xmm0
movups %xmm0, (%r15)
testq %rbx, %rbx
jne 0x266be
addq $0x10, %r13
movq %r14, %rbp
cmpq $0x100, %r13            # imm = 0x100
jne 0x2666e
xorl %r13d, %r13d
jmp 0x266c1
movq (%rbx), %r13
testq %r13, %r13
je 0x26652
jmp 0x2671d
movq %r12, %rdi
callq 0x22be9
movq (%rax), %r13
jmp 0x26718
cmpl $0x0, 0xa3ff8(%rip)     # 0xca6d4
jle 0x26799
xorl %ebx, %ebx
xorl %r13d, %r13d
xorl %r14d, %r14d
movq %r12, %rdi
callq 0x22be9
movq 0x8(%rax), %rcx
testq %r13, %r13
sete %dl
cmpq %rcx, %r14
setg %sil
orb %dl, %sil
je 0x2670e
movq (%rax), %r13
movq %rcx, %r14
incl %ebx
cmpl 0xa3fbe(%rip), %ebx     # 0xca6d4
jl 0x266ea
testq %r13, %r13
je 0x26794
movslq -0x8(%r13), %rsi
movq %r13, %rdi
callq 0x3068f
movq %rax, %r12
movq 0x10(%rsp), %r14
movq %r14, %rdi
movq %rax, %rsi
callq 0x32c3a
callq 0x29b5e
movq %rax, %rbx
movq %r14, %rdi
movq %r12, %rsi
callq 0x31a36
callq 0x29b5e
subq %rax, %rbx
addq %rbx, 0x18(%rsp)
incq 0xa3ba5(%rip)           # 0xca308
movl 0x30(%r14), %ecx
movl $0x200, %edi            # imm = 0x200
leaq 0x6f813(%rip), %rsi     # 0x95f86
movq %r12, %rdx
callq 0x60371
movq %r12, %rdi
callq 0x30b0c
incl 0x4(%rsp)
cmpq $0x0, 0x28(%rsp)
je 0x26794
callq 0x2fbbb
movq 0x8(%rsp), %rsi
incq %rsi
movslq 0xa3c85(%rip), %rax     # 0xca428
cmpq %rax, %rsi
jl 0x265df
cmpl $0x0, 0x4(%rsp)
movq 0x20(%rsp), %rax
movl $0xffffffff, %ecx       # imm = 0xFFFFFFFF
jne 0x265bd
jmp 0x267c5
xorl %ecx, %ecx
movl %ecx, %eax
addq $0x48, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq