hwclock.c 11 KB

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