// File: /workspace/github_c_makefile_star2_O1/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 0xa3e88(%rip), %rax     # 0xca168
movl 0x28(%rax), %ebx
callq 0x298b2
movq %rax, %rcx
movq %rbx, 0x28(%rsp)
testq %rbx, %rbx
je 0x26340
movq %rcx, %r15
movq 0xa3e69(%rip), %rdi     # 0xca168
leaq 0x38(%rsp), %rbx
movq %rbx, %rsi
callq 0x205d2
movq %rbx, %rdi
callq 0x205ef
testq %rax, %rax
je 0x2633d
xorl %ebx, %ebx
leaq 0x38(%rsp), %r14
movq 0x10(%rax), %rdi
callq 0x2f212
subq %rax, %r15
cmovbq %rbx, %r15
movq %r14, %rdi
callq 0x205ef
testq %rax, %rax
jne 0x26320
movq %r15, %rcx
cmpl $0x0, 0xa4131(%rip)     # 0xca478
je 0x26365
movq 0xa4168(%rip), %rax     # 0xca4b8
movslq -0x8(%rax), %rbx
movq %rcx, %r14
callq 0x49396
movq %r14, %rcx
addq %rbx, %rax
subq %rax, %rcx
xorl %eax, %eax
subq 0xa435a(%rip), %rcx     # 0xca6c8
jbe 0x265a6
movl $0xffffffff, %eax       # imm = 0xFFFFFFFF
cmpl $0x5, 0xa4350(%rip)     # 0xca6d0
je 0x265a6
movq $0x0, 0x18(%rsp)
movq %rcx, 0x20(%rsp)
cmpq %rcx, 0x18(%rsp)
jae 0x265a4
cmpl $0x0, 0xa4082(%rip)     # 0xca428
jle 0x26598
xorl %esi, %esi
movl $0x0, 0x4(%rsp)
movq %rsi, %rdi
shlq $0x6, %rdi
addq 0xa3bf4(%rip), %rdi     # 0xc9fb8
movl 0xa4306(%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 0x26571
cmpl $0x4, %eax
movq %rsi, 0x8(%rsp)
ja 0x264ed
movl %eax, %eax
leaq 0x6de2f(%rip), %rcx     # 0x94234
movslq (%rcx,%rax,4), %rax
addq %rcx, %rax
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 0x2763c
movq 0x30(%rsp), %rbp
xorl %r13d, %r13d
leaq -0x10(%rbp), %r14
movq -0x8(%rbp), %rsi
testq %rsi, %rsi
je 0x26480
movq %r12, %rdi
callq 0x224dc
movq %rax, %rbx
movq -0x8(%rbp), %rdi
callq 0x28204
movq %r14, %rdi
movq %rbp, %rsi
movq %r13, %rdx
callq 0x1f780
xorps %xmm0, %xmm0
movups %xmm0, (%r15)
testq %rbx, %rbx
jne 0x26495
addq $0x10, %r13
movq %r14, %rbp
cmpq $0x100, %r13            # imm = 0x100
jne 0x26445
xorl %r13d, %r13d
jmp 0x26498
movq (%rbx), %r13
testq %r13, %r13
je 0x26429
jmp 0x264f0
movq %r12, %rdi
callq 0x22a1c
movq (%rax), %r13
jmp 0x264f0
cmpl $0x0, 0xa4221(%rip)     # 0xca6d4
jle 0x264ed
xorl %ebx, %ebx
xorl %r13d, %r13d
xorl %r14d, %r14d
movq %r12, %rdi
callq 0x22a1c
movq 0x8(%rax), %rcx
testq %r13, %r13
sete %dl
cmpq %rcx, %r14
setg %sil
orb %dl, %sil
je 0x264e1
movq (%rax), %r13
movq %rcx, %r14
incl %ebx
cmpl 0xa41eb(%rip), %ebx     # 0xca6d4
jl 0x264bd
jmp 0x264f0
xorl %r13d, %r13d
testq %r13, %r13
je 0x2656c
movslq -0x8(%r13), %rsi
movq %r13, %rdi
callq 0x303b7
movq %rax, %r12
movq 0x10(%rsp), %r14
movq %r14, %rdi
movq %rax, %rsi
callq 0x328ff
callq 0x298b2
movq %rax, %rbx
movq %r14, %rdi
movq %r12, %rsi
callq 0x3174b
callq 0x298b2
subq %rax, %rbx
addq %rbx, 0x18(%rsp)
incq 0xa3dcd(%rip)           # 0xca308
movl 0x30(%r14), %ecx
movl $0x200, %edi            # imm = 0x200
leaq 0x6f9eb(%rip), %rsi     # 0x95f36
movq %r12, %rdx
callq 0x608b5
movq %r12, %rdi
callq 0x30834
incl 0x4(%rsp)
cmpq $0x0, 0x28(%rsp)
je 0x2656c
callq 0x2f8cc
movq 0x8(%rsp), %rsi
incq %rsi
movslq 0xa3ead(%rip), %rax     # 0xca428
cmpq %rax, %rsi
jl 0x263b6
cmpl $0x0, 0x4(%rsp)
sete %dl
movq 0x20(%rsp), %rcx
movl $0xffffffff, %eax       # imm = 0xFFFFFFFF
jmp 0x2659a
movb $0x1, %dl
testb %dl, %dl
je 0x26394
jmp 0x265a6
xorl %eax, %eax
addq $0x48, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq