3
0

hwclock.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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.9 kb)"
  11. //config: default y
  12. //config: select LONG_OPTS
  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. //musl has no __MUSL__ or similar define to check for,
  37. //but its <sys/types.h> has these lines:
  38. // #define __NEED_fsblkcnt_t
  39. // #define __NEED_fsfilcnt_t
  40. #if defined(__linux__) && defined(__NEED_fsblkcnt_t) && defined(__NEED_fsfilcnt_t)
  41. # define LIBC_IS_MUSL 1
  42. # include <sys/syscall.h>
  43. #else
  44. # define LIBC_IS_MUSL 0
  45. #endif
  46. /* diff code is disabled: it's not sys/hw clock diff, it's some useless
  47. * "time between hwclock was started and we saw CMOS tick" quantity.
  48. * It's useless since hwclock is started at a random moment,
  49. * thus the quantity is also random, useless. Showing 0.000000 does not
  50. * deprive us from any useful info.
  51. *
  52. * SHOW_HWCLOCK_DIFF code in this file shows the difference between system
  53. * and hw clock. It is useful, but not compatible with standard hwclock.
  54. * Thus disabled.
  55. */
  56. #define SHOW_HWCLOCK_DIFF 0
  57. #if !SHOW_HWCLOCK_DIFF
  58. # define read_rtc(pp_rtcname, sys_tv, utc) read_rtc(pp_rtcname, utc)
  59. #endif
  60. static time_t read_rtc(const char **pp_rtcname, struct timeval *sys_tv, int utc)
  61. {
  62. struct tm tm_time;
  63. int fd;
  64. fd = rtc_xopen(pp_rtcname, O_RDONLY);
  65. rtc_read_tm(&tm_time, fd);
  66. #if SHOW_HWCLOCK_DIFF
  67. {
  68. int before = tm_time.tm_sec;
  69. while (1) {
  70. rtc_read_tm(&tm_time, fd);
  71. xgettimeofday(sys_tv);
  72. if (before != (int)tm_time.tm_sec)
  73. break;
  74. }
  75. }
  76. #endif
  77. if (ENABLE_FEATURE_CLEAN_UP)
  78. close(fd);
  79. return rtc_tm2time(&tm_time, utc);
  80. }
  81. static void show_clock(const char **pp_rtcname, int utc)
  82. {
  83. #if SHOW_HWCLOCK_DIFF
  84. struct timeval sys_tv;
  85. #endif
  86. time_t t = read_rtc(pp_rtcname, &sys_tv, utc);
  87. #if ENABLE_LOCALE_SUPPORT
  88. /* Standard hwclock uses locale-specific output format */
  89. char cp[64];
  90. struct tm *ptm = localtime(&t);
  91. strftime(cp, sizeof(cp), "%c", ptm);
  92. #else
  93. char *cp = ctime(&t);
  94. chomp(cp);
  95. #endif
  96. #if !SHOW_HWCLOCK_DIFF
  97. printf("%s 0.000000 seconds\n", cp);
  98. #else
  99. {
  100. long diff = sys_tv.tv_sec - t;
  101. if (diff < 0 /*&& tv.tv_usec != 0*/) {
  102. /* Why we need diff++? */
  103. /* diff >= 0 is ok: | diff < 0, can't just use tv.tv_usec: */
  104. /* 45.520820 | 43.520820 */
  105. /* - 44.000000 | - 45.000000 */
  106. /* = 1.520820 | = -1.479180, not -2.520820! */
  107. diff++;
  108. /* Should be 1000000 - tv.tv_usec, but then we must check tv.tv_usec != 0 */
  109. sys_tv.tv_usec = 999999 - sys_tv.tv_usec;
  110. }
  111. printf("%s %ld.%06lu seconds\n", cp, diff, (unsigned long)sys_tv.tv_usec);
  112. }
  113. #endif
  114. }
  115. static void set_kernel_tz(const struct timezone *tz)
  116. {
  117. #if LIBC_IS_MUSL
  118. /* musl libc does not pass tz argument to syscall
  119. * because "it's deprecated by POSIX, therefore it's fine
  120. * if we gratuitously break stuff" :(
  121. */
  122. #if !defined(SYS_settimeofday) && defined(SYS_settimeofday_time32)
  123. # define SYS_settimeofday SYS_settimeofday_time32
  124. #endif
  125. int ret = syscall(SYS_settimeofday, NULL, tz);
  126. #else
  127. int ret = settimeofday(NULL, tz);
  128. #endif
  129. if (ret)
  130. bb_simple_perror_msg_and_die("settimeofday");
  131. }
  132. /*
  133. * At system boot, kernel may set system time from RTC,
  134. * but it knows nothing about timezones. If RTC is in local time,
  135. * then system time is wrong - it is offset by timezone.
  136. * --systz option corrects system time if RTC is in local time,
  137. * and (always) sets in-kernel timezone.
  138. * (Unlike --hctosys, it does not read the RTC).
  139. *
  140. * util-linux's code has this comment:
  141. * RTC | settimeofday calls
  142. * ------|-------------------------------------------------
  143. * Local | 1st) warps system time*, sets PCIL* and kernel tz
  144. * UTC | 1st) locks warp_clock 2nd) sets kernel tz
  145. * * only on first call after boot
  146. * (PCIL is "persistent_clock_is_local" kernel internal flag,
  147. * it makes kernel save RTC in local time, not UTC.)
  148. */
  149. static void set_kernel_timezone_and_clock(int utc, const struct timeval *hctosys)
  150. {
  151. time_t cur;
  152. struct tm *broken;
  153. struct timezone tz = { 0 };
  154. /* if --utc, prevent kernel's warp_clock() with a dummy call */
  155. if (utc)
  156. set_kernel_tz(&tz);
  157. /* Set kernel's timezone offset based on userspace one */
  158. //It's tempting to call tzset() and use libc global "timezone" variable
  159. //...but it does NOT include DST shift (IOW: it's WRONG, usually by one hour,
  160. //if DST is in effect!) Thus this ridiculous dance:
  161. cur = time(NULL);
  162. broken = localtime(&cur);
  163. tz.tz_minuteswest = -broken->tm_gmtoff / 60;
  164. /*tz.tz_dsttime = 0; already is */
  165. set_kernel_tz(&tz); /* MIGHT warp_clock() if 1st call since boot */
  166. if (hctosys) /* it's --hctosys: set time too */
  167. xsettimeofday(hctosys);
  168. }
  169. static void to_sys_clock(const char **pp_rtcname, int utc)
  170. {
  171. struct timeval tv;
  172. tv.tv_sec = read_rtc(pp_rtcname, NULL, utc);
  173. tv.tv_usec = 0;
  174. return set_kernel_timezone_and_clock(utc, &tv);
  175. }
  176. static void from_sys_clock(const char **pp_rtcname, int utc)
  177. {
  178. #if 1
  179. struct timeval tv;
  180. struct tm tm_time;
  181. int rtc;
  182. rtc = rtc_xopen(pp_rtcname, O_WRONLY);
  183. xgettimeofday(&tv);
  184. /* Prepare tm_time */
  185. if (sizeof(time_t) == sizeof(tv.tv_sec)) {
  186. if (utc)
  187. gmtime_r((time_t*)&tv.tv_sec, &tm_time);
  188. else
  189. localtime_r((time_t*)&tv.tv_sec, &tm_time);
  190. } else {
  191. time_t t = tv.tv_sec;
  192. if (utc)
  193. gmtime_r(&t, &tm_time);
  194. else
  195. localtime_r(&t, &tm_time);
  196. }
  197. #else
  198. /* Bloated code which tries to set hw clock with better precision.
  199. * On x86, even though code does set hw clock within <1ms of exact
  200. * whole seconds, apparently hw clock (at least on some machines)
  201. * doesn't reset internal fractional seconds to 0,
  202. * making all this a pointless exercise.
  203. */
  204. /* If we see that we are N usec away from whole second,
  205. * we'll sleep for N-ADJ usecs. ADJ corrects for the fact
  206. * that CPU is not infinitely fast.
  207. * On infinitely fast CPU, next wakeup would be
  208. * on (exactly_next_whole_second - ADJ). On real CPUs,
  209. * this difference between current time and whole second
  210. * is less than ADJ (assuming system isn't heavily loaded).
  211. */
  212. /* Small value of 256us gives very precise sync for 2+ GHz CPUs.
  213. * Slower CPUs will fail to sync and will go to bigger
  214. * ADJ values. qemu-emulated armv4tl with ~100 MHz
  215. * performance ends up using ADJ ~= 4*1024 and it takes
  216. * 2+ secs (2 tries with successively larger ADJ)
  217. * to sync. Even straced one on the same qemu (very slow)
  218. * takes only 4 tries.
  219. */
  220. #define TWEAK_USEC 256
  221. unsigned adj = TWEAK_USEC;
  222. struct tm tm_time;
  223. struct timeval tv;
  224. int rtc = rtc_xopen(pp_rtcname, O_WRONLY);
  225. /* Try to catch the moment when whole second is close */
  226. while (1) {
  227. unsigned rem_usec;
  228. time_t t;
  229. xgettimeofday(&tv);
  230. t = tv.tv_sec;
  231. rem_usec = 1000000 - tv.tv_usec;
  232. if (rem_usec < adj) {
  233. /* Close enough */
  234. small_rem:
  235. t++;
  236. }
  237. /* Prepare tm_time from t */
  238. if (utc)
  239. gmtime_r(&t, &tm_time); /* may read /etc/xxx (it takes time) */
  240. else
  241. localtime_r(&t, &tm_time); /* same */
  242. if (adj >= 32*1024) {
  243. break; /* 32 ms diff and still no luck?? give up trying to sync */
  244. }
  245. /* gmtime/localtime took some time, re-get cur time */
  246. xgettimeofday(&tv);
  247. if (tv.tv_sec < t /* we are still in old second */
  248. || (tv.tv_sec == t && tv.tv_usec < adj) /* not too far into next second */
  249. ) {
  250. break; /* good, we are in sync! */
  251. }
  252. rem_usec = 1000000 - tv.tv_usec;
  253. if (rem_usec < adj) {
  254. t = tv.tv_sec;
  255. goto small_rem; /* already close to next sec, don't sleep */
  256. }
  257. /* Try to sync up by sleeping */
  258. usleep(rem_usec - adj);
  259. /* Jump to 1ms diff, then increase fast (x2): EVERY loop
  260. * takes ~1 sec, people won't like slowly converging code here!
  261. */
  262. //bb_error_msg("adj:%d tv.tv_usec:%d", adj, (int)tv.tv_usec);
  263. if (adj < 512)
  264. adj = 512;
  265. /* ... and if last "overshoot" does not look insanely big,
  266. * just use it as adj increment. This makes convergence faster.
  267. */
  268. if (tv.tv_usec < adj * 8) {
  269. adj += tv.tv_usec;
  270. continue;
  271. }
  272. adj *= 2;
  273. }
  274. /* Debug aid to find "optimal" TWEAK_USEC with nearly exact sync.
  275. * Look for a value which makes tv_usec close to 999999 or 0.
  276. * For 2.20GHz Intel Core 2: optimal TWEAK_USEC ~= 200
  277. */
  278. //bb_error_msg("tv.tv_usec:%d", (int)tv.tv_usec);
  279. #endif
  280. tm_time.tm_isdst = 0;
  281. xioctl(rtc, RTC_SET_TIME, &tm_time);
  282. if (ENABLE_FEATURE_CLEAN_UP)
  283. close(rtc);
  284. }
  285. static uint64_t resolve_rtc_param_alias(const char *alias)
  286. {
  287. int n;
  288. BUILD_BUG_ON(RTC_PARAM_FEATURES != 0
  289. || RTC_PARAM_CORRECTION != 1
  290. || RTC_PARAM_BACKUP_SWITCH_MODE != 2
  291. );
  292. n = index_in_strings(
  293. "features" "\0"
  294. "correction" "\0"
  295. "bsm" "\0"
  296. , alias);
  297. if (n >= 0)
  298. return n;
  299. return xstrtoull(alias, 0);
  300. }
  301. static void get_rtc_param(const char **pp_rtcname, const char *rtc_param)
  302. {
  303. int rtc;
  304. struct rtc_param param;
  305. param.param = resolve_rtc_param_alias(rtc_param);
  306. rtc = rtc_xopen(pp_rtcname, O_RDONLY);
  307. xioctl(rtc, RTC_PARAM_GET, &param);
  308. printf("The RTC parameter 0x%llx is set to 0x%llx.\n",
  309. (unsigned long long) param.param, (unsigned long long) param.uvalue);
  310. if (ENABLE_FEATURE_CLEAN_UP)
  311. close(rtc);
  312. }
  313. static void set_rtc_param(const char **pp_rtcname, char *rtc_param)
  314. {
  315. int rtc;
  316. struct rtc_param param;
  317. char *eq;
  318. /* handle param name */
  319. eq = strchr(rtc_param, '=');
  320. if (!eq)
  321. bb_simple_error_msg_and_die("expected <param>=<value>");
  322. *eq = '\0';
  323. param.param = resolve_rtc_param_alias(rtc_param);
  324. *eq = '=';
  325. /* handle param value */
  326. param.uvalue = xstrtoull(eq + 1, 0);
  327. rtc = rtc_xopen(pp_rtcname, O_WRONLY);
  328. printf("The RTC parameter 0x%llx will be set to 0x%llx.\n",
  329. (unsigned long long) param.param, (unsigned long long) param.uvalue);
  330. xioctl(rtc, RTC_PARAM_SET, &param);
  331. if (ENABLE_FEATURE_CLEAN_UP)
  332. close(rtc);
  333. }
  334. // hwclock from util-linux 2.36.1
  335. // hwclock [function] [option...]
  336. //Functions:
  337. // -r, --show display the RTC time
  338. // --get display drift corrected RTC time
  339. // --set set the RTC according to --date
  340. // -s, --hctosys set the system time from the RTC
  341. // -w, --systohc set the RTC from the system time
  342. // --systz send timescale configurations to the kernel
  343. // -a, --adjust adjust the RTC to account for systematic drift
  344. // --predict predict the drifted RTC time according to --date
  345. //Options:
  346. // -u, --utc the RTC timescale is UTC
  347. // -l, --localtime the RTC timescale is Local
  348. // -f, --rtc <file> use an alternate file to /dev/rtc0
  349. // --directisa use the ISA bus instead of /dev/rtc0 access
  350. // --date <time> date/time input for --set and --predict
  351. // --delay <sec> delay used when set new RTC time
  352. // --update-drift update the RTC drift factor
  353. // --noadjfile do not use /etc/adjtime
  354. // --adjfile <file> use an alternate file to /etc/adjtime
  355. // --test dry run; implies --verbose
  356. // -v, --verbose display more details
  357. //usage:#define hwclock_trivial_usage
  358. //usage: "[-ul] [-f DEV] [-s|-w|--systz|--param-get PARAM|--param-set PARAM=VAL]"
  359. //usage:#define hwclock_full_usage "\n\n"
  360. //usage: "Show or set hardware clock (RTC)\n"
  361. //usage: "\n -f DEV Use this device (e.g. /dev/rtc2)"
  362. //usage: "\n -u Assume RTC is kept in UTC"
  363. //usage: "\n -l Assume RTC is kept in local time"
  364. //usage: "\n (if neither is given, read from "ADJTIME_PATH")"
  365. ///////: "\n -r Show RTC time"
  366. ///////-r is default, don't bother showing it in help
  367. //usage: "\n -s Set system time from RTC"
  368. //usage: "\n -w Set RTC from system time"
  369. //usage: "\n --systz Set in-kernel timezone, correct system time"
  370. //usage: "\n if RTC is kept in local time"
  371. //usage: "\n --param-get PARAM Get RTC parameter"
  372. //usage: "\n --param-set PARAM=VAL Set RTC parameter"
  373. int hwclock_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  374. int hwclock_main(int argc UNUSED_PARAM, char **argv)
  375. {
  376. const char *rtcname = NULL;
  377. char *param;
  378. unsigned opt, exclusive;
  379. int utc;
  380. #define OPT_LOCALTIME (1 << 0)
  381. #define OPT_UTC (1 << 1)
  382. #define OPT_RTCFILE (1 << 2)
  383. #define OPT_SHOW (1 << 3)
  384. #define OPT_HCTOSYS (1 << 4)
  385. #define OPT_SYSTOHC (1 << 5)
  386. #define OPT_PARAM_GET (1 << 6)
  387. #define OPT_PARAM_SET (1 << 7)
  388. //#define OPT_VERBOSE (1 << 8) UNUSED
  389. #define OPT_SYSTZ (1 << 9)
  390. static const char hwclock_longopts[] ALIGN1 =
  391. "localtime\0" No_argument "l"
  392. "utc\0" No_argument "u"
  393. "rtc\0" Required_argument "f"
  394. "show\0" No_argument "r"
  395. "hctosys\0" No_argument "s"
  396. "systohc\0" No_argument "w"
  397. "param-get\0" Required_argument "\xfd" /* no short equivalent */
  398. "param-set\0" Required_argument "\xfe" /* no short equivalent */
  399. "systz\0" No_argument "\xff" /* no short equivalent */
  400. ;
  401. opt = getopt32long(argv,
  402. "^""luf:rsw\xfd:\xfe:v" /* -v is accepted and ignored */
  403. "\0"
  404. "l--u:u--l",
  405. hwclock_longopts,
  406. &rtcname,
  407. &param,
  408. &param
  409. );
  410. #if 0 //DEBUG
  411. bb_error_msg("opt:0x%x", opt);
  412. if (opt & OPT_PARAM_GET) bb_error_msg("OPT_PARAM_GET %s", param);
  413. if (opt & OPT_PARAM_SET) bb_error_msg("OPT_PARAM_SET %s", param);
  414. if (opt & OPT_SYSTZ ) bb_error_msg("OPT_SYSTZ");
  415. return 0;
  416. #endif
  417. /* All options apart from -luf are exclusive, enforce */
  418. exclusive = opt >> 3;
  419. if ((exclusive - 1) & exclusive) /* more than one bit set? */
  420. bb_show_usage();
  421. /* If -u or -l wasn't given, check if we are using utc */
  422. if (opt & (OPT_UTC | OPT_LOCALTIME))
  423. utc = (opt & OPT_UTC);
  424. else
  425. utc = rtc_adjtime_is_utc();
  426. if (opt & OPT_HCTOSYS)
  427. to_sys_clock(&rtcname, utc);
  428. else if (opt & OPT_SYSTOHC)
  429. from_sys_clock(&rtcname, utc);
  430. else if (opt & OPT_SYSTZ)
  431. set_kernel_timezone_and_clock(utc, NULL);
  432. else if (opt & OPT_PARAM_GET)
  433. get_rtc_param(&rtcname, param);
  434. else if (opt & OPT_PARAM_SET)
  435. set_rtc_param(&rtcname, param);
  436. else
  437. /* default OPT_SHOW */
  438. show_clock(&rtcname, utc);
  439. return 0;
  440. }