// File: /workspace/github_c_makefile_star2_O1/nilyang[P]redis-tdd-annotation/src/redis.c
// Function: serverCron
int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
    int j;
    REDIS_NOTUSED(eventLoop);
    REDIS_NOTUSED(id);
    REDIS_NOTUSED(clientData);

    /* Software watchdog: deliver the SIGALRM that will reach the signal
     * handler if we don't return here fast enough. */
    if (server.watchdog_period) watchdogScheduleSignal(server.watchdog_period);

    /* Update the time cache. */
    updateCachedTime();

    // 记录服务器执行命令的次数
    run_with_period(100) trackOperationsPerSecond();

    /* We have just REDIS_LRU_BITS bits per object for LRU information.
     * So we use an (eventually wrapping) LRU clock.
     *
     * Note that even if the counter wraps it's not a big problem,
     * everything will still work but some object will appear younger
     * to Redis. However for this to happen a given object should never be
     * touched for all the time needed to the counter to wrap, which is
     * not likely.
     *
     * 即使服务器的时间最终比 1.5 年长也无所谓，
     * 对象系统仍会正常运作，不过一些对象可能会比服务器本身的时钟更年轻。
     * 不过这要这个对象在 1.5 年内都没有被访问过，才会出现这种现象。
     *
     * Note that you can change the resolution altering the
     * REDIS_LRU_CLOCK_RESOLUTION define.
     *
     * LRU 时间的精度可以通过修改 REDIS_LRU_CLOCK_RESOLUTION 常量来改变。
     */
    server.lruclock = getLRUClock();

    /* Record the max memory used since the server was started. */
    // 记录服务器的内存峰值
    if (zmalloc_used_memory() > server.stat_peak_memory)
        server.stat_peak_memory = zmalloc_used_memory();

    /* Sample the RSS here since this is a relatively slow call. */
    server.resident_set_size = zmalloc_get_rss();

    /* We received a SIGTERM, shutting down here in a safe way, as it is
     * not ok doing so inside the signal handler. */
    // 服务器进程收到 SIGTERM 信号，关闭服务器
    if (server.shutdown_asap) {

        // 尝试关闭服务器
        if (prepareForShutdown(0) == REDIS_OK) exit(0);

        // 如果关闭失败，那么打印 LOG ，并移除关闭标识
        redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
        server.shutdown_asap = 0;
    }

    /* Show some info about non-empty databases */
    // 打印数据库的键值对信息
    run_with_period(5000) {
        for (j = 0; j < server.dbnum; j++) {
            long long size, used, vkeys;

            // 可用键值对的数量
            size = dictSlots(server.db[j].dict);
            // 已用键值对的数量
            used = dictSize(server.db[j].dict);
            // 带有过期时间的键值对数量
            vkeys = dictSize(server.db[j].expires);

            // 用 LOG 打印数量
            if (used || vkeys) {
                redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
                /* dictPrintStats(server.dict); */
            }
        }
    }

    /* Show information about connected clients */
    // 如果服务器没有运行在 SENTINEL 模式下，那么打印客户端的连接信息
    if (!server.sentinel_mode) {
        run_with_period(5000) {
            redisLog(REDIS_VERBOSE,
                "%lu clients connected (%lu slaves), %zu bytes in use",
                listLength(server.clients)-listLength(server.slaves),
                listLength(server.slaves),
                zmalloc_used_memory());
        }
    }

    /* We need to do a few operations on clients asynchronously. */
    // 检查客户端，关闭超时客户端，并释放客户端多余的缓冲区
    clientsCron();

    /* Handle background operations on Redis databases. */
    // 对数据库执行各种操作
    databasesCron();

    /* Start a scheduled AOF rewrite if this was requested by the user while
     * a BGSAVE was in progress. */
    // 如果 BGSAVE 和 BGREWRITEAOF 都没有在执行
    // 并且有一个 BGREWRITEAOF 在等待，那么执行 BGREWRITEAOF
    if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 &&
        server.aof_rewrite_scheduled)
    {
        rewriteAppendOnlyFileBackground();
    }

    /* Check if a background saving or AOF rewrite in progress terminated. */
    // 检查 BGSAVE 或者 BGREWRITEAOF 是否已经执行完毕
    if (server.rdb_child_pid != -1 || server.aof_child_pid != -1) {
        int statloc;
        pid_t pid;

        // 接收子进程发来的信号，非阻塞
        if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
            int exitcode = WEXITSTATUS(statloc);
            int bysignal = 0;
            
            if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);

            // BGSAVE 执行完毕
            if (pid == server.rdb_child_pid) {
                backgroundSaveDoneHandler(exitcode,bysignal);

            // BGREWRITEAOF 执行完毕
            } else if (pid == server.aof_child_pid) {
                backgroundRewriteDoneHandler(exitcode,bysignal);

            } else {
                redisLog(REDIS_WARNING,
                    "Warning, detected child with unmatched pid: %ld",
                    (long)pid);
            }
            updateDictResizePolicy();
        }
    } else {

        /* If there is not a background saving/rewrite in progress check if
         * we have to save/rewrite now */
        // 既然没有 BGSAVE 或者 BGREWRITEAOF 在执行，那么检查是否需要执行它们

        // 遍历所有保存条件，看是否需要执行 BGSAVE 命令
         for (j = 0; j < server.saveparamslen; j++) {
            struct saveparam *sp = server.saveparams+j;

            /* Save if we reached the given amount of changes,
             * the given amount of seconds, and if the latest bgsave was
             * successful or if, in case of an error, at least
             * REDIS_BGSAVE_RETRY_DELAY seconds already elapsed. */
            // 检查是否有某个保存条件已经满足了
            if (server.dirty >= sp->changes &&
                server.unixtime-server.lastsave > sp->seconds &&
                (server.unixtime-server.lastbgsave_try >
                 REDIS_BGSAVE_RETRY_DELAY ||
                 server.lastbgsave_status == REDIS_OK))
            {
                redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
                    sp->changes, (int)sp->seconds);
                // 执行 BGSAVE
                rdbSaveBackground(server.rdb_filename);
                break;
            }
         }

         /* Trigger an AOF rewrite if needed */
        // 出发 BGREWRITEAOF
         if (server.rdb_child_pid == -1 &&
             server.aof_child_pid == -1 &&
             server.aof_rewrite_perc &&
             // AOF 文件的当前大小大于执行 BGREWRITEAOF 所需的最小大小
             server.aof_current_size > server.aof_rewrite_min_size)
         {
            // 上一次完成 AOF 写入之后，AOF 文件的大小
            long long base = server.aof_rewrite_base_size ?
                            server.aof_rewrite_base_size : 1;

            // AOF 文件当前的体积相对于 base 的体积的百分比
            long long growth = (server.aof_current_size*100/base) - 100;

            // 如果增长体积的百分比超过了 growth ，那么执行 BGREWRITEAOF
            if (growth >= server.aof_rewrite_perc) {
                redisLog(REDIS_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth);
                // 执行 BGREWRITEAOF
                rewriteAppendOnlyFileBackground();
            }
         }
    }

    // 根据 AOF 政策，
    // 考虑是否需要将 AOF 缓冲区中的内容写入到 AOF 文件中
    /* AOF postponed flush: Try at every cron cycle if the slow fsync
     * completed. */
    if (server.aof_flush_postponed_start) flushAppendOnlyFile(0);

    /* AOF write errors: in this case we have a buffer to flush as well and
     * clear the AOF error in case of success to make the DB writable again,
     * however to try every second is enough in case of 'hz' is set to
     * an higher frequency. */
    run_with_period(1000) {
        if (server.aof_last_write_status == REDIS_ERR)
            flushAppendOnlyFile(0);
    }

    /* Close clients that need to be closed asynchronous */
    // 关闭那些需要异步关闭的客户端
    freeClientsInAsyncFreeQueue();

    /* Clear the paused clients flag if needed. */
    clientsArePaused(); /* Don't check return value, just use the side effect. */

    /* Replication cron function -- used to reconnect to master and
     * to detect transfer failures. */
    // 复制函数
    // 重连接主服务器、向主服务器发送 ACK 、判断数据发送失败情况、断开本服务器超时的从服务器，等等
    run_with_period(1000) replicationCron();

    /* Run the Redis Cluster cron. */
    // 如果服务器运行在集群模式下，那么执行集群操作
    run_with_period(100) {
        if (server.cluster_enabled) clusterCron();
    }

    /* Run the Sentinel timer if we are in sentinel mode. */
    // 如果服务器运行在 sentinel 模式下，那么执行 SENTINEL 的主函数
    run_with_period(100) {
        if (server.sentinel_mode) sentinelTimer();
    }

    /* Cleanup expired MIGRATE cached sockets. */
    // 集群。。。TODO
    run_with_period(1000) {
        migrateCloseTimedoutSockets();
    }

    // 增加 loop 计数器
    server.cronloops++;

    return 1000/server.hz;
}

// Assembly:
pushq %r15
pushq %r14
pushq %rbx
subq $0x10, %rsp
movl 0xa6ae4(%rip), %edi     # 0xca7e0
testl %edi, %edi
je 0x23d05
callq 0x4e4c5
callq 0x23c9a
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa6299(%rip)           # 0xc9fb0
cmpl $0x63, %eax
jg 0x23d38
movl %eax, %ecx
movl 0xa62d8(%rip), %esi     # 0xc9ffc
movl $0x64, %eax
xorl %edx, %edx
idivl %ecx
movl %eax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x23d3d
callq 0x23914
movq %rsp, %rbx
movq %rbx, %rdi
xorl %esi, %esi
callq 0x1f2f0
imulq $0xf4240, (%rbx), %rax  # imm = 0xF4240
addq 0x8(%rbx), %rax
movabsq $0x431bde82d7b634db, %rcx # imm = 0x431BDE82D7B634DB
imulq %rcx
movq %rdx, %rax
shrq $0x3f, %rax
shrq $0x12, %rdx
addl %eax, %edx
andl $0xffffff, %edx         # imm = 0xFFFFFF
movzbl 0xa625f(%rip), %eax     # 0xc9fdb
shll $0x18, %eax
orl %edx, %eax
movl %eax, 0xa6251(%rip)     # 0xc9fd8
callq 0x298b2
cmpq 0xa658d(%rip), %rax     # 0xca320
jbe 0x23da1
callq 0x298b2
movq %rax, 0xa657f(%rip)     # 0xca320
callq 0x298d6
movq %rax, 0xa65c3(%rip)     # 0xca370
cmpl $0x0, 0xa6228(%rip)     # 0xc9fdc
je 0x23de2
xorl %edi, %edi
callq 0x26664
testl %eax, %eax
je 0x2420e
leaq 0x70907(%rip), %rsi     # 0x946d3
movl $0x3, %edi
xorl %eax, %eax
callq 0x23064
movl $0x0, 0xa61fa(%rip)     # 0xc9fdc
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa61c1(%rip)           # 0xc9fb0
movl %eax, %ecx
movl 0xa6205(%rip), %esi     # 0xc9ffc
movl $0x1388, %eax           # imm = 0x1388
xorl %edx, %edx
idivl %ecx
movl %eax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x23e79
cmpl $0x0, 0xa6616(%rip)     # 0xca428
jle 0x23e79
movl $0x8, %r15d
leaq 0x70912(%rip), %rbx     # 0x94733
xorl %r14d, %r14d
movq 0xa618d(%rip), %rcx     # 0xc9fb8
movq -0x8(%rcx,%r15), %rax
movq (%rcx,%r15), %rdx
movq 0x48(%rax), %rcx
addq 0x28(%rax), %rcx
movq 0x48(%rdx), %r8
addq 0x28(%rdx), %r8
movq %rcx, %rdx
orq %r8, %rdx
je 0x23e66
movq 0x38(%rax), %r9
addq 0x18(%rax), %r9
movl $0x1, %edi
movq %rbx, %rsi
movl %r14d, %edx
xorl %eax, %eax
callq 0x23064
incq %r14
movslq 0xa65b8(%rip), %rax     # 0xca428
addq $0x40, %r15
cmpq %rax, %r14
jl 0x23e24
cmpl $0x0, 0xa61ac(%rip)     # 0xca02c
jne 0x23ee5
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa6121(%rip)           # 0xc9fb0
movl %eax, %ecx
movl 0xa6165(%rip), %esi     # 0xc9ffc
movl $0x1388, %eax           # imm = 0x1388
xorl %edx, %edx
idivl %ecx
movl %eax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x23ee5
movq 0xa62a6(%rip), %rax     # 0xca158
movq 0x28(%rax), %rbx
movq 0xa62ab(%rip), %rax     # 0xca168
movq 0x28(%rax), %r14
subq %r14, %rbx
callq 0x298b2
leaq 0x70896(%rip), %rsi     # 0x94766
movl $0x1, %edi
movq %rbx, %rdx
movq %r14, %rcx
movq %rax, %r8
xorl %eax, %eax
callq 0x23064
callq 0x23b71
callq 0x23bef
cmpl $-0x1, 0xa6622(%rip)    # 0xca518
jne 0x23f0f
cmpl $-0x1, 0xa65ad(%rip)    # 0xca4ac
jne 0x23f0f
cmpl $0x0, 0xa65a0(%rip)     # 0xca4a8
je 0x23f0f
callq 0x49ae1
cmpl $-0x1, 0xa6602(%rip)    # 0xca518
jne 0x23fa3
cmpl $-0x1, 0xa6589(%rip)    # 0xca4ac
jne 0x23fa3
movslq 0xa65fc(%rip), %rax     # 0xca528
testq %rax, %rax
jle 0x24024
movq 0xa65e4(%rip), %rsi     # 0xca520
movq 0xa65c5(%rip), %rdi     # 0xca508
movq 0xa67f6(%rip), %rcx     # 0xca740
movq %rcx, %r8
subq 0xa65ec(%rip), %r8      # 0xca540
subq 0xa65ed(%rip), %rcx     # 0xca548
cmpq $0x6, %rcx
setl %cl
cmpl $0x0, 0xa65f7(%rip)     # 0xca560
setne %r9b
andb %cl, %r9b
shlq $0x4, %rax
xorl %r10d, %r10d
movslq 0x8(%rsi,%r10), %rdx
cmpq %rdx, %rdi
jl 0x23f95
movq (%rsi,%r10), %rcx
cmpq %rcx, %r8
setle %r11b
orb %r9b, %r11b
testb $0x1, %r11b
je 0x24005
addq $0x10, %r10
cmpq %r10, %rax
jne 0x23f77
jmp 0x24024
xorl %ebx, %ebx
movq %rsp, %rdi
movl $0x1, %esi
xorl %edx, %edx
callq 0x1f800
testl %eax, %eax
je 0x240b4
movl (%rsp), %ecx
movzbl %ch, %edi
andl $0x7f, %ecx
movl %ecx, %edx
shll $0x18, %edx
addl $0x1000000, %edx        # imm = 0x1000000
cmpl $0x2000000, %edx        # imm = 0x2000000
cmovgel %ecx, %ebx
cmpl 0xa6539(%rip), %eax     # 0xca518
jne 0x23fed
movl %ebx, %esi
callq 0x38581
jmp 0x240af
cmpl 0xa64b9(%rip), %eax     # 0xca4ac
jne 0x24099
movl %ebx, %esi
callq 0x4b43d
jmp 0x240af
leaq 0x707bf(%rip), %rsi     # 0x947cb
movl $0x2, %edi
xorl %eax, %eax
callq 0x23064
movq 0xa6511(%rip), %rdi     # 0xca530
callq 0x37660
movl 0xa6482(%rip), %eax     # 0xca4ac
andl 0xa64e8(%rip), %eax     # 0xca518
cmpl $-0x1, %eax
sete %cl
movl 0xa6450(%rip), %eax     # 0xca48c
testl %eax, %eax
setne %dl
andb %cl, %dl
cmpb $0x1, %dl
jne 0x240b4
movq 0xa6451(%rip), %rcx     # 0xca4a0
cmpq 0xa643a(%rip), %rcx     # 0xca490
jle 0x240b4
movq 0xa6439(%rip), %rsi     # 0xca498
cmpq $0x1, %rsi
adcq $0x0, %rsi
movslq %eax, %rdi
imulq $0x64, %rcx, %rax
cqto
idivq %rsi
addq $-0x64, %rax
cmpq %rdi, %rax
jl 0x240b4
leaq 0x7076c(%rip), %rsi     # 0x947ef
movl $0x2, %edi
movq %rax, %rdx
xorl %eax, %eax
callq 0x23064
callq 0x49ae1
jmp 0x240b4
movslq %eax, %rdx
leaq 0x706f8(%rip), %rsi     # 0x9479b
movl $0x3, %edi
xorl %eax, %eax
callq 0x23064
callq 0x23589
cmpq $0x0, 0xa640c(%rip)     # 0xca4c8
je 0x240c5
xorl %edi, %edi
callq 0x496c4
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa5ede(%rip)           # 0xc9fb0
cmpl $0x3e7, %eax            # imm = 0x3E7
jg 0x240f5
movl %eax, %ecx
movl 0xa5f1b(%rip), %esi     # 0xc9ffc
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl %ecx
movl %eax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x24105
cmpl $-0x1, 0xa6400(%rip)    # 0xca4fc
jne 0x24105
xorl %edi, %edi
callq 0x496c4
callq 0x2e697
callq 0x2ed93
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa5e94(%rip)           # 0xc9fb0
cmpl $0x3e7, %eax            # imm = 0x3E7
jg 0x2413f
movl %eax, %ecx
movl 0xa5ed1(%rip), %esi     # 0xc9ffc
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl %ecx
movl %eax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x24144
callq 0x359fb
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa5e5f(%rip)           # 0xc9fb0
cmpl $0x63, %eax
jg 0x24172
movl %eax, %ecx
movl 0xa5e9e(%rip), %esi     # 0xc9ffc
movl $0x64, %eax
xorl %edx, %edx
idivl %ecx
movl %eax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x24180
cmpl $0x0, 0xa65eb(%rip)     # 0xca764
je 0x24180
callq 0x53d88
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa5e23(%rip)           # 0xc9fb0
cmpl $0x63, %eax
jg 0x241ae
movl %eax, %ecx
movl 0xa5e62(%rip), %esi     # 0xc9ffc
movl $0x64, %eax
xorl %edx, %edx
idivl %ecx
movl %eax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x241bc
cmpl $0x0, 0xa5e77(%rip)     # 0xca02c
je 0x241bc
callq 0x6059b
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa5de7(%rip)           # 0xc9fb0
cmpl $0x3e7, %eax            # imm = 0x3E7
jg 0x241ec
movl %eax, %ecx
movl 0xa5e24(%rip), %esi     # 0xc9ffc
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl %ecx
movl %eax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x241f1
callq 0x55b2d
incl 0xa5e05(%rip)           # 0xc9ffc
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa5dac(%rip)           # 0xc9fb0
addq $0x10, %rsp
popq %rbx
popq %r14
popq %r15
retq
xorl %edi, %edi
callq 0x1f2b0