3
0

hwclock.c 10 KB

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