// File: /workspace/github_c_makefile_star2_O0/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
movq %rsp, %rbp
subq $0xc0, %rsp
movq 0xea6d6(%rip), %rax     # 0x113ab8
movq 0x28(%rax), %rax
movl %eax, -0x24(%rbp)
callq 0x2e480
movq %rax, -0x10(%rbp)
cmpl $0x0, -0x24(%rbp)
je 0x2945b
movq 0xea6b9(%rip), %rdi     # 0x113ab8
leaq -0x38(%rbp), %rsi
callq 0x202b0
leaq -0x38(%rbp), %rdi
callq 0x20310
movq %rax, -0x40(%rbp)
cmpq $0x0, %rax
je 0x29459
movq -0x40(%rbp), %rax
movq 0x10(%rax), %rax
movq %rax, -0x48(%rbp)
movq -0x48(%rbp), %rdi
callq 0x38390
movq %rax, -0x50(%rbp)
movq -0x50(%rbp), %rax
cmpq -0x10(%rbp), %rax
jbe 0x29448
movq $0x0, -0x10(%rbp)
jmp 0x29457
movq -0x50(%rbp), %rcx
movq -0x10(%rbp), %rax
subq %rcx, %rax
movq %rax, -0x10(%rbp)
jmp 0x29408
jmp 0x2945b
cmpl $0x0, 0xea966(%rip)     # 0x113dc8
je 0x29491
movq 0xea99d(%rip), %rdi     # 0x113e08
callq 0x24b20
movq %rax, %rcx
movq -0x10(%rbp), %rax
subq %rcx, %rax
movq %rax, -0x10(%rbp)
callq 0x5e7c0
movq %rax, %rcx
movq -0x10(%rbp), %rax
subq %rcx, %rax
movq %rax, -0x10(%rbp)
movq -0x10(%rbp), %rax
cmpq 0xeab7c(%rip), %rax     # 0x114018
ja 0x294aa
movl $0x0, -0x4(%rbp)
jmp 0x2989f
cmpl $0x5, 0xeab6f(%rip)     # 0x114020
jne 0x294bf
movl $0xffffffff, -0x4(%rbp) # imm = 0xFFFFFFFF
jmp 0x2989f
movq -0x10(%rbp), %rax
subq 0xeab4e(%rip), %rax     # 0x114018
movq %rax, -0x18(%rbp)
movq $0x0, -0x20(%rbp)
movq -0x20(%rbp), %rax
cmpq -0x18(%rbp), %rax
jae 0x29898
movl $0x0, -0x5c(%rbp)
movl $0x0, -0x54(%rbp)
movl -0x54(%rbp), %eax
cmpl 0xea87d(%rip), %eax     # 0x113d78
jge 0x29884
movq $0x0, -0x68(%rbp)
movq $0x0, -0x70(%rbp)
movq 0xea3f0(%rip), %rax     # 0x113908
movslq -0x54(%rbp), %rcx
shlq $0x6, %rcx
addq %rcx, %rax
movq %rax, -0x80(%rbp)
cmpl $0x3, 0xeaaf2(%rip)     # 0x114020
je 0x29539
cmpl $0x4, 0xeaae9(%rip)     # 0x114020
jne 0x29557
movq 0xea3c8(%rip), %rax     # 0x113908
movslq -0x54(%rbp), %rcx
shlq $0x6, %rcx
addq %rcx, %rax
movq (%rax), %rax
movq %rax, -0x88(%rbp)
jmp 0x29574
movq 0xea3aa(%rip), %rax     # 0x113908
movslq -0x54(%rbp), %rcx
shlq $0x6, %rcx
addq %rcx, %rax
movq 0x8(%rax), %rax
movq %rax, -0x88(%rbp)
movq -0x88(%rbp), %rax
movq 0x28(%rax), %rax
movq -0x88(%rbp), %rcx
addq 0x48(%rcx), %rax
cmpq $0x0, %rax
jne 0x29595
jmp 0x29876
cmpl $0x4, 0xeaa84(%rip)     # 0x114020
je 0x295a7
cmpl $0x2, 0xeaa7b(%rip)     # 0x114020
jne 0x295c7
movq -0x88(%rbp), %rdi
callq 0x24470
movq %rax, -0x78(%rbp)
movq -0x78(%rbp), %rax
movq (%rax), %rax
movq %rax, -0x70(%rbp)
jmp 0x29798
cmpl $0x3, 0xeaa52(%rip)     # 0x114020
je 0x295dd
cmpl $0x0, 0xeaa49(%rip)     # 0x114020
jne 0x29713
movq -0x80(%rbp), %rax
movq 0x28(%rax), %rax
movq %rax, -0x90(%rbp)
cmpq $0x0, -0x70(%rbp)
jne 0x2970e
movq -0x88(%rbp), %rdi
movq -0x80(%rbp), %rax
movq (%rax), %rsi
movq -0x80(%rbp), %rax
movq 0x28(%rax), %rdx
callq 0x2b180
movl $0xf, -0x58(%rbp)
cmpl $0x0, -0x58(%rbp)
jl 0x29709
movq -0x90(%rbp), %rax
movslq -0x58(%rbp), %rcx
shlq $0x4, %rcx
addq %rcx, %rax
cmpq $0x0, 0x8(%rax)
jne 0x29641
jmp 0x296fb
movq -0x88(%rbp), %rdi
movq -0x90(%rbp), %rax
movslq -0x58(%rbp), %rcx
shlq $0x4, %rcx
addq %rcx, %rax
movq 0x8(%rax), %rsi
callq 0x23aa0
movq %rax, -0x78(%rbp)
movq -0x90(%rbp), %rax
movslq -0x58(%rbp), %rcx
shlq $0x4, %rcx
addq %rcx, %rax
movq 0x8(%rax), %rdi
callq 0x2c160
movq -0x90(%rbp), %rdi
movslq -0x58(%rbp), %rax
shlq $0x4, %rax
addq %rax, %rdi
movq -0x90(%rbp), %rsi
movslq -0x58(%rbp), %rax
shlq $0x4, %rax
addq %rax, %rsi
addq $0x10, %rsi
movl $0x10, %eax
subl -0x58(%rbp), %eax
subl $0x1, %eax
movslq %eax, %rdx
shlq $0x4, %rdx
callq 0x1f780
movq -0x90(%rbp), %rax
movq $0x0, 0xf8(%rax)
movq -0x90(%rbp), %rax
movq $0x0, 0xf0(%rax)
cmpq $0x0, -0x78(%rbp)
je 0x296f9
movq -0x78(%rbp), %rax
movq (%rax), %rax
movq %rax, -0x70(%rbp)
jmp 0x29709
jmp 0x296fb
movl -0x58(%rbp), %eax
addl $-0x1, %eax
movl %eax, -0x58(%rbp)
jmp 0x29619
jmp 0x295ec
jmp 0x29796
cmpl $0x1, 0xea906(%rip)     # 0x114020
jne 0x29794
movl $0x0, -0x58(%rbp)
movl -0x58(%rbp), %eax
cmpl 0xea8f8(%rip), %eax     # 0x114024
jge 0x29792
movq -0x88(%rbp), %rdi
callq 0x24470
movq %rax, -0x78(%rbp)
movq -0x78(%rbp), %rax
movq (%rax), %rax
movq %rax, -0x98(%rbp)
movq -0x78(%rbp), %rax
movq 0x8(%rax), %rax
movq %rax, -0xa0(%rbp)
cmpq $0x0, -0x70(%rbp)
je 0x2976f
movq -0xa0(%rbp), %rax
cmpq -0x68(%rbp), %rax
jge 0x29785
movq -0x98(%rbp), %rax
movq %rax, -0x70(%rbp)
movq -0xa0(%rbp), %rax
movq %rax, -0x68(%rbp)
jmp 0x29787
movl -0x58(%rbp), %eax
addl $0x1, %eax
movl %eax, -0x58(%rbp)
jmp 0x29723
jmp 0x29794
jmp 0x29796
jmp 0x29798
cmpq $0x0, -0x70(%rbp)
je 0x29874
movq -0x70(%rbp), %rax
movq %rax, -0xb8(%rbp)
movq -0x70(%rbp), %rdi
callq 0x24b20
movq -0xb8(%rbp), %rdi
movq %rax, %rsi
callq 0x3a2e0
movq %rax, -0xb0(%rbp)
movq -0x80(%rbp), %rdi
movq -0xb0(%rbp), %rsi
callq 0x3e030
callq 0x2e480
movq %rax, -0xa8(%rbp)
movq -0x80(%rbp), %rdi
movq -0xb0(%rbp), %rsi
callq 0x3c4f0
callq 0x2e480
movq %rax, %rcx
movq -0xa8(%rbp), %rax
subq %rcx, %rax
movq %rax, -0xa8(%rbp)
movq -0xa8(%rbp), %rax
addq -0x20(%rbp), %rax
movq %rax, -0x20(%rbp)
movq 0xea430(%rip), %rax     # 0x113c58
addq $0x1, %rax
movq %rax, 0xea425(%rip)     # 0x113c58
movq -0xb0(%rbp), %rdx
movq -0x80(%rbp), %rax
movl 0x30(%rax), %ecx
movl $0x200, %edi            # imm = 0x200
leaq 0xb6761(%rip), %rsi     # 0xdffae
callq 0x814a0
movq -0xb0(%rbp), %rdi
callq 0x3aaa0
movl -0x5c(%rbp), %eax
addl $0x1, %eax
movl %eax, -0x5c(%rbp)
cmpl $0x0, -0x24(%rbp)
je 0x29872
callq 0x38e10
jmp 0x29874
jmp 0x29876
movl -0x54(%rbp), %eax
addl $0x1, %eax
movl %eax, -0x54(%rbp)
jmp 0x294f2
cmpl $0x0, -0x5c(%rbp)
jne 0x29893
movl $0xffffffff, -0x4(%rbp) # imm = 0xFFFFFFFF
jmp 0x2989f
jmp 0x294d6
movl $0x0, -0x4(%rbp)
movl -0x4(%rbp), %eax
addq $0xc0, %rsp
popq %rbp
retq
nopl (%rax,%rax)