clocks.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "../libnetdata.h"
  3. // defaults are for compatibility
  4. // call clocks_init() once, to optimize these default settings
  5. static clockid_t clock_boottime_to_use = CLOCK_MONOTONIC;
  6. static clockid_t clock_monotonic_to_use = CLOCK_MONOTONIC;
  7. usec_t clock_monotonic_resolution = 1000;
  8. usec_t clock_realtime_resolution = 1000;
  9. #ifndef HAVE_CLOCK_GETTIME
  10. inline int clock_gettime(clockid_t clk_id __maybe_unused, struct timespec *ts) {
  11. struct timeval tv;
  12. if(unlikely(gettimeofday(&tv, NULL) == -1)) {
  13. error("gettimeofday() failed.");
  14. return -1;
  15. }
  16. ts->tv_sec = tv.tv_sec;
  17. ts->tv_nsec = (long)((tv.tv_usec % USEC_PER_SEC) * NSEC_PER_USEC);
  18. return 0;
  19. }
  20. #endif
  21. // Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments
  22. // or the incremental adjustments performed by adjtime(3). This clock does not count time that the system is suspended
  23. static void test_clock_monotonic_raw(void) {
  24. #ifdef CLOCK_MONOTONIC_RAW
  25. struct timespec ts;
  26. if(clock_gettime(CLOCK_MONOTONIC_RAW, &ts) == -1 && errno == EINVAL)
  27. clock_monotonic_to_use = CLOCK_MONOTONIC;
  28. else
  29. clock_monotonic_to_use = CLOCK_MONOTONIC_RAW;
  30. #else
  31. clock_monotonic_to_use = CLOCK_MONOTONIC;
  32. #endif
  33. }
  34. // When running a binary with CLOCK_BOOTTIME defined on a system with a linux kernel older than Linux 2.6.39 the
  35. // clock_gettime(2) system call fails with EINVAL. In that case it must fall-back to CLOCK_MONOTONIC.
  36. static void test_clock_boottime(void) {
  37. struct timespec ts;
  38. if(clock_gettime(CLOCK_BOOTTIME, &ts) == -1 && errno == EINVAL)
  39. clock_boottime_to_use = clock_monotonic_to_use;
  40. else
  41. clock_boottime_to_use = CLOCK_BOOTTIME;
  42. }
  43. static usec_t get_clock_resolution(clockid_t clock) {
  44. struct timespec ts;
  45. clock_getres(clock, &ts);
  46. return ts.tv_sec * USEC_PER_SEC + ts.tv_nsec * NSEC_PER_USEC;
  47. }
  48. // perform any initializations required for clocks
  49. void clocks_init(void) {
  50. // monotonic raw has to be tested before boottime
  51. test_clock_monotonic_raw();
  52. // boottime has to be tested after monotonic coarse
  53. test_clock_boottime();
  54. clock_monotonic_resolution = get_clock_resolution(clock_monotonic_to_use);
  55. clock_realtime_resolution = get_clock_resolution(CLOCK_REALTIME);
  56. // if for any reason these are zero, netdata will crash
  57. // since we use them as modulo to calculations
  58. if(!clock_realtime_resolution)
  59. clock_realtime_resolution = 1000;
  60. if(!clock_monotonic_resolution)
  61. clock_monotonic_resolution = 1000;
  62. }
  63. inline time_t now_sec(clockid_t clk_id) {
  64. struct timespec ts;
  65. if(unlikely(clock_gettime(clk_id, &ts) == -1)) {
  66. error("clock_gettime(%d, &timespec) failed.", clk_id);
  67. return 0;
  68. }
  69. return ts.tv_sec;
  70. }
  71. inline usec_t now_usec(clockid_t clk_id) {
  72. struct timespec ts;
  73. if(unlikely(clock_gettime(clk_id, &ts) == -1)) {
  74. error("clock_gettime(%d, &timespec) failed.", clk_id);
  75. return 0;
  76. }
  77. return (usec_t)ts.tv_sec * USEC_PER_SEC + (ts.tv_nsec % NSEC_PER_SEC) / NSEC_PER_USEC;
  78. }
  79. inline int now_timeval(clockid_t clk_id, struct timeval *tv) {
  80. struct timespec ts;
  81. if(unlikely(clock_gettime(clk_id, &ts) == -1)) {
  82. error("clock_gettime(%d, &timespec) failed.", clk_id);
  83. tv->tv_sec = 0;
  84. tv->tv_usec = 0;
  85. return -1;
  86. }
  87. tv->tv_sec = ts.tv_sec;
  88. tv->tv_usec = (suseconds_t)((ts.tv_nsec % NSEC_PER_SEC) / NSEC_PER_USEC);
  89. return 0;
  90. }
  91. inline time_t now_realtime_sec(void) {
  92. return now_sec(CLOCK_REALTIME);
  93. }
  94. inline usec_t now_realtime_usec(void) {
  95. return now_usec(CLOCK_REALTIME);
  96. }
  97. inline int now_realtime_timeval(struct timeval *tv) {
  98. return now_timeval(CLOCK_REALTIME, tv);
  99. }
  100. inline time_t now_monotonic_sec(void) {
  101. return now_sec(clock_monotonic_to_use);
  102. }
  103. inline usec_t now_monotonic_usec(void) {
  104. return now_usec(clock_monotonic_to_use);
  105. }
  106. inline int now_monotonic_timeval(struct timeval *tv) {
  107. return now_timeval(clock_monotonic_to_use, tv);
  108. }
  109. inline time_t now_monotonic_high_precision_sec(void) {
  110. return now_sec(CLOCK_MONOTONIC);
  111. }
  112. inline usec_t now_monotonic_high_precision_usec(void) {
  113. return now_usec(CLOCK_MONOTONIC);
  114. }
  115. inline int now_monotonic_high_precision_timeval(struct timeval *tv) {
  116. return now_timeval(CLOCK_MONOTONIC, tv);
  117. }
  118. inline time_t now_boottime_sec(void) {
  119. return now_sec(clock_boottime_to_use);
  120. }
  121. inline usec_t now_boottime_usec(void) {
  122. return now_usec(clock_boottime_to_use);
  123. }
  124. inline int now_boottime_timeval(struct timeval *tv) {
  125. return now_timeval(clock_boottime_to_use, tv);
  126. }
  127. inline usec_t timeval_usec(struct timeval *tv) {
  128. return (usec_t)tv->tv_sec * USEC_PER_SEC + (tv->tv_usec % USEC_PER_SEC);
  129. }
  130. inline msec_t timeval_msec(struct timeval *tv) {
  131. return (msec_t)tv->tv_sec * MSEC_PER_SEC + ((tv->tv_usec % USEC_PER_SEC) / MSEC_PER_SEC);
  132. }
  133. inline susec_t dt_usec_signed(struct timeval *now, struct timeval *old) {
  134. usec_t ts1 = timeval_usec(now);
  135. usec_t ts2 = timeval_usec(old);
  136. if(likely(ts1 >= ts2)) return (susec_t)(ts1 - ts2);
  137. return -((susec_t)(ts2 - ts1));
  138. }
  139. inline usec_t dt_usec(struct timeval *now, struct timeval *old) {
  140. usec_t ts1 = timeval_usec(now);
  141. usec_t ts2 = timeval_usec(old);
  142. return (ts1 > ts2) ? (ts1 - ts2) : (ts2 - ts1);
  143. }
  144. #ifdef __linux__
  145. void sleep_to_absolute_time(usec_t usec) {
  146. static int einval_printed = 0, enotsup_printed = 0, eunknown_printed = 0;
  147. clockid_t clock = CLOCK_REALTIME;
  148. struct timespec req = {
  149. .tv_sec = (time_t)(usec / USEC_PER_SEC),
  150. .tv_nsec = (suseconds_t)((usec % USEC_PER_SEC) * NSEC_PER_USEC)
  151. };
  152. errno = 0;
  153. int ret = 0;
  154. while( (ret = clock_nanosleep(clock, TIMER_ABSTIME, &req, NULL)) != 0 ) {
  155. if(ret == EINTR) {
  156. errno = 0;
  157. continue;
  158. }
  159. else {
  160. if (ret == EINVAL) {
  161. if (!einval_printed) {
  162. einval_printed++;
  163. error(
  164. "Invalid time given to clock_nanosleep(): clockid = %d, tv_sec = %lld, tv_nsec = %ld",
  165. clock,
  166. (long long)req.tv_sec,
  167. req.tv_nsec);
  168. }
  169. } else if (ret == ENOTSUP) {
  170. if (!enotsup_printed) {
  171. enotsup_printed++;
  172. error(
  173. "Invalid clock id given to clock_nanosleep(): clockid = %d, tv_sec = %lld, tv_nsec = %ld",
  174. clock,
  175. (long long)req.tv_sec,
  176. req.tv_nsec);
  177. }
  178. } else {
  179. if (!eunknown_printed) {
  180. eunknown_printed++;
  181. error(
  182. "Unknown return value %d from clock_nanosleep(): clockid = %d, tv_sec = %lld, tv_nsec = %ld",
  183. ret,
  184. clock,
  185. (long long)req.tv_sec,
  186. req.tv_nsec);
  187. }
  188. }
  189. sleep_usec(usec);
  190. }
  191. }
  192. };
  193. #endif
  194. #define HEARTBEAT_ALIGNMENT_STATISTICS_SIZE 10
  195. netdata_mutex_t heartbeat_alignment_mutex = NETDATA_MUTEX_INITIALIZER;
  196. static size_t heartbeat_alignment_id = 0;
  197. struct heartbeat_thread_statistics {
  198. size_t sequence;
  199. usec_t dt;
  200. };
  201. static struct heartbeat_thread_statistics heartbeat_alignment_values[HEARTBEAT_ALIGNMENT_STATISTICS_SIZE] = { 0 };
  202. void heartbeat_statistics(usec_t *min_ptr, usec_t *max_ptr, usec_t *average_ptr, size_t *count_ptr) {
  203. struct heartbeat_thread_statistics current[HEARTBEAT_ALIGNMENT_STATISTICS_SIZE];
  204. static struct heartbeat_thread_statistics old[HEARTBEAT_ALIGNMENT_STATISTICS_SIZE] = { 0 };
  205. memcpy(current, heartbeat_alignment_values, sizeof(struct heartbeat_thread_statistics) * HEARTBEAT_ALIGNMENT_STATISTICS_SIZE);
  206. usec_t min = 0, max = 0, total = 0, average = 0;
  207. size_t i, count = 0;
  208. for(i = 0; i < HEARTBEAT_ALIGNMENT_STATISTICS_SIZE ;i++) {
  209. if(current[i].sequence == old[i].sequence) continue;
  210. usec_t value = current[i].dt - old[i].dt;
  211. if(!count) {
  212. min = max = total = value;
  213. count = 1;
  214. }
  215. else {
  216. total += value;
  217. if(value < min) min = value;
  218. if(value > max) max = value;
  219. count++;
  220. }
  221. }
  222. if(count)
  223. average = total / count;
  224. if(min_ptr) *min_ptr = min;
  225. if(max_ptr) *max_ptr = max;
  226. if(average_ptr) *average_ptr = average;
  227. if(count_ptr) *count_ptr = count;
  228. memcpy(old, current, sizeof(struct heartbeat_thread_statistics) * HEARTBEAT_ALIGNMENT_STATISTICS_SIZE);
  229. }
  230. inline void heartbeat_init(heartbeat_t *hb) {
  231. hb->realtime = 0ULL;
  232. hb->randomness = 250 * USEC_PER_MS + ((now_realtime_usec() * clock_realtime_resolution) % (250 * USEC_PER_MS));
  233. hb->randomness -= (hb->randomness % clock_realtime_resolution);
  234. netdata_mutex_lock(&heartbeat_alignment_mutex);
  235. hb->statistics_id = heartbeat_alignment_id;
  236. heartbeat_alignment_id++;
  237. netdata_mutex_unlock(&heartbeat_alignment_mutex);
  238. if(hb->statistics_id < HEARTBEAT_ALIGNMENT_STATISTICS_SIZE) {
  239. heartbeat_alignment_values[hb->statistics_id].dt = 0;
  240. heartbeat_alignment_values[hb->statistics_id].sequence = 0;
  241. }
  242. }
  243. // waits for the next heartbeat
  244. // it waits using the monotonic clock
  245. // it returns the dt using the realtime clock
  246. usec_t heartbeat_next(heartbeat_t *hb, usec_t tick) {
  247. if(unlikely(hb->randomness > tick / 2)) {
  248. // TODO: The heartbeat tick should be specified at the heartbeat_init() function
  249. usec_t tmp = (now_realtime_usec() * clock_realtime_resolution) % (tick / 2);
  250. error_limit_static_global_var(erl, 10, 0);
  251. error_limit(&erl, "heartbeat randomness of %llu is too big for a tick of %llu - setting it to %llu", hb->randomness, tick, tmp);
  252. hb->randomness = tmp;
  253. }
  254. usec_t dt;
  255. usec_t now = now_realtime_usec();
  256. usec_t next = now - (now % tick) + tick + hb->randomness;
  257. // align the next time we want to the clock resolution
  258. if(next % clock_realtime_resolution)
  259. next = next - (next % clock_realtime_resolution) + clock_realtime_resolution;
  260. // sleep_usec() has a loop to guarantee we will sleep for at least the requested time.
  261. // According the specs, when we sleep for a relative time, clock adjustments should not affect the duration
  262. // we sleep.
  263. sleep_usec_with_now(next - now, now);
  264. now = now_realtime_usec();
  265. dt = now - hb->realtime;
  266. if(hb->statistics_id < HEARTBEAT_ALIGNMENT_STATISTICS_SIZE) {
  267. heartbeat_alignment_values[hb->statistics_id].dt += now - next;
  268. heartbeat_alignment_values[hb->statistics_id].sequence++;
  269. }
  270. if(unlikely(now < next)) {
  271. errno = 0;
  272. error_limit_static_global_var(erl, 10, 0);
  273. error_limit(&erl, "heartbeat clock: woke up %llu microseconds earlier than expected (can be due to the CLOCK_REALTIME set to the past).", next - now);
  274. }
  275. else if(unlikely(now - next > tick / 2)) {
  276. errno = 0;
  277. error_limit_static_global_var(erl, 10, 0);
  278. error_limit(&erl, "heartbeat clock: woke up %llu microseconds later than expected (can be due to system load or the CLOCK_REALTIME set to the future).", now - next);
  279. }
  280. if(unlikely(!hb->realtime)) {
  281. // the first time return zero
  282. dt = 0;
  283. }
  284. hb->realtime = now;
  285. return dt;
  286. }
  287. void sleep_usec_with_now(usec_t usec, usec_t started_ut) {
  288. // we expect microseconds (1.000.000 per second)
  289. // but timespec is nanoseconds (1.000.000.000 per second)
  290. struct timespec rem = { 0, 0 }, req = {
  291. .tv_sec = (time_t) (usec / USEC_PER_SEC),
  292. .tv_nsec = (suseconds_t) ((usec % USEC_PER_SEC) * NSEC_PER_USEC)
  293. };
  294. // make sure errno is not EINTR
  295. errno = 0;
  296. if(!started_ut)
  297. started_ut = now_realtime_usec();
  298. usec_t end_ut = started_ut + usec;
  299. while (nanosleep(&req, &rem) != 0) {
  300. if (likely(errno == EINTR && (rem.tv_sec || rem.tv_nsec))) {
  301. req = rem;
  302. rem = (struct timespec){ 0, 0 };
  303. // break an infinite loop
  304. errno = 0;
  305. usec_t now_ut = now_realtime_usec();
  306. if(now_ut >= end_ut)
  307. break;
  308. usec_t remaining_ut = (usec_t)req.tv_sec * USEC_PER_SEC + (usec_t)req.tv_nsec * NSEC_PER_USEC > usec;
  309. usec_t check_ut = now_ut - started_ut;
  310. if(remaining_ut > check_ut) {
  311. req = (struct timespec){
  312. .tv_sec = (time_t) ( check_ut / USEC_PER_SEC),
  313. .tv_nsec = (suseconds_t) ((check_ut % USEC_PER_SEC) * NSEC_PER_USEC)
  314. };
  315. }
  316. }
  317. else {
  318. error("Cannot nanosleep() for %llu microseconds.", usec);
  319. break;
  320. }
  321. }
  322. }
  323. static inline collected_number uptime_from_boottime(void) {
  324. #ifdef CLOCK_BOOTTIME_IS_AVAILABLE
  325. return (collected_number)(now_boottime_usec() / USEC_PER_MS);
  326. #else
  327. error("uptime cannot be read from CLOCK_BOOTTIME on this system.");
  328. return 0;
  329. #endif
  330. }
  331. static procfile *read_proc_uptime_ff = NULL;
  332. static inline collected_number read_proc_uptime(char *filename) {
  333. if(unlikely(!read_proc_uptime_ff)) {
  334. read_proc_uptime_ff = procfile_open(filename, " \t", PROCFILE_FLAG_DEFAULT);
  335. if(unlikely(!read_proc_uptime_ff)) return 0;
  336. }
  337. read_proc_uptime_ff = procfile_readall(read_proc_uptime_ff);
  338. if(unlikely(!read_proc_uptime_ff)) return 0;
  339. if(unlikely(procfile_lines(read_proc_uptime_ff) < 1)) {
  340. error("/proc/uptime has no lines.");
  341. return 0;
  342. }
  343. if(unlikely(procfile_linewords(read_proc_uptime_ff, 0) < 1)) {
  344. error("/proc/uptime has less than 1 word in it.");
  345. return 0;
  346. }
  347. return (collected_number)(strtondd(procfile_lineword(read_proc_uptime_ff, 0, 0), NULL) * 1000.0);
  348. }
  349. inline collected_number uptime_msec(char *filename){
  350. static int use_boottime = -1;
  351. if(unlikely(use_boottime == -1)) {
  352. collected_number uptime_boottime = uptime_from_boottime();
  353. collected_number uptime_proc = read_proc_uptime(filename);
  354. long long delta = (long long)uptime_boottime - (long long)uptime_proc;
  355. if(delta < 0) delta = -delta;
  356. if(delta <= 1000 && uptime_boottime != 0) {
  357. procfile_close(read_proc_uptime_ff);
  358. info("Using now_boottime_usec() for uptime (dt is %lld ms)", delta);
  359. use_boottime = 1;
  360. }
  361. else if(uptime_proc != 0) {
  362. info("Using /proc/uptime for uptime (dt is %lld ms)", delta);
  363. use_boottime = 0;
  364. }
  365. else {
  366. error("Cannot find any way to read uptime on this system.");
  367. return 1;
  368. }
  369. }
  370. collected_number uptime;
  371. if(use_boottime)
  372. uptime = uptime_from_boottime();
  373. else
  374. uptime = read_proc_uptime(filename);
  375. return uptime;
  376. }