RTC
- 原创,转载请写明出处。
一直以来想写一篇关于RTC的总结,可是人太懒,在读完John Z. Sonmez大伽的《软技能代码之外的生存技能》后,终于下定决心,完成这项早已计划中的任务。首先声明,本文是以PC为例来阐述RTC工作的基本原理。
RTC的基本概念
RTC(Real Time Clock),实时时钟,是存在于PC(x86)及类PC架构的电路中,其主要的作用是记录设备关机时的时间及在设备开机时提供时间基准,也就是说在设备机器关电的时候,记录下当时的时间,在设备启动时为设备内部的时间提供基准值,从而使得设备内部的时间值不是从初值开始,而是从RTC记录并运行的时间开始。从这个意义上RTC有被成为墙上时间(walltimer)。
RTC电路
聪明的你,先来看下RTC电路
其中RTCX1,RTCX2, RTCRST#, SRTCRST#连接到PCH上, 所以上RTC的input和output都是受PCH的控制的,也就是说RTC提供的时间是给PCH的。
RTCX1为晶振的input,RTCX2为晶振的output,也就是晶振反馈值。
RTCRST#的主要作用是用来清楚CMOS的,当然它也可以用来检测电池的电压是否低于2V。
SRTCRST#用来当电池更换时清除Intel ME相关的寄存器。
Vbatt时由安装的一颗3V左右(一般为2.8V~3.3V)的纽扣电池(一般都为CR2302,提供最大10mA的电流)提供,这颗电池的作用时在机器移除AC电源后, RTC电路仍然可以正常工作。当这颗电池的电压不足的时候,就会出现RTC时间不准确。
Xtal是由一颗频率为32 .768KHz的石英晶振提供的, 此晶振的功能是提供给计时电路用的基准clock。
肖特基二极管D1的作用:当AC电源连接时,也就是VCCRTC(3.3V)有电时,D1不导通,电池不提供电流给RTC电路;当AC电源移除后,D1导通,电池工作。
RTC工作原理
提起RTC,不得不提起PC系统的另外一个时间,系统时间。在Linux和Windows中,这个时间都是内核在维护的,也就是说在Linux等操作系统中,有两套时间在运行。
系统时间的精度可以做到微妙级,而相对应的RTC的时间精度只能做到秒级。一般情况下系统时间的精度为24小时最大漂移1.2秒,RTC的时间的漂移就要大的多。这就造成了系统时间的精确的要远远高于RTC。所以当系统运行了一段时间后,会出现系统时间和RTC不一致的情况,这是就需要我们定期将两个时间进行同步。
RTC和CMOS
RTC的时间和设置都保存在CMOS RAM中,详细的如下表,其中前10个字节(offset 00 ~ 09h)存储着RTC确切的时间,也就是你在BIOS setup utility中看到的时间,当然这个时间是变动的,剩下的都是RTC的配置字节。可以通过70/71h端口去操作,也可以通过ioctl命令去配置。
Offset Hex |
Offset Dec |
Field Size |
Function |
00h |
0 |
1 byte |
RTC seconds. Contains the seconds value of current time |
01h |
1 |
1 byte |
RTC seconds alarm. Contains the seconds value for the RTC alarm |
02h |
2 |
1 byte |
RTC minutes. Contains the minutes value of the current time |
03h |
3 |
1 byte |
RTC minutes alarm. Contains the minutes value for the RTC alarm |
04h |
4 |
1 byte |
RTC hours. Contains the hours value of the current time |
05h |
5 |
1 byte |
RTC hours alarm. Contains the hours value for the RTC alarm |
06h |
6 |
1 byte |
RTC day of week. Contains the current day of the week |
07h |
7 |
1 byte |
RTC date day. Contains day value of current date |
08h |
8 |
1 byte |
RTC date month. Contains the month value of current date |
09h |
9 |
1 byte |
RTC date year. Contains the year value of current date |
0Ah |
10 |
1 byte |
Status Register A |
|
|
|
Bit 7 = Update in progress (0 = Date and time can be read, 1 = Time update in progress) |
|
|
|
Bits 6-4 = Time frequ |