hwclock.c 11 KB

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