// File: /workspace/github_c_makefile_star2_O1/nilyang[P]redis-tdd-annotation/src/redis.c
// Function: activeExpireCycle
void activeExpireCycle(int type) {
    /* This function has some global state in order to continue the work
     * incrementally across calls. */
    // 静态变量，用来累积函数连续执行时的数据
    static unsigned int current_db = 0; /* Last DB tested. */
    static int timelimit_exit = 0;      /* Time limit hit in previous call? */
    static long long last_fast_cycle = 0; /* When last fast cycle ran. */

    unsigned int j, iteration = 0;
    // 默认每次处理的数据库数量
    unsigned int dbs_per_call = REDIS_DBCRON_DBS_PER_CALL;
    // 函数开始的时间
    long long start = ustime(), timelimit;

    // 快速模式
    if (type == ACTIVE_EXPIRE_CYCLE_FAST) {
        /* Don't start a fast cycle if the previous cycle did not exited
         * for time limt. Also don't repeat a fast cycle for the same period
         * as the fast cycle total duration itself. */
        // 如果上次函数没有触发 timelimit_exit ，那么不执行处理
        if (!timelimit_exit) return;
        // 如果距离上次执行未够一定时间，那么不执行处理
        if (start < last_fast_cycle + ACTIVE_EXPIRE_CYCLE_FAST_DURATION*2) return;
        // 运行到这里，说明执行快速处理，记录当前时间
        last_fast_cycle = start;
    }

    /* We usually should test REDIS_DBCRON_DBS_PER_CALL per iteration, with
     * two exceptions:
     *
     * 一般情况下，函数只处理 REDIS_DBCRON_DBS_PER_CALL 个数据库，
     * 除非：
     *
     * 1) Don't test more DBs than we have.
     *    当前数据库的数量小于 REDIS_DBCRON_DBS_PER_CALL
     * 2) If last time we hit the time limit, we want to scan all DBs
     * in this iteration, as there is work to do in some DB and we don't want
     * expired keys to use memory for too much time. 
     *     如果上次处理遇到了时间上限，那么这次需要对所有数据库进行扫描，
     *     这可以避免过多的过期键占用空间
     */
    if (dbs_per_call > server.dbnum || timelimit_exit)
        dbs_per_call = server.dbnum;

    /* We can use at max ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC percentage of CPU time
     * per iteration. Since this function gets called with a frequency of
     * server.hz times per second, the following is the max amount of
     * microseconds we can spend in this function. */
    // 函数处理的微秒时间上限
    // ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC 默认为 25 ，也即是 25 % 的 CPU 时间
    timelimit = 1000000*ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/server.hz/100;
    timelimit_exit = 0;
    if (timelimit <= 0) timelimit = 1;

    // 如果是运行在快速模式之下
    // 那么最多只能运行 FAST_DURATION 微秒 
    // 默认值为 1000 （微秒）
    if (type == ACTIVE_EXPIRE_CYCLE_FAST)
        timelimit = ACTIVE_EXPIRE_CYCLE_FAST_DURATION; /* in microseconds. */

    // 遍历数据库
    for (j = 0; j < dbs_per_call; j++) {
        int expired;
        // 指向要处理的数据库
        redisDb *db = server.db+(current_db % server.dbnum);

        /* Increment the DB now so we are sure if we run out of time
         * in the current DB we'll restart from the next. This allows to
         * distribute the time evenly across DBs. */
        // 为 DB 计数器加一，如果进入 do 循环之后因为超时而跳出
        // 那么下次会直接从下个 DB 开始处理
        current_db++;

        /* Continue to expire if at the end of the cycle more than 25%
         * of the keys were expired. */
        do {
            unsigned long num, slots;
            long long now, ttl_sum;
            int ttl_samples;

            /* If there is nothing to expire try next DB ASAP. */
            // 获取数据库中带过期时间的键的数量
            // 如果该数量为 0 ，直接跳过这个数据库
            if ((num = dictSize(db->expires)) == 0) {
                db->avg_ttl = 0;
                break;
            }
            // 获取数据库中键值对的数量
            slots = dictSlots(db->expires);
            // 当前时间
            now = mstime();

            /* When there are less than 1% filled slots getting random
             * keys is expensive, so stop here waiting for better times...
             * The dictionary will be resized asap. */
            // 这个数据库的使用率低于 1% ，扫描起来太费力了（大部分都会 MISS）
            // 跳过，等待字典收缩程序运行
            if (num && slots > DICT_HT_INITIAL_SIZE &&
                (num*100/slots < 1)) break;

            /* The main collection cycle. Sample random keys among keys
             * with an expire set, checking for expired ones. 
             *
             * 样本计数器
             */
            // 已处理过期键计数器
            expired = 0;
            // 键的总 TTL 计数器
            ttl_sum = 0;
            // 总共处理的键计数器
            ttl_samples = 0;

            // 每次最多只能检查 LOOKUPS_PER_LOOP 个键
            if (num > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP)
                num = ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP;

            // 开始遍历数据库
            while (num--) {
                dictEntry *de;
                long long ttl;

                // 从 expires 中随机取出一个带过期时间的键
                if ((de = dictGetRandomKey(db->expires)) == NULL) break;
                // 计算 TTL
                ttl = dictGetSignedIntegerVal(de)-now;
                // 如果键已经过期，那么删除它，并将 expired 计数器增一
                if (activeExpireCycleTryExpire(db,de,now)) expired++;
                if (ttl < 0) ttl = 0;
                // 累积键的 TTL
                ttl_sum += ttl;
                // 累积处理键的个数
                ttl_samples++;
            }

            /* Update the average TTL stats for this database. */
            // 为这个数据库更新平均 TTL 统计数据
            if (ttl_samples) {
                // 计算当前平均值
                long long avg_ttl = ttl_sum/ttl_samples;
                
                // 如果这是第一次设置数据库平均 TTL ，那么进行初始化
                if (db->avg_ttl == 0) db->avg_ttl = avg_ttl;
                /* Smooth the value averaging with the previous one. */
                // 取数据库的上次平均 TTL 和今次平均 TTL 的平均值
                db->avg_ttl = (db->avg_ttl+avg_ttl)/2;
            }

            /* We can't block forever here even if there are many keys to
             * expire. So after a given amount of milliseconds return to the
             * caller waiting for the other active expire cycle. */
            // 我们不能用太长时间处理过期键，
            // 所以这个函数执行一定时间之后就要返回

            // 更新遍历次数
            iteration++;

            // 每遍历 16 次执行一次
            if ((iteration & 0xf) == 0 && /* check once every 16 iterations. */
                (ustime()-start) > timelimit)
            {
                // 如果遍历次数正好是 16 的倍数
                // 并且遍历的时间超过了 timelimit
                // 那么断开 timelimit_exit
                timelimit_exit = 1;
            }

            // 已经超时了，返回
            if (timelimit_exit) return;

            /* We don't repeat the cycle if there are less than 25% of keys
             * found expired in the current DB. */
            // 如果已删除的过期键占当前总数据库带过期时间的键数量的 25 %
            // 那么不再遍历
        } while (expired > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP/4);
    }
}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x48, %rsp
movl %edi, %ebx
leaq 0x30(%rsp), %r14
movq %r14, %rdi
xorl %esi, %esi
callq 0x1f2f0
imulq $0xf4240, (%r14), %rax  # imm = 0xF4240
addq 0x8(%r14), %rax
movq %rax, 0x20(%rsp)
cmpl $0x1, %ebx
jne 0x23673
cmpb $0x1, 0xa71a2(%rip)     # 0xca7ec
jne 0x238c3
movl $0x7d0, %eax            # imm = 0x7D0
addq 0xa7194(%rip), %rax     # 0xca7f0
cmpq %rax, 0x20(%rsp)
jl 0x238c3
movq 0x20(%rsp), %rax
movq %rax, 0xa717d(%rip)     # 0xca7f0
movl 0xa6daf(%rip), %eax     # 0xca428
testb $0x1, 0xa716c(%rip)     # 0xca7ec
movl $0x10, %esi
cmovnel %eax, %esi
cmpl $0x10, %eax
cmovbl %eax, %esi
movl $0x17d7840, %eax        # imm = 0x17D7840
xorl %edx, %edx
idivl 0xa6915(%rip)           # 0xc9fb0
cltq
imulq $0x51eb851f, %rax, %rax # imm = 0x51EB851F
movq %rax, %rcx
shrq $0x3f, %rcx
sarq $0x25, %rax
addl %ecx, %eax
cmpl $0x2, %eax
movl $0x1, %ecx
cmovgel %eax, %ecx
cmpl $0x1, %ebx
movb $0x0, 0xa7126(%rip)     # 0xca7ec
movl $0x3e8, %eax            # imm = 0x3E8
cmovnel %ecx, %eax
movq %rax, 0x40(%rsp)
movl %esi, 0x2c(%rsp)
testl %esi, %esi
je 0x238c3
leaq 0x30(%rsp), %r14
movabsq $0x20c49ba5e353f7cf, %r12 # imm = 0x20C49BA5E353F7CF
xorl %esi, %esi
movl $0x0, 0x8(%rsp)
movq %rax, 0x10(%rsp)
movl 0xa70e5(%rip), %ecx     # 0xca7e8
movl %ecx, %eax
xorl %edx, %edx
divl 0xa6d1b(%rip)           # 0xca428
shlq $0x6, %rdx
addq 0xa68a0(%rip), %rdx     # 0xc9fb8
movq %rdx, 0x18(%rsp)
incl %ecx
movl %ecx, 0xa70c3(%rip)     # 0xca7e8
movl %esi, 0xc(%rsp)
movq 0x18(%rsp), %rcx
movq 0x8(%rcx), %rax
movq 0x48(%rax), %rbp
addq 0x28(%rax), %rbp
je 0x2388a
movq 0x38(%rax), %rbx
addq 0x18(%rax), %rbx
movq %r14, %rdi
xorl %esi, %esi
callq 0x1f2f0
imulq $0xf4240, 0x30(%rsp), %rax # imm = 0xF4240
addq 0x38(%rsp), %rax
imulq %r12
movq %rdx, %r15
cmpq $0x5, %rbx
jb 0x2377e
imulq $0x64, %rbp, %rcx
movl $0x5, %eax
cmpq %rcx, %rbx
ja 0x23884
movq %r15, %rax
shrq $0x3f, %rax
sarq $0x7, %r15
addq %rax, %r15
cmpq $0x14, %rbp
movl $0x14, %eax
cmovaeq %rax, %rbp
incq %rbp
movq $0x0, 0x10(%rsp)
xorl %r12d, %r12d
xorl %ebx, %ebx
movq 0x18(%rsp), %r14
decq %rbp
je 0x23803
movq 0x8(%r14), %rdi
callq 0x22a1c
movq %rax, %r13
testq %rax, %rax
je 0x237fe
movq 0x8(%r13), %r14
subq %r15, %r14
movq 0x18(%rsp), %rdi
movq %r13, %rsi
movq %r15, %rdx
callq 0x235a8
movq 0x10(%rsp), %rcx
addl %eax, %ecx
movq %rcx, 0x10(%rsp)
testq %r14, %r14
movl $0x0, %eax
cmovleq %rax, %r14
addq %r14, %r12
movq 0x18(%rsp), %r14
incl %ebx
testq %r13, %r13
jne 0x237af
testl %ebx, %ebx
je 0x23832
movslq %ebx, %rcx
movq %r12, %rax
cqto
idivq %rcx
cmpq $0x0, 0x38(%r14)
jne 0x2381d
movq %rax, 0x38(%r14)
addq 0x38(%r14), %rax
movq %rax, %rcx
shrq $0x3f, %rcx
addq %rax, %rcx
sarq %rcx
movq %rcx, 0x38(%r14)
movl 0x8(%rsp), %eax
incl %eax
movl %eax, 0x8(%rsp)
testb $0xf, %al
leaq 0x30(%rsp), %r14
jne 0x23873
movq %r14, %rdi
xorl %esi, %esi
callq 0x1f2f0
imulq $0xf4240, 0x30(%rsp), %rax # imm = 0xF4240
movq 0x38(%rsp), %rcx
subq 0x20(%rsp), %rcx
addq %rax, %rcx
cmpq 0x40(%rsp), %rcx
jle 0x23873
movb $0x1, 0xa6f79(%rip)     # 0xca7ec
movzbl 0xa6f72(%rip), %eax     # 0xca7ec
movabsq $0x20c49ba5e353f7cf, %r12 # imm = 0x20C49BA5E353F7CF
movl 0xc(%rsp), %esi
jmp 0x23897
movq $0x0, 0x38(%rcx)
movl $0x5, %eax
testl %eax, %eax
jne 0x238a8
cmpl $0x5, 0x10(%rsp)
jg 0x23729
jmp 0x238ad
cmpl $0x5, %eax
jne 0x238b1
xorl %eax, %eax
jmp 0x238b3
movb $0x1, %al
testb %al, %al
jne 0x238c3
incl %esi
cmpl 0x2c(%rsp), %esi
jne 0x236fd
addq $0x48, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq