6.4 Updating the Time and Date

User programs get the current time and date from the xtime variable of type struct timeval. The kernel also occasionally refers to it, for instance, when updating inode timestamps (see Section 1.5.4). In particular, xtime.tv_sec stores the number of seconds that have elapsed since midnight of January 1, 1970 (UTC), while xtime.tv_usec stores the number of microseconds that have elapsed within the last second (its value ranges between 0 and 999999).

During kernel initialization, the time_init( ) function is invoked to set up the time and date. It reads them from the Real Time Clock by invoking the get_cmos_time( ) function, then it initializes xtime. Once this has been done, the kernel does not need the RTC anymore; it relies instead on the TIMER_BH bottom half, which is usually activated once every tick.

The update_times( ) function is equivalent to the following:

void update_times(void)
{ 
    unsigned long ticks;
    write_lock_irq(&xtime_lock);
    ticks = jiffies - wall_jiffies;
    if (ticks) {
        wall_jiffies += ticks;
        update_wall_time(ticks);
    }
    write_unlock_irq(&xtime_lock);
    calc_load(ticks);
} 

On a uniprocessor system, the write_lock_irq( ) and write_unlock_irq( ) functions simply disable and enable the interrupts on the executing CPU; on multiprocessor systems, they also acquire and release the xtime_lock spin lock, which protects against concurrent accesses to the xtime variable.

The wall_jiffies variable stores the time of the last update of the xtime variable. Observe that the value of wall_jiffies can be smaller than jiffies-1, since the execution of the bottom half can be delayed; in other words, the kernel does not necessarily update the xtime variable at every tick. However, no tick is definitively lost, and in the long run, xtime stores the correct system time.

The update_wall_time( ) function invokes the update_wall_time_one_tick( ) function ticks consecutive times; each invocation adds 10,000 to the xtime.tv_usec field.[5] If xtime.tv_usec becomes greater than 999,999, the update_wall_time( ) function also updates the tv_sec field of xtime.

[5] In fact, the function is much more complex since it might tune the value 10,000 slightly. This may be necessary if an adjtimex( ) system call has been issued (see Section 6.7.2 later in this chapter).