hwclock.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. //musl has no __MUSL__ or similar define to check for,
  36. //but its <sys/types.h> has these lines:
  37. // #define __NEED_fsblkcnt_t
  38. // #define __NEED_fsfilcnt_t
  39. #if defined(__linux__) && defined(__NEED_fsblkcnt_t) && defined(__NEED_fsfilcnt_t)
  40. # define LIBC_IS_MUSL 1
  41. # include <sys/syscall.h>
  42. #else
  43. # define LIBC_IS_MUSL 0
  44. #endif
  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. xgettimeofday(sys_tv);
  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 set_kernel_tz(const struct timezone *tz)
  115. {
  116. #if LIBC_IS_MUSL
  117. /* musl libc does not pass tz argument to syscall
  118. * because "it's deprecated by POSIX, therefore it's fine
  119. * if we gratuitously break stuff" :(
  120. */
  121. #if !defined(SYS_settimeofday) && defined(SYS_settimeofday_time32)
  122. # define SYS_settimeofday SYS_settimeofday_time32
  123. #endif
  124. int ret = syscall(SYS_settimeofday, NULL, tz);
  125. #else
  126. int ret = settimeofday(NULL, tz);
  127. #endif
  128. if (ret)
  129. bb_simple_perror_msg_and_die("settimeofday");
  130. }
  131. /*
  132. * At system boot, kernel may set system time from RTC,
  133. * but it knows nothing about timezones. If RTC is in local time,
  134. * then system time is wrong - it is offset by timezone.
  135. * --systz option corrects system time if RTC is in local time,
  136. * and (always) sets in-kernel timezone.
  137. * (Unlike --hctosys, it does not read the RTC).
  138. *
  139. * util-linux's code has this comment:
  140. * RTC | settimeofday calls
  141. * ------|-------------------------------------------------
  142. * Local | 1st) warps system time*, sets PCIL* and kernel tz
  143. * UTC | 1st) locks warp_clock 2nd) sets kernel tz
  144. * * only on first call after boot
  145. * (PCIL is "persistent_clock_is_local" kernel internal flag,
  146. * it makes kernel save RTC in local time, not UTC.)
  147. */
  148. static void set_kernel_timezone_and_clock(int utc, const struct timeval *hctosys)
  149. {
  150. time_t cur;
  151. struct tm *broken;
  152. struct timezone tz = { 0 };
  153. /* if --utc, prevent kernel's warp_clock() with a dummy call */
  154. if (utc)
  155. set_kernel_tz(&tz);
  156. /* Set kernel's timezone offset based on userspace one */
  157. //It's tempting to call tzset() and use libc global "timezone" variable
  158. //...but it does NOT include DST shift (IOW: it's WRONG, usually by one hour,
  159. //if DST is in effect!) Thus this ridiculous dance:
  160. cur = time(NULL);
  161. broken = localtime(&cur);
  162. tz.tz_minuteswest = -broken->tm_gmtoff / 60;
  163. /*tz.tz_dsttime = 0; already is */
  164. set_kernel_tz(&tz); /* MIGHT warp_clock() if 1st call since boot */
  165. if (hctosys) /* it's --hctosys: set time too */
  166. xsettimeofday(hctosys);
  167. }
  168. static void to_sys_clock(const char **pp_rtcname, int utc)
  169. {
  170. struct timeval tv;
  171. tv.tv_sec = read_rtc(pp_rtcname, NULL, utc);
  172. tv.tv_usec = 0;
  173. return set_kernel_timezone_and_clock(utc, &tv);
  174. }
  175. static void from_sys_clock(const char **pp_rtcname, int utc)
  176. {
  177. #if 1
  178. struct timeval tv;
  179. struct tm tm_time;
  180. int rtc;
  181. rtc = rtc_xopen(pp_rtcname, O_WRONLY);
  182. xgettimeofday(&tv);
  183. /* Prepare tm_time */
  184. if (sizeof(time_t) == sizeof(tv.tv_sec)) {
  185. if (utc)
  186. gmtime_r((time_t*)&tv.tv_sec, &tm_time);
  187. else
  188. localtime_r((time_t*)&tv.tv_sec, &tm_time);
  189. } else {
  190. time_t t = tv.tv_sec;
  191. if (utc)
  192. gmtime_r(&t, &tm_time);
  193. else
  194. localtime_r(&t, &tm_time);
  195. }
  196. #else
  197. /* Bloated code which tries to set hw clock with better precision.
  198. * On x86, even though code does set hw clock within <1ms of exact
  199. * whole seconds, apparently hw clock (at least on some machines)
  200. * doesn't reset internal fractional seconds to 0,
  201. * making all this a pointless exercise.
  202. */
  203. /* If we see that we are N usec away from whole second,
  204. * we'll sleep for N-ADJ usecs. ADJ corrects for the fact
  205. * that CPU is not infinitely fast.
  206. * On infinitely fast CPU, next wakeup would be
  207. * on (exactly_next_whole_second - ADJ). On real CPUs,
  208. * this difference between current time and whole second
  209. * is less than ADJ (assuming system isn't heavily loaded).
  210. */
  211. /* Small value of 256us gives very precise sync for 2+ GHz CPUs.
  212. * Slower CPUs will fail to sync and will go to bigger
  213. * ADJ values. qemu-emulated armv4tl with ~100 MHz
  214. * performance ends up using ADJ ~= 4*1024 and it takes
  215. * 2+ secs (2 tries with successively larger ADJ)
  216. * to sync. Even straced one on the same qemu (very slow)
  217. * takes only 4 tries.
  218. */
  219. #define TWEAK_USEC 256
  220. unsigned adj = TWEAK_USEC;
  221. struct tm tm_time;
  222. struct timeval tv;
  223. int rtc = rtc_xopen(pp_rtcname, O_WRONLY);
  224. /* Try to catch the moment when whole second is close */
  225. while (1) {
  226. unsigned rem_usec;
  227. time_t t;
  228. xgettimeofday(&tv);
  229. t = tv.tv_sec;
  230. rem_usec = 1000000 - tv.tv_usec;
  231. if (rem_usec < adj) {
  232. /* Close enough */
  233. small_rem:
  234. t++;
  235. }
  236. /* Prepare tm_time from t */
  237. if (utc)
  238. gmtime_r(&t, &tm_time); /* may read /etc/xxx (it takes time) */
  239. else
  240. localtime_r(&t, &tm_time); /* same */
  241. if (adj >= 32*1024) {
  242. break; /* 32 ms diff and still no luck?? give up trying to sync */
  243. }
  244. /* gmtime/localtime took some time, re-get cur time */
  245. xgettimeofday(&tv);
  246. if (tv.tv_sec < t /* we are still in old second */
  247. || (tv.tv_sec == t && tv.tv_usec < adj) /* not too far into next second */
  248. ) {
  249. break; /* good, we are in sync! */
  250. }
  251. rem_usec = 1000000 - tv.tv_usec;
  252. if (rem_usec < adj) {
  253. t = tv.tv_sec;
  254. goto small_rem; /* already close to next sec, don't sleep */
  255. }
  256. /* Try to sync up by sleeping */
  257. usleep(rem_usec - adj);
  258. /* Jump to 1ms diff, then increase fast (x2): EVERY loop
  259. * takes ~1 sec, people won't like slowly converging code here!
  260. */
  261. //bb_error_msg("adj:%d tv.tv_usec:%d", adj, (int)tv.tv_usec);
  262. if (adj < 512)
  263. adj = 512;
  264. /* ... and if last "overshoot" does not look insanely big,
  265. * just use it as adj increment. This makes convergence faster.
  266. */
  267. if (tv.tv_usec < adj * 8) {
  268. adj += tv.tv_usec;
  269. continue;
  270. }
  271. adj *= 2;
  272. }
  273. /* Debug aid to find "optimal" TWEAK_USEC with nearly exact sync.
  274. * Look for a value which makes tv_usec close to 999999 or 0.
  275. * For 2.20GHz Intel Core 2: optimal TWEAK_USEC ~= 200
  276. */
  277. //bb_error_msg("tv.tv_usec:%d", (int)tv.tv_usec);
  278. #endif
  279. tm_time.tm_isdst = 0;
  280. xioctl(rtc, RTC_SET_TIME, &tm_time);
  281. if (ENABLE_FEATURE_CLEAN_UP)
  282. close(rtc);
  283. }
  284. // hwclock from util-linux 2.36.1
  285. // hwclock [function] [option...]
  286. //Functions:
  287. // -r, --show display the RTC time
  288. // --get display drift corrected RTC time
  289. // --set set the RTC according to --date
  290. // -s, --hctosys set the system time from the RTC
  291. // -w, --systohc set the RTC from the system time
  292. // --systz send timescale configurations to the kernel
  293. // -a, --adjust adjust the RTC to account for systematic drift
  294. // --predict predict the drifted RTC time according to --date
  295. //Options:
  296. // -u, --utc the RTC timescale is UTC
  297. // -l, --localtime the RTC timescale is Local
  298. // -f, --rtc <file> use an alternate file to /dev/rtc0
  299. // --directisa use the ISA bus instead of /dev/rtc0 access
  300. // --date <time> date/time input for --set and --predict
  301. // --delay <sec> delay used when set new RTC time
  302. // --update-drift update the RTC drift factor
  303. // --noadjfile do not use /etc/adjtime
  304. // --adjfile <file> use an alternate file to /etc/adjtime
  305. // --test dry run; implies --verbose
  306. // -v, --verbose display more details
  307. //usage:#define hwclock_trivial_usage
  308. //usage: IF_LONG_OPTS(
  309. //usage: "[-swul] [--systz] [-f DEV]"
  310. //usage: )
  311. //usage: IF_NOT_LONG_OPTS(
  312. //usage: "[-swult] [-f DEV]"
  313. //usage: )
  314. //usage:#define hwclock_full_usage "\n\n"
  315. //usage: "Show or set hardware clock (RTC)\n"
  316. ///////: "\n -r Show RTC time"
  317. ///////-r is default, don't bother showing it in help
  318. //usage: "\n -s Set system time from RTC"
  319. //usage: "\n -w Set RTC from system time"
  320. //usage: IF_LONG_OPTS(
  321. //usage: "\n --systz Set in-kernel timezone, correct system time"
  322. //usage: "\n if RTC is kept in local time"
  323. //usage: )
  324. //usage: "\n -f DEV Use specified device (e.g. /dev/rtc2)"
  325. //usage: "\n -u Assume RTC is kept in UTC"
  326. //usage: "\n -l Assume RTC is kept in local time"
  327. //usage: "\n (if neither is given, read from "ADJTIME_PATH")"
  328. //TODO: get rid of incompatible -t alias to --systz?
  329. #define HWCLOCK_OPT_LOCALTIME 0x01
  330. #define HWCLOCK_OPT_UTC 0x02
  331. #define HWCLOCK_OPT_SHOW 0x04
  332. #define HWCLOCK_OPT_HCTOSYS 0x08
  333. #define HWCLOCK_OPT_SYSTOHC 0x10
  334. #define HWCLOCK_OPT_SYSTZ 0x20
  335. #define HWCLOCK_OPT_RTCFILE 0x40
  336. int hwclock_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  337. int hwclock_main(int argc UNUSED_PARAM, char **argv)
  338. {
  339. const char *rtcname = NULL;
  340. unsigned opt;
  341. int utc;
  342. #if ENABLE_LONG_OPTS
  343. static const char hwclock_longopts[] ALIGN1 =
  344. "localtime\0" No_argument "l"
  345. "utc\0" No_argument "u"
  346. "show\0" No_argument "r"
  347. "hctosys\0" No_argument "s"
  348. "systohc\0" No_argument "w"
  349. "systz\0" No_argument "t" /* short opt is non-standard */
  350. "rtc\0" Required_argument "f"
  351. ;
  352. #endif
  353. opt = getopt32long(argv,
  354. "^""lurswtf:v" /* -v is accepted and ignored */
  355. "\0"
  356. "r--wst:w--rst:s--wrt:t--rsw:l--u:u--l",
  357. hwclock_longopts,
  358. &rtcname
  359. );
  360. /* If -u or -l wasn't given, check if we are using utc */
  361. if (opt & (HWCLOCK_OPT_UTC | HWCLOCK_OPT_LOCALTIME))
  362. utc = (opt & HWCLOCK_OPT_UTC);
  363. else
  364. utc = rtc_adjtime_is_utc();
  365. if (opt & HWCLOCK_OPT_HCTOSYS)
  366. to_sys_clock(&rtcname, utc);
  367. else if (opt & HWCLOCK_OPT_SYSTOHC)
  368. from_sys_clock(&rtcname, utc);
  369. else if (opt & HWCLOCK_OPT_SYSTZ)
  370. set_kernel_timezone_and_clock(utc, NULL);
  371. else
  372. /* default HWCLOCK_OPT_SHOW */
  373. show_clock(&rtcname, utc);
  374. return 0;
  375. }