首页 > 系统相关 >Linux时间子系统1:gettimeofday和clock_gettime实现分析

Linux时间子系统1:gettimeofday和clock_gettime实现分析

时间:2024-06-13 15:03:46浏览次数:12  
标签:struct CLOCK gettime clock tv gettimeofday

1. Linux用户态获取时间的函数

a. 秒级别的时间函数:time和stime

time和stime函数的定义如下:

#include <time.h>

time_t time(time_t *t);

int stime(time_t *t);

        time函数返回了当前时间点到linux epoch的秒数(内核中timekeeper模块保存了这个值,timekeeper->xtime_sec)。stime是设定当前时间点到linux epoch的秒数。对于linux kernel,设定时间的进程必须拥有CAP_SYS_TIME的权利,否则会失败。

b. 微秒级别的时间函数:gettimeofday和settimeofday

#include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);

int settimeofday(const struct timeval *tv, const struct timezone *tz);

        这两个函数和上一小节秒数的函数类似,只不过时间精度可以达到微秒级别。gettimeofday函数可以获取从linux epoch到当前时间点的秒数以及微秒数

        显然,sys_gettimeofday和sys_settimeofday这两个系统调用是用来支持上面两个函数功能的,值得一提的是:这些系统调用在新的POSIX标准中 gettimeofday和settimeofday接口函数被标注为obsolescent,取而代之的是clock_gettime和clock_settime接口函数

        实际上上面的说法并不完全准确,在《Linux多线程服务端编程》一书5.1节中提到过,在x86-64的Linux上,gettimeofday不是系统调用,不会陷入内核。这种说法也有问题,因为gettimeofday确实是个系统调用,但是linux的vdso(virtual dynamic shared object)机制帮我们做到了在调用这些系统调用时不陷入内核,从而提高了性能。我们后面分析代码时会看到。

c. 纳秒级别的时间函数:clock_gettime和clock_settime

#include <time.h>

int clock_getres(clockid_t clk_id, struct timespec *res);

int clock_gettime(clockid_t clk_id, struct timespec *tp);

int clock_settime(clockid_t clk_id, const struct timespec *tp);

        如果不是clk_id这个参数,clock_gettime和clock_settime基本上是不用解释的,其概念和gettimeofday和settimeofday接口函数是完全类似的,除了精度是纳秒。Linux 5.10 定义了如下的clkid

/*
 * The IDs of the various system clocks (for POSIX.1b interval timers):
 */
#define CLOCK_REALTIME			0
#define CLOCK_MONOTONIC			1
#define CLOCK_PROCESS_CPUTIME_ID	2
#define CLOCK_THREAD_CPUTIME_ID		3
#define CLOCK_MONOTONIC_RAW		4
#define CLOCK_REALTIME_COARSE		5
#define CLOCK_MONOTONIC_COARSE		6
#define CLOCK_BOOTTIME			7
#define CLOCK_REALTIME_ALARM		8
#define CLOCK_BOOTTIME_ALARM		9

        但是以上ID并没有包含全部的clock类型,时钟类型,以及时间与时钟源的关系,我们后面再来分析

2. gettimeofday和clock_gettime的实现

a. gettimeofday的实现

        我们先看gettimeofday的实现,使用gettimeofday的示例代码如下:
 

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
  struct timeval tv_begin, tv_end;
  gettimeofday(&tv_begin, NULL);
  printf("start tv_sec %ld tv_usec %ld\n", tv_begin.tv_sec, tv_begin.tv_usec);
    
  usleep(1000);
  
  gettimeofday(&tv_end, NULL);
  printf("end tv_sec %ld tv_usec %ld\n", tv_end.tv_sec, tv_end.tv_usec);
}

在Linux kernel中,kernel/time/time.c目录下有如下代码:

SYSCALL_DEFINE2(gettimeofday, struct __kernel_old_timeval __user *, tv,
		struct timezone __user *, tz)
{
	if (likely(tv != NULL)) {
		struct timespec64 ts;

		ktime_get_real_ts64(&ts);
		if (put_user(ts.tv_sec, &tv->tv_sec) ||
		    put_user(ts.tv_nsec / 1000, &tv->tv_usec))
			return -EFAULT;
	}
	if (unlikely(tz != NULL)) {
		if (copy_to_user(tz, &sys_tz, sizeof(sys_tz)))
			return -EFAULT;
	}
	return 0;
}

如果不看gettimeofday的C库实现,肯定会认为gettimeofday就是直接使用上面的系统调用,实际上我一开始就是这么认为的。我们去glibc/musl看一下,这个函数在musl 1.2.3中的定义如下

int gettimeofday(struct timeval *restrict tv, void *restrict tz)
{
        struct timespec ts;
        if (!tv) return 0;
        clock_gettime(CLOCK_REALTIME, &ts);
        tv->tv_sec = ts.tv_sec;
        tv->tv_usec = (int)ts.tv_nsec / 1000;
        return 0;
}

gettimeofday并没有直接使用系统调用,而是调用了clock_gettime,并且clockid直接填写了CLOCK_REALTIME,那么接下来我们就要分析clock_gettime函数了。

b. clock_gettime的实现

再看musl 1.2.3中的clock_gettime的代码

int __clock_gettime(clockid_t clk, struct timespec *ts)
{
        int r;

#ifdef VDSO_CGT_SYM
        int (*f)(clockid_t, struct timespec *) =
                (int (*)(clockid_t, struct timespec *))vdso_func;
        if (f) {
                r = f(clk, ts);
                if (!r) return r;
                if (r == -EINVAL) return __syscall_ret(r);
                /* Fall through on errors other than EINVAL. Some buggy
                 * vdso implementations return ENOSYS for clocks they
                 * can't handle, rather than making the syscall. This
                 * also handles the case where cgt_init fails to find
                 * a vdso function to use. */
        }
#endif

#ifdef SYS_clock_gettime64
        r = -ENOSYS;
        if (sizeof(time_t) > 4)
                r = __syscall(SYS_clock_gettime64, clk, ts);
        if (SYS_clock_gettime == SYS_clock_gettime64 || r!=-ENOSYS)
                return __syscall_ret(r);
        long ts32[2];
        r = __syscall(SYS_clock_gettime, clk, ts32);
        if (r==-ENOSYS && clk==CLOCK_REALTIME) {
                r = __syscall(SYS_gettimeofday, ts32, 0);
                ts32[1] *= 1000;
        }
        if (!r) {
                ts->tv_sec = ts32[0];
                ts->tv_nsec = ts32[1];
                return r;
        }
        return __syscall_ret(r);
#else
        r = __syscall(SYS_clock_gettime, clk, ts);
        if (r == -ENOSYS) {
                if (clk == CLOCK_REALTIME) {
                        __syscall(SYS_gettimeofday, ts, 0);
                        ts->tv_nsec = (int)ts->tv_nsec * 1000;
                        return 0;
                }
                r = -EINVAL;
        }
        return __syscall_ret(r);
#endif
}

weak_alias(__clock_gettime, clock_gettime);

很明显有2个分支,我们先看第一个分支,包含宏定义VDSO_CGT_SYM,这里不详细介绍vdso了,放在后面单独讲,vdso简而言之就是为了避免系统调用的开销,使用内存映射的办法,将内核数据映射到用户空间。

那么数据是如何更新到vdso数据的呢?在内核的时间更新函数timekeeping_update函数中调用update_vsyscall更新了vdso数据结构

那么clock_gettime是否在所有情况下都能从用户态获取到时间呢,其实并不是,即使在使能了vdso的情况下,也还是有一些场景需要trap进内核,比如访问phc clock的时间。所以内核还是支持正常的系统调用,内核实现如下:

SYSCALL_DEFINE2(clock_gettime, const clockid_t, which_clock,
		struct __kernel_timespec __user *, tp)
{
	const struct k_clock *kc = clockid_to_kclock(which_clock);
	struct timespec64 kernel_tp;
	int error;

	if (!kc)
		return -EINVAL;

	error = kc->clock_get_timespec(which_clock, &kernel_tp);

	if (!error && put_timespec64(&kernel_tp, tp))
		error = -EFAULT;

	return error;
}

同样,我们可以看到根据clockid的不同可以获取到不同的时间,如下:

static const struct k_clock * const posix_clocks[] = {
	[CLOCK_REALTIME]		= &clock_realtime,
	[CLOCK_MONOTONIC]		= &clock_monotonic,
	[CLOCK_PROCESS_CPUTIME_ID]	= &clock_process,
	[CLOCK_THREAD_CPUTIME_ID]	= &clock_thread,
	[CLOCK_MONOTONIC_RAW]		= &clock_monotonic_raw,
	[CLOCK_REALTIME_COARSE]		= &clock_realtime_coarse,
	[CLOCK_MONOTONIC_COARSE]	= &clock_monotonic_coarse,
	[CLOCK_BOOTTIME]		= &clock_boottime,
	[CLOCK_REALTIME_ALARM]		= &alarm_clock,
	[CLOCK_BOOTTIME_ALARM]		= &alarm_clock,
	[CLOCK_TAI]			= &clock_tai,
};

这里的时间的含义是什么,我们获取到的是什么时间,这个问题下面再讨论。

3. 遗留问题

a. vdso的机制:vdso是如何让用户态不必陷入到内核获取到时间的?

b. clock_gettime能够获取到的各类时间有什么不同?

这两个问题可参考下一篇:Linux时间子系统2: clock_gettime的VDSO机制分析-CSDN博客

标签:struct,CLOCK,gettime,clock,tv,gettimeofday
From: https://blog.csdn.net/Bluetangos/article/details/136721196

相关文章

  • 倒计时:日期对象.getTime();获取当前时间戳
    <!DOCTYPEhtml><htmllang="en"><head> <metacharset="UTF-8"> <title>Document</title></head><body> <h1></h1> <scripttype="text/javascript"> //现在到202......
  • 【Xilinx约束】使用set_clock_groups 约束语法处理异步时钟域
            在XilinxVivado环境中,set_clock_groups约束用于定义时钟组,以确保工具在布局和布线时考虑时钟之间的关联性。这对于跨时钟域的设计和时序优化非常重要。                使用set_clock_groups约束语法处理异步时钟域有不同的方式,适用于不......
  • [转帖]Unnecessary GCLocker-initiated young GCs
    https://www.cnblogs.com/zhangshengdong/p/9196128.html DetailsType: BugResolution:FixedPriority: P3FixVersion/s:14AffectsVersion/s:7u60, 8, 8u20, 8u40, 9, 11, 13Component/s:hotspotLabels:8u20-defer-SQE-OK 8u20......
  • Clock Switch,芯片时钟切换的毛刺是什么,如何消除
    背景芯片运行过程中需要时钟切换时,要考虑到是否会产生glitch,小小的glitch有可能导致电路运行的错误。所以时钟切换时需要特别的处理。直接使用MUX进行时钟切换或者采用如下电路结构进行时钟切换:assignoutclock=(clk1&select)|(~select&clk0);或assignoutclock=......
  • SystemVerilog -- 6.4 Interface ~ Clocking Block Part II
    SystemVerilogClockingBlockPartII时钟模块允许在指定的时钟事件对输入进行采样并驱动输出。如果提到时钟模块的输入skew,则该模块中的所有输入信号都将在时钟事件之前以skew时间单位进行采样。如果提到时钟模块的输出skew,则该模块中的输出信号都将在相应的时钟事件之后以ske......
  • SystemVerilog -- 6.4 Interface ~ Clocking Blocks
    SystemVerilogClockingBlocks默认情况下,模块端口和接口不指定信号之间的任何时序要求或同步方案。在clocking和endclocking之间定义的时钟块正是这样做的。它是与特定时钟同步的信号集合,有助于指定时钟和信号之间的定时要求。这将允许测试编写者更多地关注事务,而不是担心信号......
  • CLOCK_MONOTONIC 与 CLOCK_REALTIME 区别
    CLOCK_MONOTONIC指的是monotonictime,而CLOCK_REALTIME指的是walltime。monotonictime的字面意思是单调时间,实际上,指的是系统启动之后所流逝的时间,这是由变量jiffies来记录的,当系统每次启动时,jiffies被初始化为0,在每一个timerinterrupt到来时,变量jiffies就加上......
  • 12-hour clock
    Createasetofcounterssuitableforuseasa12-hourclock(witham/pmindicator).Yourcountersareclockedbyafast-runningclk,withapulseonenawheneveryourclockshouldincrement(i.e.,oncepersecond).resetresetstheclockto12:00AM.pm......
  • STM32第九节(中级篇):RCC(第二节)——讲解系统时钟配置函数SetSysClockTo72
    目录前言STM32第九节(中级篇):RCC(第二节)——讲解系统时钟配置函数SetSysClockTo72代码内容位置及检索分析代码 代码展示时钟控制使能闪存控制寄存器配置AHP,APB1,APB2的总线时钟配置锁相环时钟 超频操作小结前言    上节课我们讲了理论部分,那么我们这节课......
  • 鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之TextClock组件
    鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之TextClock组件一、操作环境操作系统: Windows10专业版、IDE:DevEcoStudio3.1、SDK:HarmonyOS3.1+编辑二、TextClock组件TextClock组件通过文本将当前系统时间显示在设备上。支持不同时区的时间显示,最高精度到秒级。子组件无。接口TextClock......