// File: /workspace/github_c_makefile_star2_O2/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 %rbp
pushq %r15
pushq %r14
pushq %rbx
pushq %rax
movl 0xa47e1(%rip), %edi     # 0xc77e0
testl %edi, %edi
je 0x23008
callq 0x4a328
callq 0x22fd5
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3f96(%rip)           # 0xc6fb0
cmpl $0x63, %eax
jg 0x2303c
movl %eax, %ecx
movl 0xa3fd5(%rip), %esi     # 0xc6ffc
movw $0x64, %ax
xorl %edx, %edx
idivw %cx
movswl %ax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x23041
callq 0x22d1b
callq 0x22d04
movzbl 0xa3f8e(%rip), %ecx     # 0xc6fdb
shll $0x18, %ecx
orl %eax, %ecx
movl %ecx, 0xa3f80(%rip)     # 0xc6fd8
callq 0x28434
cmpq 0xa42bc(%rip), %rax     # 0xc7320
jbe 0x23072
callq 0x28434
movq %rax, 0xa42ae(%rip)     # 0xc7320
callq 0x28458
movq %rax, 0xa42f2(%rip)     # 0xc7370
cmpl $0x0, 0xa3f57(%rip)     # 0xc6fdc
je 0x230ae
xorl %edi, %edi
callq 0x2577d
testl %eax, %eax
je 0x2350f
leaq 0x67646(%rip), %rsi     # 0x8a6e3
pushq $0x3
popq %rdi
xorl %eax, %eax
callq 0x22613
andl $0x0, 0xa3f2e(%rip)     # 0xc6fdc
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3ef5(%rip)           # 0xc6fb0
movl %eax, %ecx
movl 0xa3f39(%rip), %esi     # 0xc6ffc
movw $0x1388, %ax            # imm = 0x1388
xorl %edx, %edx
idivw %cx
movswl %ax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
je 0x2325d
cmpl $0x0, 0xa3f49(%rip)     # 0xc702c
jne 0x23147
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3ebe(%rip)           # 0xc6fb0
movl %eax, %ecx
movl 0xa3f02(%rip), %esi     # 0xc6ffc
movw $0x1388, %ax            # imm = 0x1388
xorl %edx, %edx
idivw %cx
movswl %ax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x23147
movq 0xa4042(%rip), %rax     # 0xc7158
movq 0x28(%rax), %rbx
movq 0xa4047(%rip), %rax     # 0xc7168
movq 0x28(%rax), %r14
subq %r14, %rbx
callq 0x28434
leaq 0x67642(%rip), %rsi     # 0x8a776
pushq $0x1
popq %rdi
movq %rbx, %rdx
movq %r14, %rcx
movq %rax, %r8
xorl %eax, %eax
callq 0x22613
callq 0x22ed0
callq 0x22f3e
movl 0xa43c1(%rip), %ecx     # 0xc7518
movl 0xa434f(%rip), %eax     # 0xc74ac
cmpl $-0x1, %ecx
jne 0x23181
cmpl $-0x1, %eax
jne 0x23181
cmpl $0x0, 0xa433a(%rip)     # 0xc74a8
je 0x23181
callq 0x4605f
movl 0xa439d(%rip), %ecx     # 0xc7518
movl 0xa432b(%rip), %eax     # 0xc74ac
cmpl $-0x1, %ecx
jne 0x2320e
cmpl $-0x1, %eax
jne 0x2320e
movl 0xa4393(%rip), %eax     # 0xc7528
movq 0xa4384(%rip), %rsi     # 0xc7520
movq 0xa459d(%rip), %rcx     # 0xc7740
movq %rcx, %rdi
subq 0xa4393(%rip), %rdi     # 0xc7540
subq 0xa4394(%rip), %rcx     # 0xc7548
cmpq $0x6, %rcx
setl %cl
cmpl $0x0, 0xa439e(%rip)     # 0xc7560
movq 0xa433f(%rip), %r8      # 0xc7508
setne %r9b
andb %cl, %r9b
xorl %r10d, %r10d
testl %eax, %eax
cmovlel %r10d, %eax
shlq $0x4, %rax
cmpq %r10, %rax
je 0x232ce
movslq 0x8(%rsi,%r10), %rdx
cmpq %rdx, %r8
jl 0x23208
movq (%rsi,%r10), %rcx
cmpq %rcx, %rdi
setle %r11b
orb %r9b, %r11b
testb $0x1, %r11b
je 0x232d2
addq $0x10, %r10
jmp 0x231dd
xorl %ebx, %ebx
leaq 0x4(%rsp), %rdi
pushq $0x1
popq %rsi
xorl %edx, %edx
callq 0x1f800
testl %eax, %eax
je 0x2338c
movl 0x4(%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 0xa42cd(%rip), %eax     # 0xc7518
jne 0x23362
movl %ebx, %esi
callq 0x35db8
jmp 0x23387
pushq $0x8
popq %r15
movl 0xa41c1(%rip), %eax     # 0xc7428
leaq 0x674d5(%rip), %rbx     # 0x8a743
pushq $0x1
popq %rbp
xorl %r14d, %r14d
movslq %eax, %rcx
cmpq %rcx, %r14
jge 0x230dc
movq 0xa3d31(%rip), %rcx     # 0xc6fb8
movq -0x8(%rcx,%r15), %rdx
movq (%rcx,%r15), %rsi
movq 0x48(%rdx), %rcx
addq 0x28(%rdx), %rcx
movq 0x48(%rsi), %r8
addq 0x28(%rsi), %r8
movq %rcx, %rsi
orq %r8, %rsi
je 0x232c5
movq 0x38(%rdx), %r9
addq 0x18(%rdx), %r9
movl %ebp, %edi
movq %rbx, %rsi
movl %r14d, %edx
xorl %eax, %eax
callq 0x22613
movl 0xa4163(%rip), %eax     # 0xc7428
incq %r14
addq $0x40, %r15
jmp 0x23274
movb $0x1, %cl
jmp 0x23301
leaq 0x67502(%rip), %rsi     # 0x8a7db
pushq $0x2
popq %rdi
xorl %eax, %eax
callq 0x22613
movq 0xa4246(%rip), %rdi     # 0xc7530
callq 0x350c8
movl 0xa41b7(%rip), %eax     # 0xc74ac
andl 0xa421d(%rip), %eax     # 0xc7518
cmpl $-0x1, %eax
sete %cl
movl 0xa4185(%rip), %eax     # 0xc748c
testl %eax, %eax
setne %dl
andb %cl, %dl
cmpb $0x1, %dl
jne 0x2338c
movq 0xa4186(%rip), %rcx     # 0xc74a0
cmpq 0xa416f(%rip), %rcx     # 0xc7490
jle 0x2338c
movq 0xa416e(%rip), %rsi     # 0xc7498
cmpq $0x1, %rsi
adcq $0x0, %rsi
movslq %eax, %rdi
imulq $0x64, %rcx, %rax
cqto
idivq %rsi
addq $-0x64, %rax
cmpq %rdi, %rax
jl 0x2338c
leaq 0x674b1(%rip), %rsi     # 0x8a7ff
pushq $0x2
popq %rdi
movq %rax, %rdx
xorl %eax, %eax
callq 0x22613
callq 0x4605f
jmp 0x2338c
cmpl 0xa4144(%rip), %eax     # 0xc74ac
jne 0x23373
movl %ebx, %esi
callq 0x476d1
jmp 0x23387
movslq %eax, %rdx
leaq 0x6742e(%rip), %rsi     # 0x8a7ab
pushq $0x3
popq %rdi
xorl %eax, %eax
callq 0x22613
callq 0x22a8d
cmpq $0x0, 0xa4134(%rip)     # 0xc74c8
je 0x2339d
xorl %edi, %edi
callq 0x45c80
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3c06(%rip)           # 0xc6fb0
cmpl $0x3e7, %eax            # imm = 0x3E7
jg 0x233ce
movl %eax, %ecx
movl 0xa3c43(%rip), %esi     # 0xc6ffc
movw $0x3e8, %ax             # imm = 0x3E8
xorl %edx, %edx
idivw %cx
movswl %ax, %ecx
movl %esi, %eax
cltd
idivl %ecx
testl %edx, %edx
jne 0x233de
cmpl $-0x1, 0xa4127(%rip)    # 0xc74fc
jne 0x233de
xorl %edi, %edi
callq 0x45c80
callq 0x2cf07
callq 0x2d5a3
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3bbb(%rip)           # 0xc6fb0
cmpl $0x3e7, %eax            # imm = 0x3E7
jg 0x23419
movl %eax, %ecx
movl 0xa3bf8(%rip), %esi     # 0xc6ffc
movw $0x3e8, %ax             # imm = 0x3E8
xorl %edx, %edx
idivw %cx
movswl %ax, %edi
movl %esi, %eax
cltd
idivl %edi
testl %edx, %edx
jne 0x2342d
callq 0x33b5e
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3b85(%rip)           # 0xc6fb0
movl %eax, %ecx
cmpl $0x63, %ecx
jle 0x2343d
cmpl $0x0, 0xa432b(%rip)     # 0xc7764
jne 0x23461
jmp 0x2347a
movl 0xa3bb9(%rip), %esi     # 0xc6ffc
movw $0x64, %ax
xorl %edx, %edx
idivw %cx
movswl %ax, %edi
movl %esi, %eax
cltd
idivl %edi
testl %edx, %edx
jne 0x23485
cmpl $0x0, 0xa4305(%rip)     # 0xc7764
je 0x23485
callq 0x4f488
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3b3d(%rip)           # 0xc6fb0
movl %eax, %ecx
cmpl $0x63, %eax
jle 0x23485
cmpl $0x0, 0xa3bab(%rip)     # 0xc702c
jne 0x234a9
jmp 0x234bd
movl 0xa3b71(%rip), %esi     # 0xc6ffc
movw $0x64, %ax
xorl %edx, %edx
idivw %cx
movswl %ax, %edi
movl %esi, %eax
cltd
idivl %edi
testl %edx, %edx
jne 0x234c5
cmpl $0x0, 0xa3b85(%rip)     # 0xc702c
je 0x234c5
callq 0x5b1c0
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3af5(%rip)           # 0xc6fb0
movl %eax, %ecx
cmpl $0x3e7, %ecx            # imm = 0x3E7
jg 0x234e0
movl 0xa3b31(%rip), %esi     # 0xc6ffc
movw $0x3e8, %ax             # imm = 0x3E8
xorl %edx, %edx
idivw %cx
movswl %ax, %edi
movl %esi, %eax
cltd
idivl %edi
testl %edx, %edx
jne 0x234fa
callq 0x511a9
movl 0xa3b11(%rip), %esi     # 0xc6ffc
movl $0x3e8, %eax            # imm = 0x3E8
xorl %edx, %edx
idivl 0xa3ab8(%rip)           # 0xc6fb0
movl %eax, %ecx
incl %esi
movl %esi, 0xa3afa(%rip)     # 0xc6ffc
movl %ecx, %eax
addq $0x8, %rsp
popq %rbx
popq %r14
popq %r15
popq %rbp
retq
xorl %edi, %edi
callq 0x1f2b0