// File: /workspace/github_c_makefile_star2_O2/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 $0x58, %rsp
movq 0xa1d42(%rip), %rax     # 0xc7168
movl 0x28(%rax), %ebx
callq 0x28434
movq %rbx, 0x38(%rsp)
testq %rbx, %rbx
je 0x25471
movq %rax, %rbx
movq 0xa1d26(%rip), %rdi     # 0xc7168
leaq 0x48(%rsp), %r14
movq %r14, %rsi
callq 0x1ffac
movq %r14, %rdi
callq 0x1ffc6
testq %rax, %rax
je 0x2546e
movq 0x10(%rax), %rdi
callq 0x2da02
subq %rax, %rbx
jae 0x2544f
xorl %ebx, %ebx
jmp 0x2544f
movq %rbx, %rax
cmpl $0x0, 0xa2000(%rip)     # 0xc7478
je 0x25496
movq %rax, %r14
movq 0xa2034(%rip), %rax     # 0xc74b8
movslq -0x8(%rax), %rbx
callq 0x459e6
addq %rbx, %rax
subq %rax, %r14
movq %r14, %rax
xorl %esi, %esi
subq 0xa2229(%rip), %rax     # 0xc76c8
jbe 0x256cd
pushq $-0x1
popq %rsi
cmpl $0x5, 0xa2221(%rip)     # 0xc76d0
je 0x256cd
xorl %r12d, %r12d
movq %rax, 0x30(%rsp)
cmpq %rax, %r12
jae 0x256cb
xorl %r14d, %r14d
movl $0x0, 0xc(%rsp)
movslq 0xa1f50(%rip), %rax     # 0xc7428
cmpq %rax, %r14
jge 0x256b9
movq %r14, %rdi
shlq $0x6, %rdi
addq 0xa1ac9(%rip), %rdi     # 0xc6fb8
movl 0xa21db(%rip), %eax     # 0xc76d0
leal -0x3(%rax), %ecx
xorl %edx, %edx
cmpl $0x2, %ecx
setae %dl
movq %rdi, 0x20(%rsp)
movq (%rdi,%rdx,8), %rdx
movq 0x28(%rdx), %rcx
movq %rdx, 0x10(%rsp)
addq 0x48(%rdx), %rcx
je 0x25674
cmpl $0x4, %eax
ja 0x25674
movl %eax, %eax
leaq 0x64d16(%rip), %rcx     # 0x8a244
movslq (%rcx,%rax,4), %rax
addq %rcx, %rax
movq %r14, 0x18(%rsp)
movq %r12, 0x28(%rsp)
jmpq *%rax
movq 0x20(%rsp), %rax
movq 0x28(%rax), %rax
leaq 0xf0(%rax), %r15
addq $0x100, %rax            # imm = 0x100
movq %rax, 0x40(%rsp)
xorl %r13d, %r13d
testq %r13, %r13
jne 0x255ef
movq 0x20(%rsp), %rax
movq (%rax), %rsi
movq 0x28(%rax), %rdx
movq 0x10(%rsp), %rdi
callq 0x266d0
movq 0x40(%rsp), %rbp
xorl %r13d, %r13d
pushq $0xf
popq %r12
testq %r12, %r12
js 0x2555c
leaq -0x10(%rbp), %r14
movq -0x8(%rbp), %rsi
testq %rsi, %rsi
je 0x255cc
movq 0x10(%rsp), %rdi
callq 0x21b64
movq %rax, %rbx
movq -0x8(%rbp), %rdi
callq 0x271f7
movq %r14, %rdi
movq %rbp, %rsi
movq %r13, %rdx
callq 0x1f780
xorps %xmm0, %xmm0
movups %xmm0, (%r15)
testq %rbx, %rbx
jne 0x255d8
decq %r12
addq $0x10, %r13
movq %r14, %rbp
jmp 0x2558a
movq (%rbx), %r13
jmp 0x2555f
movq 0x10(%rsp), %rdi
callq 0x22047
movq (%rax), %r13
testq %r13, %r13
je 0x25667
movslq -0x8(%r13), %rsi
movq %r13, %rdi
callq 0x2ea81
movq %rax, %r13
movq 0x20(%rsp), %rbx
movq %rbx, %rdi
movq %rax, %rsi
callq 0x30cd9
callq 0x28434
movq %rax, %r12
movq %rbx, %rdi
movq %r13, %rsi
callq 0x2fc3b
callq 0x28434
subq %rax, %r12
addq 0x28(%rsp), %r12
incq 0xa1cd3(%rip)           # 0xc7308
movl 0x30(%rbx), %ecx
movl $0x200, %edi            # imm = 0x200
leaq 0x66902(%rip), %rsi     # 0x8bf46
movq %r13, %rdx
callq 0x5b488
movq %r13, %rdi
callq 0x2ee1f
incl 0xc(%rsp)
cmpq $0x0, 0x38(%rsp)
je 0x2566c
callq 0x2e043
jmp 0x2566c
movq 0x28(%rsp), %r12
pushq $-0x1
popq %rsi
movq 0x18(%rsp), %r14
incq %r14
jmp 0x254d1
xorl %ebx, %ebx
xorl %r13d, %r13d
xorl %ebp, %ebp
cmpl 0xa204b(%rip), %ebp     # 0xc76d4
jge 0x255ea
movq 0x10(%rsp), %rdi
callq 0x22047
movq 0x8(%rax), %rcx
testq %r13, %r13
sete %dl
cmpq %rcx, %rbx
setg %sil
orb %dl, %sil
je 0x256b5
movq (%rax), %r13
movq %rcx, %rbx
incl %ebp
jmp 0x25683
cmpl $0x0, 0xc(%rsp)
movq 0x30(%rsp), %rax
jne 0x254bd
jmp 0x256cd
xorl %esi, %esi
movl %esi, %eax
addq $0x58, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq