hwclock.c 11 KB

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