Linux时间管理之hardware

系统 Linux
一直以来对Linux下的时间管理知之不详,GFree_wind在微博发起过几次Linux下时钟的讨论,和Godbach这些大牛比,我完全插不上话,因为不懂。近来闲暇时间研究了下Linux下的时间管理,分享出来,请大家指正。

一直以来对Linux下的时间管理知之不详,GFree_wind在微博发起过几次Linux下时钟的讨论,和Godbach这些大牛比,我完全插不上话,因为不懂。近来闲暇时间研究了下Linux下的时间管理,分享出来,请大家指正。

从我们大白话的角度想,时间管理其实分成两部分,就像我们小时候学习物理的时候物理老师不断强调时间和时刻的区别。一个是时刻,比如现在是20:44:37秒,指的是时刻,我们手机上看时间,指的也是时刻。另一块是时间,比如说,我每天工作八小时,再比如说,半小时之后,我要出门了,结束时间指向的是未来,但是仍然是一段时间。OK。无论是时刻还是时望间,都是需要硬件支持的,你手里只有一块最小刻度只有1秒的手表,就不要指用这块手表给百米大赛度量成绩了,何哉,硬件太挫。Linux也是如此,之所以Linux启动之后,可以精确的计时,那是因为Linux的下面有相应的硬件为依托。  

RTC


RTC,real time clock,实时时钟和其他的硬件是不同的,RTC吐出来的是时刻,而其他硬件时钟吐出来的是时间。也就是说,RTC能告诉我们,当前是2013年9月12日,21:49:38,但是其他的硬件如TSC,PIT,HPET只能告诉我们,我应该走过了XX个cycle,按照我的频率,已经过去了10分钟了。

为啥RTC这么牛X,可以告诉我们当前时刻,哪怕用户关了机?以X86为例,RTC是主板上的一块CMOS芯片,哪怕你的Linux关了机,她也可以依赖主板上的电池维持时钟的准确。当然了,在Linux下,RTC存储的是UTC时间,而不会考虑timezone。

所以,Linux启动的时候,一定会拜访RTC来获得当前的时刻值,尽管精度不高(精确到秒)。When and How?

首先回答When。Linux启动的时候,start_kernel有四大time相关的函数调用:

  1. init_timers();
  2. hrtimers_init();
  3. timekeeping_init()
  4. time_init();

从RTC中读取当前的UTC时间是timekeeping_init中做的事情,调用路径如下:

 timekeeping_init

|___________read_persistent_clock    (arch/x86/kernel/rtc.c)

            |_____x86_platform.get_wallclock()

            |_____mach_get_cmos_time  (arch/x86/kernel/x86_init.c)

 

  1. /************arch/x86/kernel/rtc.c*****************/ 
  2. void read_persistent_clock(struct timespec *ts) 
  3.     unsigned long retval; 
  4.   
  5.     retval = x86_platform.get_wallclock(); 
  6.   
  7.     ts->tv_sec = retval
  8.     ts->tv_nsec = 0
  9.   
  10. /*****************arch/x86/kernel/x86_init.c ****************/ 
  11.   
  12. struct x86_platform_ops x86_platform = { 
  13.     .calibrate_tsc = native_calibrate_tsc
  14.     .wallclock_init = wallclock_init_noop
  15.     .get_wallclock = mach_get_cmos_time
  16.     .set_wallclock = mach_set_rtc_mmss
  17.     .iommu_shutdown = iommu_shutdown_noop
  18.     .is_untracked_pat_range = is_ISA_range
  19.     .nmi_init = default_nmi_init
  20.     .get_nmi_reason = default_get_nmi_reason
  21.     .i8042_detect = default_i8042_detect
  22.     .save_sched_clock_state = tsc_save_sched_clock_state
  23.     .restore_sched_clock_state = tsc_restore_sched_clock_state

对于我们而言,我们要读的function是mach_get_cmos_time

  1. unsigned long mach_get_cmos_time(void) 
  2.     unsigned int status, year, mon, day, hour, min, sec, century = 0
  3.     unsigned long flags; 
  4.   
  5.     spin_lock_irqsave(&rtc_lock, flags); 
  6.   
  7.     /* 
  8.      * If UIP is clear, then we have >= 244 microseconds before 
  9.      * RTC registers will be updated. Spec sheet says that this 
  10.      * is the reliable way to read RTC - registers. If UIP is set 
  11.      * then the register access might be invalid. 
  12.      */ 
  13.     while ((CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP)) 
  14.         cpu_relax(); 
  15.   
  16.     sec = CMOS_READ(RTC_SECONDS); 
  17.     min = CMOS_READ(RTC_MINUTES); 
  18.     hour = CMOS_READ(RTC_HOURS); 
  19.     day = CMOS_READ(RTC_DAY_OF_MONTH); 
  20.     mon = CMOS_READ(RTC_MONTH); 
  21.     year = CMOS_READ(RTC_YEAR); 
  22.   
  23. #ifdef CONFIG_ACPI 
  24.     if (acpi_gbl_FADT.header.revision >= FADT2_REVISION_ID && 
  25.      acpi_gbl_FADT.century) 
  26.         century = CMOS_READ(acpi_gbl_FADT.century); 
  27. #endif 
  28.   
  29.     status = CMOS_READ(RTC_CONTROL); 
  30.     WARN_ON_ONCE(RTC_ALWAYS_BCD && (status & RTC_DM_BINARY)); 
  31.   
  32.     spin_unlock_irqrestore(&rtc_lock, flags); 
  33.   
  34.     if (RTC_ALWAYS_BCD || !(status & RTC_DM_BINARY)) { 
  35.         sec = bcd2bin(sec); 
  36.         min = bcd2bin(min); 
  37.         hour = bcd2bin(hour); 
  38.         day = bcd2bin(day); 
  39.         mon = bcd2bin(mon); 
  40.         year = bcd2bin(year); 
  41.     } 
  42.   
  43.     if (century) { 
  44.         century = bcd2bin(century); 
  45.         year += century * 100; 
  46.         printk(KERN_INFO "Extended CMOS year: %d\n", century * 100); 
  47.     } else 
  48.         year += CMOS_YEARS_OFFS; 
  49.   
  50.     return mktime(year, mon, day, hour, min, sec); 

这一段代码已经牵扯到了硬件相关的编程,我们其实并不关心驱动,对于硬件比较感兴趣的筒子,可以访问http://xenyinzen.wikidot.com/reship:080225-2

获得更多更详细的信息。mktime是将年月日时分秒组装成1970年1月1日00:00:00这个UNIX基准时间以来的秒数。我们在Linux下可以通过一下方式获得这个值:

  1. root@manu:/sys/class/rtc/rtc0# date +%s ;cat /sys/class/rtc/rtc0/since_epoch  
  2. 1379081060 
  3. 1379081060 

既然Linux上电的时候,可以从RTC中读出当前的时间,我们也可以设置时间,并且写入到RTC。用户层也可以操作RTC硬件时钟,通过ioctl。下面给出一个样例: 

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <linux/rtc.h>  
  4. #include <fcntl.h> 
  5. #include <sys/ioctl.h> 
  6.   
  7. int main(int argc,char *argv[]) 
  8.     int retval,fd; 
  9.     struct rtc_time rtc_tm; 
  10.   
  11.     fd=open("/dev/rtc",O_RDONLY);  
  12.     if(fd==-1) 
  13.     { 
  14.         perror("error open /dev/rtc"); 
  15.         return -1; 
  16.     } 
  17.   
  18.     retval=ioctl(fd,RTC_RD_TIME,&rtc_tm); 
  19.     if(retval==-1) 
  20.     { 
  21.         perror("error exec RTC_RD_TIME ioctl"); 
  22.         return -2; 
  23.     } 
  24.     printf("RTC time is %d-%d-%d %d:%d:%d \n", 
  25.            rtc_tm.tm_year+1900,rtc_tm.tm_mon,rtc_tm.tm_mday, 
  26.            rtc_tm.tm_hour,rtc_tm.tm_min,rtc_tm.tm_sec); 
  27.   
  28.     close(fd); 
  29.   
  30.     return 0; 

输出如下:   

  1. root@manu:~/code/c/self/rtc# ./rtc_test  
  2. RTC time is 2013-8-14 15:46:2 

对于set RTC 也可以通过ioctl RTC_SET_TIME参数来实现,我就不多说了,对这部分感兴趣的,可以自行man rtc,或者Kernel的Documentation/rtc.txt有一个示例代码,比较详细。

已经说过了,RTC在时间相关的硬件中是个独树一帜的奇葩,作用和其他的硬件不同。而其他的硬件只是以一定的频率产生时钟中断,帮助OS完成计时。前面我也提到过,你手里拿着个手表,就不要指望给百米大赛计时,原因就是精度太低。硬件也是如此,有精度高的有精度低的。Linux操作系统抽象出了clocksource(时钟源)来管理这些硬件。Linux会在所有的硬件时钟中选择出精度最高作为当前在用的时钟源。

如何查看当前所有的可用的时钟源已经当前在用的时钟源呢? 

  1. manu@manu:/$ cat /sys/devices/system/clocksource/clocksource0/available_clocksource  
  2. tsc hpet acpi_pm  
  3. manu@manu:/$ cat /sys/devices/system/clocksource/clocksource0/current_clocksource  
  4. tsc 

我们分别介绍hpet,acpi_pm,tsc,不过在这之前,先介绍一个PIT

#p#

PIT


PIT全称Programmable Interval Timer,是出现比较早的,比较菜的硬件。这种设备有8253/8254,对底层感兴趣的可以读drivers/clocksource/i8253.c,这种硬件的频率是1MHZ左右:

  1. #define PIT_TICK_RATE 1193182ul 

PIT为啥没有落在available_clocksource中呢,因为后起之秀HPET的存在。Kernel中发现可以使用HPET,就不会用PIT作为始终源了。后面我们会分析到。

HPET


PIT 的精度较低,HPET 被设计来替代 PIT 提供高精度时钟中断(至少 10MHz)。它是由微软和 Intel 联合开发的。一个 HPET 包括了一个固定频率的数值增加的计数器以及 3 到 32 个独立的计时器,这每一个计时器有包涵了一个比较器和一个寄存器(保存一个数值,表示触发中断的时机)。每一个比较器都比较计数器中的数值和寄存器的数值,相等就会产生中断。

HPET这个时钟源的检测和注册是在前文提到的四大初始化中的最后一个:time_init   

 time_init

|________________x86_late_time_init

                 |_________x86_init.timers.timer_init (arch/x86/kernel/x86_init.c)

                           |________hpet_time_init

                                    |_____hpet_enable

                                          |____hpet_clocksource_register

                                    |_____set_default_time_irq 

|________________tsc_init

                 |________x86_platform.calibrate_tsc (x86_init.c)

                        |______native_calibrate_tsc

                               |___quit_pit_calibrate

在这个时候我们看到,time_init主要是两个部分,TSC是一个,HPET(PIT)是一个。

  1. static struct irqaction irq0 = { 
  2.     .handler = timer_interrupt
  3.     .flags = IRQF_DISABLED | IRQF_NOBALANCING | IRQF_IRQPOLL | IRQF_TIMER, 
  4.     .name = "timer" 
  5. }; 
  6.   
  7. void __init setup_default_timer_irq(void) 
  8.     setup_irq(0, &irq0); 
  9.   
  10. /* Default timer init function */ 
  11. void __init hpet_time_init(void) 
  12.     if (!hpet_enable()
  13.         setup_pit_timer()
  14.     setup_default_timer_irq(); 
  15.   
  16. static __init void x86_late_time_init(void) 
  17.     x86_init.timers.timer_init();  
  18.     tsc_init(); //TSC part 
  19.   
  20. /* 
  21.  * Initialize TSC and delay the periodic timer init to 
  22.  * late x86_late_time_init() so ioremap works. 
  23.  */ 
  24. void __init time_init(void) 
  25.     late_time_init = x86_late_time_init

从上面加粗的部分可以看到,当HPET可以enable的时候,我们就不用PIT作为时钟源了,原因是HPET频率高,精度高。

从我的笔记本Linux的dmesg可看到:

 [ 0.664201] hpet0: 8 comparators, 64-bit 14.318180 MHz counter

我的笔记本的HPET,频率是14.318180MHz。

讲到这里,就不得不讲clocksource。Linux将真实的时钟做了抽象,用数据结构clocksource来管理这些硬件时钟源。

  1. /** 
  2.  * struct clocksource - hardware abstraction for a free running counter 
  3.  *    Provides mostly state-free accessors to the underlying hardware. 
  4.  *    This is the structure used for system time. 
  5.  * 
  6.  * @name:        ptr to clocksource name 
  7.  * @list:        list head for registration 
  8.  * @rating:        rating value for selection (higher is better) 
  9.  *            To avoid rating inflation the following 
  10.  *            list should give you a guide as to how 
  11.  *            to assign your clocksource a rating 
  12.  *            1-99: Unfit for real use 
  13.  *                Only available for bootup and testing purposes. 
  14.  *            100-199: Base level usability. 
  15.  *                Functional for real use, but not desired. 
  16.  *            200-299: Good. 
  17.  *                A correct and usable clocksource. 
  18.  *            300-399: Desired. 
  19.  *                A reasonably fast and accurate clocksource. 
  20.  *            400-499: Perfect 
  21.  *                The ideal clocksource. A must-use where 
  22.  *                available. 
  23.  * @read:        returns a cycle value, passes clocksource as argument 
  24.  * @enable:        optional function to enable the clocksource 
  25.  * @disable:        optional function to disable the clocksource 
  26.  * @mask:        bitmask for two's complement 
  27.  *            subtraction of non 64 bit counters 
  28.  * @mult:        cycle to nanosecond multiplier 
  29.  * @shift:        cycle to nanosecond pisor (power of two) 
  30.  * @max_idle_ns:    max idle time permitted by the clocksource (nsecs) 
  31.  * @maxadj:        maximum adjustment value to mult (~11%) 
  32.  * @flags:        flags describing special properties 
  33.  * @archdata:        arch-specific data 
  34.  * @suspend:        suspend function for the clocksource, if necessary 
  35.  * @resume:        resume function for the clocksource, if necessary 
  36.  * @cycle_last:        most recent cycle counter value seen by ::read() 
  37.  */ 
  38. struct clocksource { 
  39.     /* 
  40.      * Hotpath data, fits in a single cache line when the 
  41.      * clocksource itself is cacheline aligned. 
  42.      */ 
  43.     cycle_t (*read)(struct clocksource *cs); 
  44.     cycle_t cycle_last; 
  45.     cycle_t mask; 
  46.     u32 mult; 
  47.     u32 shift; 
  48.     u64 max_idle_ns; 
  49.     u32 maxadj; 
  50. #ifdef CONFIG_ARCH_CLOCKSOURCE_DATA 
  51.     struct arch_clocksource_data archdata; 
  52. #endif 
  53.   
  54.     const char *name; 
  55.     struct list_head list; 
  56.     int rating; 
  57.     int (*enable)(struct clocksource *cs); 
  58.     void (*disable)(struct clocksource *cs); 
  59.     unsigned long flags; 
  60.     void (*suspend)(struct clocksource *cs); 
  61.     void (*resume)(struct clocksource *cs); 
  62.   
  63.     /* private: */ 
  64. #ifdef CONFIG_CLOCKSOURCE_WATCHDOG 
  65.     /* Watchdog related data, used by the framework */ 
  66.     struct list_head wd_list; 
  67.     cycle_t cs_last; 
  68.     cycle_t wd_last; 
  69. #endif 
  70. } ____cacheline_aligned;     

很重要的一个参数是rating时钟源分优劣,精度越高的时钟源的,rating值越大。从注释中我们可以看到:

  • 1--99: 不适合于用作实际的时钟源,只用于启动过程或用于测试;
  • 100--199:基本可用,可用作真实的时钟源,但不推荐;
  • 200--299:精度较好,可用作真实的时钟源;
  • 300--399:很好,精确的时钟源;
  • 400--499:理想的时钟源,如有可能就必须选择它作为时钟源;
  1. static struct clocksource clocksource_hpet = { 
  2.     .name = "hpet"
  3.     .rating = 250
  4.     .read = read_hpet
  5.     .mask = HPET_MASK
  6.     .flags = CLOCK_SOURCE_IS_CONTINUOUS
  7.     .resume = hpet_resume_counter
  8. #ifdef CONFIG_X86_64 
  9.     .archdata = { .vclock_mode = VCLOCK_HPET }, 
  10. #endif 
  11. }; 

从rating上HPET的rating是250,已经很不错了,为什么最终选择了TSC,available_clocksource中的acpi_pm又是什么?    

#p#

ACPI_PM


这个是传说中的ACPI Power Management Time,这个其实我也知之不详,对这个感兴趣的可以去找下CU的彭东,这小子写OS,应该会经常和这种硬件纠缠不清。到了硬件驱动层,我水平基本温饱线以下。

  1. #define PMTMR_TICKS_PER_SEC 3579545 
  2.   
  3.  66 static struct clocksource clocksource_acpi_pm = { 
  4.           .name = "acpi_pm"
  5.           .rating = 200
  6.           .read = acpi_pm_read
  7.           .mask = (cycle_t)ACPI_PM_MASK, 
  8.           .mult = 0, /*to be calculated*/ 
  9.           .shift = 22
  10.           .flags = CLOCK_SOURCE_IS_CONTINUOUS
  11.   
  12.  }; 
  13. fs_initcall(init_acpi_pm_clocksource) 

我们看到了频率在3Mhz这个级别,rating是200,低于HPET。至于初始化在fs_initcall这一步做。

TSC


TSC是Time Stamp Counter。CPU 执行指令需要一个外部振荡器产生时钟信号,从 CLK 管脚输入。x86 提供了一个 TSC 寄存器,该寄存器的值在每次收到一个时钟信号时加一。比如 CPU 的主频为 1GHZ,则每一秒时间内,TSC 寄存器的值将增加 1G 次,或者说每一个纳秒加一次。x86 还提供了 rtdsc 指令来读取该值,因此 TSC 也可以作为时钟设备。TSC 提供了比 RTC 更高精度的时间,即纳秒级的时间精度。这个很牛X,看时钟频率是和CPU的频率一个水平线的。远远超过HPET,PIT这些小鱼小虾米。看下我的笔记本的TSC 频率:

  1. manu@manu:~/code/c/classical/linux-3.4.61$ dmesg |grep Detected 
  2. [ 0.004000] Detected 2127.727 MHz processor. 
  3.   
  4. manu@manu:~$ cat /proc/cpuinfo  
  5. processor   : 0 
  6. vendor_id   : GenuineIntel 
  7. cpu family  : 6 
  8. model    : 37 
  9. model name  : Intel(R) Core(TM) i3 CPU       M 330  @ 2.13GHz 
  10.   
  11. 。。。。。 

看这时钟频率,相当的吓人,看下clocksource的rating:

  1. static struct clocksource clocksource_tsc = { 
  2.     .name = "tsc"
  3.     .rating = 300
  4.     .read = read_tsc
  5.     .resume = resume_tsc
  6.     .mask = CLOCKSOURCE_MASK(64), 
  7.     .flags = CLOCK_SOURCE_IS_CONTINUOUS | 
  8.                   CLOCK_SOURCE_MUST_VERIFY, 
  9. #ifdef CONFIG_X86_64 
  10.     .archdata = { .vclock_mode = VCLOCK_TSC }, 
  11. #endif 
  12. }; 

TSC的init和register分别在tsc_init和init_tsc_clocksource中进行

 time_init

|________________x86_late_time_init

                 |_________x86_init.timers.timer_init (arch/x86/kernel/x86_init.c)

                           |________hpet_time_init

                                    |_____hpet_enable

                                          |____hpet_clocksource_register

                                    |_____set_default_time_irq 

|________________tsc_init

                 |________x86_platform.calibrate_tsc (x86_init.c)

                        |______native_calibrate_tsc

                               |___quit_pit_calibrate

 

 

  1. static int __init init_tsc_clocksource(void) 
  2.     if (!cpu_has_tsc || tsc_disabled > 0 || !tsc_khz) 
  3.         return 0; 
  4.  
  5.     if (tsc_clocksource_reliable) 
  6.         clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY; 
  7.     /* lower the rating if we already know its unstable: */ 
  8.     if (check_tsc_unstable()) { 
  9.         clocksource_tsc.rating = 0
  10.         clocksource_tsc.flags &= ~CLOCK_SOURCE_IS_CONTINUOUS; 
  11.     } 
  12.  
  13.     /* 
  14.      * Trust the results of the earlier calibration on systems 
  15.      * exporting a reliable TSC. 
  16.      */ 
  17.     if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE)) { 
  18.         clocksource_register_khz(&clocksource_tsc, tsc_khz); 
  19.         return 0; 
  20.     } 
  21.   
  22.     schedule_delayed_work(&tsc_irqwork, 0); 
  23.     return 0; 
  24. /* 
  25.  * We use device_initcall here, to ensure we run after the hpet 
  26.  * is fully initialized, which may occur at fs_initcall time. 
  27.  */ 
  28. device_initcall(init_tsc_clocksource); 

所以,clocksource 的PK之战中,TSC技压群雄,完爆HPET/PIT/ACPI_PM,成为current_clocksource。clocksource之战如何进行,如何选择当前时钟源,新的时钟源注册会带来什么影响。Linux如何根据时钟源完成计时,这个就在下一篇clocksource中介绍。

责任编辑:奔跑的冰淇淋 来源: ChinaUnix
相关推荐

2013-10-11 14:18:54

2020-07-07 11:01:04

Linux工具命令

2023-02-23 09:02:40

CIO领域管理

2018-12-12 09:44:07

Linux命令行时间管理

2013-03-14 17:17:34

2023-07-03 22:31:40

2021-03-18 13:00:51

JupyterPython编程语言

2012-07-31 09:55:50

时间管理管理

2020-02-24 11:11:10

IT企业技术

2022-01-13 13:24:16

工具底层逻辑

2012-09-26 09:52:57

项目项目回顾时间管理

2020-05-06 11:10:28

Python代码开发

2012-04-12 14:49:31

程序员

2012-07-27 10:17:05

开发

2009-12-04 10:00:31

无线路由器功能介绍

2009-10-27 11:30:00

系统集成项目管理师试题答案

2023-01-17 16:05:50

程序员时间管理日程表

2019-02-27 11:10:29

时间管理软件应用

2012-05-14 17:42:46

ibmdw

2021-05-08 15:14:50

鸿蒙HarmonyOS应用
点赞
收藏

51CTO技术栈公众号