busybox/util-linux/hwclock.c
<<
>>
Prefs
   1/* vi: set sw=4 ts=4: */
   2/*
   3 * Mini hwclock implementation for busybox
   4 *
   5 * Copyright (C) 2002 Robert Griebl <griebl@gmx.de>
   6 *
   7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
   8 */
   9//config:config HWCLOCK
  10//config:       bool "hwclock"
  11//config:       default y
  12//config:       select PLATFORM_LINUX
  13//config:       help
  14//config:         The hwclock utility is used to read and set the hardware clock
  15//config:         on a system. This is primarily used to set the current time on
  16//config:         shutdown in the hardware clock, so the hardware will keep the
  17//config:         correct time when Linux is _not_ running.
  18//config:
  19//config:config FEATURE_HWCLOCK_LONG_OPTIONS
  20//config:       bool "Support long options (--hctosys,...)"
  21//config:       default y
  22//config:       depends on HWCLOCK && LONG_OPTS
  23//config:       help
  24//config:         By default, the hwclock utility only uses short options. If you
  25//config:         are overly fond of its long options, such as --hctosys, --utc, etc)
  26//config:         then enable this option.
  27//config:
  28//config:config FEATURE_HWCLOCK_ADJTIME_FHS
  29//config:       bool "Use FHS /var/lib/hwclock/adjtime"
  30//config:       default n  # util-linux-ng in Fedora 13 still uses /etc/adjtime
  31//config:       depends on HWCLOCK
  32//config:       help
  33//config:         Starting with FHS 2.3, the adjtime state file is supposed to exist
  34//config:         at /var/lib/hwclock/adjtime instead of /etc/adjtime. If you wish
  35//config:         to use the FHS behavior, answer Y here, otherwise answer N for the
  36//config:         classic /etc/adjtime path.
  37//config:
  38//config:         pathname.com/fhs/pub/fhs-2.3.html#VARLIBHWCLOCKSTATEDIRECTORYFORHWCLO
  39
  40//applet:IF_HWCLOCK(APPLET(hwclock, BB_DIR_SBIN, BB_SUID_DROP))
  41
  42//kbuild:lib-$(CONFIG_HWCLOCK) += hwclock.o
  43
  44#include "libbb.h"
  45/* After libbb.h, since it needs sys/types.h on some systems */
  46#include <sys/utsname.h>
  47#include "rtc_.h"
  48
  49/* diff code is disabled: it's not sys/hw clock diff, it's some useless
  50 * "time between hwclock was started and we saw CMOS tick" quantity.
  51 * It's useless since hwclock is started at a random moment,
  52 * thus the quantity is also random, useless. Showing 0.000000 does not
  53 * deprive us from any useful info.
  54 *
  55 * SHOW_HWCLOCK_DIFF code in this file shows the difference between system
  56 * and hw clock. It is useful, but not compatible with standard hwclock.
  57 * Thus disabled.
  58 */
  59#define SHOW_HWCLOCK_DIFF 0
  60
  61
  62#if !SHOW_HWCLOCK_DIFF
  63# define read_rtc(pp_rtcname, sys_tv, utc) read_rtc(pp_rtcname, utc)
  64#endif
  65static time_t read_rtc(const char **pp_rtcname, struct timeval *sys_tv, int utc)
  66{
  67        struct tm tm_time;
  68        int fd;
  69
  70        fd = rtc_xopen(pp_rtcname, O_RDONLY);
  71
  72        rtc_read_tm(&tm_time, fd);
  73
  74#if SHOW_HWCLOCK_DIFF
  75        {
  76                int before = tm_time.tm_sec;
  77                while (1) {
  78                        rtc_read_tm(&tm_time, fd);
  79                        gettimeofday(sys_tv, NULL);
  80                        if (before != (int)tm_time.tm_sec)
  81                                break;
  82                }
  83        }
  84#endif
  85
  86        if (ENABLE_FEATURE_CLEAN_UP)
  87                close(fd);
  88
  89        return rtc_tm2time(&tm_time, utc);
  90}
  91
  92static void show_clock(const char **pp_rtcname, int utc)
  93{
  94#if SHOW_HWCLOCK_DIFF
  95        struct timeval sys_tv;
  96#endif
  97        time_t t = read_rtc(pp_rtcname, &sys_tv, utc);
  98
  99#if ENABLE_LOCALE_SUPPORT
 100        /* Standard hwclock uses locale-specific output format */
 101        char cp[64];
 102        struct tm *ptm = localtime(&t);
 103        strftime(cp, sizeof(cp), "%c", ptm);
 104#else
 105        char *cp = ctime(&t);
 106        chomp(cp);
 107#endif
 108
 109#if !SHOW_HWCLOCK_DIFF
 110        printf("%s  0.000000 seconds\n", cp);
 111#else
 112        {
 113                long diff = sys_tv.tv_sec - t;
 114                if (diff < 0 /*&& tv.tv_usec != 0*/) {
 115                        /* Why we need diff++? */
 116                        /* diff >= 0 is ok: | diff < 0, can't just use tv.tv_usec: */
 117                        /*   45.520820      |   43.520820 */
 118                        /* - 44.000000      | - 45.000000 */
 119                        /* =  1.520820      | = -1.479180, not -2.520820! */
 120                        diff++;
 121                        /* Should be 1000000 - tv.tv_usec, but then we must check tv.tv_usec != 0 */
 122                        sys_tv.tv_usec = 999999 - sys_tv.tv_usec;
 123                }
 124                printf("%s  %ld.%06lu seconds\n", cp, diff, (unsigned long)sys_tv.tv_usec);
 125        }
 126#endif
 127}
 128
 129static void to_sys_clock(const char **pp_rtcname, int utc)
 130{
 131        struct timeval tv;
 132        struct timezone tz;
 133
 134        tz.tz_minuteswest = timezone/60;
 135        /* ^^^ used to also subtract 60*daylight, but it's wrong:
 136         * daylight!=0 means "this timezone has some DST
 137         * during the year", not "DST is in effect now".
 138         */
 139        tz.tz_dsttime = 0;
 140
 141        tv.tv_sec = read_rtc(pp_rtcname, NULL, utc);
 142        tv.tv_usec = 0;
 143        if (settimeofday(&tv, &tz))
 144                bb_perror_msg_and_die("settimeofday");
 145}
 146
 147static void from_sys_clock(const char **pp_rtcname, int utc)
 148{
 149#if 1
 150        struct timeval tv;
 151        struct tm tm_time;
 152        int rtc;
 153
 154        rtc = rtc_xopen(pp_rtcname, O_WRONLY);
 155        gettimeofday(&tv, NULL);
 156        /* Prepare tm_time */
 157        if (sizeof(time_t) == sizeof(tv.tv_sec)) {
 158                if (utc)
 159                        gmtime_r((time_t*)&tv.tv_sec, &tm_time);
 160                else
 161                        localtime_r((time_t*)&tv.tv_sec, &tm_time);
 162        } else {
 163                time_t t = tv.tv_sec;
 164                if (utc)
 165                        gmtime_r(&t, &tm_time);
 166                else
 167                        localtime_r(&t, &tm_time);
 168        }
 169#else
 170/* Bloated code which tries to set hw clock with better precision.
 171 * On x86, even though code does set hw clock within <1ms of exact
 172 * whole seconds, apparently hw clock (at least on some machines)
 173 * doesn't reset internal fractional seconds to 0,
 174 * making all this a pointless excercise.
 175 */
 176        /* If we see that we are N usec away from whole second,
 177         * we'll sleep for N-ADJ usecs. ADJ corrects for the fact
 178         * that CPU is not infinitely fast.
 179         * On infinitely fast CPU, next wakeup would be
 180         * on (exactly_next_whole_second - ADJ). On real CPUs,
 181         * this difference between current time and whole second
 182         * is less than ADJ (assuming system isn't heavily loaded).
 183         */
 184        /* Small value of 256us gives very precise sync for 2+ GHz CPUs.
 185         * Slower CPUs will fail to sync and will go to bigger
 186         * ADJ values. qemu-emulated armv4tl with ~100 MHz
 187         * performance ends up using ADJ ~= 4*1024 and it takes
 188         * 2+ secs (2 tries with successively larger ADJ)
 189         * to sync. Even straced one on the same qemu (very slow)
 190         * takes only 4 tries.
 191         */
 192#define TWEAK_USEC 256
 193        unsigned adj = TWEAK_USEC;
 194        struct tm tm_time;
 195        struct timeval tv;
 196        int rtc = rtc_xopen(pp_rtcname, O_WRONLY);
 197
 198        /* Try to catch the moment when whole second is close */
 199        while (1) {
 200                unsigned rem_usec;
 201                time_t t;
 202
 203                gettimeofday(&tv, NULL);
 204
 205                t = tv.tv_sec;
 206                rem_usec = 1000000 - tv.tv_usec;
 207                if (rem_usec < adj) {
 208                        /* Close enough */
 209 small_rem:
 210                        t++;
 211                }
 212
 213                /* Prepare tm_time from t */
 214                if (utc)
 215                        gmtime_r(&t, &tm_time); /* may read /etc/xxx (it takes time) */
 216                else
 217                        localtime_r(&t, &tm_time); /* same */
 218
 219                if (adj >= 32*1024) {
 220                        break; /* 32 ms diff and still no luck?? give up trying to sync */
 221                }
 222
 223                /* gmtime/localtime took some time, re-get cur time */
 224                gettimeofday(&tv, NULL);
 225
 226                if (tv.tv_sec < t /* we are still in old second */
 227                 || (tv.tv_sec == t && tv.tv_usec < adj) /* not too far into next second */
 228                ) {
 229                        break; /* good, we are in sync! */
 230                }
 231
 232                rem_usec = 1000000 - tv.tv_usec;
 233                if (rem_usec < adj) {
 234                        t = tv.tv_sec;
 235                        goto small_rem; /* already close to next sec, don't sleep */
 236                }
 237
 238                /* Try to sync up by sleeping */
 239                usleep(rem_usec - adj);
 240
 241                /* Jump to 1ms diff, then increase fast (x2): EVERY loop
 242                 * takes ~1 sec, people won't like slowly converging code here!
 243                 */
 244        //bb_error_msg("adj:%d tv.tv_usec:%d", adj, (int)tv.tv_usec);
 245                if (adj < 512)
 246                        adj = 512;
 247                /* ... and if last "overshoot" does not look insanely big,
 248                 * just use it as adj increment. This makes convergence faster.
 249                 */
 250                if (tv.tv_usec < adj * 8) {
 251                        adj += tv.tv_usec;
 252                        continue;
 253                }
 254                adj *= 2;
 255        }
 256        /* Debug aid to find "optimal" TWEAK_USEC with nearly exact sync.
 257         * Look for a value which makes tv_usec close to 999999 or 0.
 258         * For 2.20GHz Intel Core 2: optimal TWEAK_USEC ~= 200
 259         */
 260        //bb_error_msg("tv.tv_usec:%d", (int)tv.tv_usec);
 261#endif
 262
 263        tm_time.tm_isdst = 0;
 264        xioctl(rtc, RTC_SET_TIME, &tm_time);
 265
 266        if (ENABLE_FEATURE_CLEAN_UP)
 267                close(rtc);
 268}
 269
 270/*
 271 * At system boot, kernel may set system time from RTC,
 272 * but it knows nothing about timezones. If RTC is in local time,
 273 * then system time is wrong - it is offset by timezone.
 274 * This option corrects system time if RTC is in local time,
 275 * and (always) sets in-kernel timezone.
 276 *
 277 * This is an alternate option to --hctosys that does not read the
 278 * hardware clock.
 279 */
 280static void set_system_clock_timezone(int utc)
 281{
 282        struct timeval tv;
 283        struct tm *broken;
 284        struct timezone tz;
 285
 286        gettimeofday(&tv, NULL);
 287        broken = localtime(&tv.tv_sec);
 288        tz.tz_minuteswest = timezone / 60;
 289        if (broken->tm_isdst > 0)
 290                tz.tz_minuteswest -= 60;
 291        tz.tz_dsttime = 0;
 292        gettimeofday(&tv, NULL);
 293        if (!utc)
 294                tv.tv_sec += tz.tz_minuteswest * 60;
 295        if (settimeofday(&tv, &tz))
 296                bb_perror_msg_and_die("settimeofday");
 297}
 298
 299//usage:#define hwclock_trivial_usage
 300//usage:        IF_FEATURE_HWCLOCK_LONG_OPTIONS(
 301//usage:       "[-r|--show] [-s|--hctosys] [-w|--systohc] [-t|--systz]"
 302//usage:       " [-l|--localtime] [-u|--utc]"
 303//usage:       " [-f|--rtc FILE]"
 304//usage:        )
 305//usage:        IF_NOT_FEATURE_HWCLOCK_LONG_OPTIONS(
 306//usage:       "[-r] [-s] [-w] [-t] [-l] [-u] [-f FILE]"
 307//usage:        )
 308//usage:#define hwclock_full_usage "\n\n"
 309//usage:       "Query and set hardware clock (RTC)\n"
 310//usage:     "\n        -r      Show hardware clock time"
 311//usage:     "\n        -s      Set system time from hardware clock"
 312//usage:     "\n        -w      Set hardware clock from system time"
 313//usage:     "\n        -t      Set in-kernel timezone, correct system time"
 314//usage:     "\n                if hardware clock is in local time"
 315//usage:     "\n        -u      Assume hardware clock is kept in UTC"
 316//usage:     "\n        -l      Assume hardware clock is kept in local time"
 317//usage:     "\n        -f FILE Use specified device (e.g. /dev/rtc2)"
 318
 319#define HWCLOCK_OPT_LOCALTIME   0x01
 320#define HWCLOCK_OPT_UTC         0x02
 321#define HWCLOCK_OPT_SHOW        0x04
 322#define HWCLOCK_OPT_HCTOSYS     0x08
 323#define HWCLOCK_OPT_SYSTOHC     0x10
 324#define HWCLOCK_OPT_SYSTZ       0x20
 325#define HWCLOCK_OPT_RTCFILE     0x40
 326
 327int hwclock_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
 328int hwclock_main(int argc UNUSED_PARAM, char **argv)
 329{
 330        const char *rtcname = NULL;
 331        unsigned opt;
 332        int utc;
 333
 334#if ENABLE_FEATURE_HWCLOCK_LONG_OPTIONS
 335        static const char hwclock_longopts[] ALIGN1 =
 336                "localtime\0" No_argument "l" /* short opt is non-standard */
 337                "utc\0"       No_argument "u"
 338                "show\0"      No_argument "r"
 339                "hctosys\0"   No_argument "s"
 340                "systohc\0"   No_argument "w"
 341                "systz\0"     No_argument "t" /* short opt is non-standard */
 342                "rtc\0"       Required_argument "f"
 343                ;
 344        applet_long_options = hwclock_longopts;
 345#endif
 346
 347        /* Initialize "timezone" (libc global variable) */
 348        tzset();
 349
 350        opt_complementary = "r--wst:w--rst:s--wrt:t--rsw:l--u:u--l";
 351        opt = getopt32(argv, "lurswtf:", &rtcname);
 352
 353        /* If -u or -l wasn't given check if we are using utc */
 354        if (opt & (HWCLOCK_OPT_UTC | HWCLOCK_OPT_LOCALTIME))
 355                utc = (opt & HWCLOCK_OPT_UTC);
 356        else
 357                utc = rtc_adjtime_is_utc();
 358
 359        if (opt & HWCLOCK_OPT_HCTOSYS)
 360                to_sys_clock(&rtcname, utc);
 361        else if (opt & HWCLOCK_OPT_SYSTOHC)
 362                from_sys_clock(&rtcname, utc);
 363        else if (opt & HWCLOCK_OPT_SYSTZ)
 364                set_system_clock_timezone(utc);
 365        else
 366                /* default HWCLOCK_OPT_SHOW */
 367                show_clock(&rtcname, utc);
 368
 369        return 0;
 370}
 371