VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceTimeSync.cpp

Last change on this file was 103149, checked in by vboxsync, 3 months ago

Additions: Some warning fixes about externally visible functions which should be static, bugref:3409

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.2 KB
Line 
1/* $Id: VBoxServiceTimeSync.cpp 103149 2024-01-31 15:41:31Z vboxsync $ */
2/** @file
3 * VBoxService - Guest Additions TimeSync Service.
4 */
5
6/*
7 * Copyright (C) 2007-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/** @page pg_vgsvc_timesync VBoxService - The Time Sync Service
30 *
31 * The time sync subservice synchronizes the guest OS walltime with the host.
32 *
33 * The time sync service plays along with the Time Manager (TM) in the VMM
34 * to keep the guest time accurate using the host machine as a reference.
35 * Communication is facilitated by VMMDev. TM will try its best to make sure
36 * all timer ticks get delivered so that there isn't normally any need to
37 * adjust the guest time.
38 *
39 * There are three normal (= acceptable) cases:
40 * -# When the service starts up. This is because ticks and such might
41 * be lost during VM and OS startup. (Need to figure out exactly why!)
42 * -# When the TM is unable to deliver all the ticks and swallows a
43 * backlog of ticks. The threshold for this is configurable with
44 * a default of 60 seconds.
45 * -# The time is adjusted on the host. This can be caused manually by
46 * the user or by some time sync daemon (NTP, LAN server, etc.).
47 *
48 * There are a number of very odd case where adjusting is needed. Here
49 * are some of them:
50 * -# Timer device emulation inaccuracies (like rounding).
51 * -# Inaccuracies in time source VirtualBox uses.
52 * -# The Guest and/or Host OS doesn't perform proper time keeping. This
53 * can come about as a result of OS and/or hardware issues.
54 *
55 * The TM is our source for the host time and will make adjustments for
56 * current timer delivery lag. The simplistic approach taken by TM is to
57 * adjust the host time by the current guest timer delivery lag, meaning that
58 * if the guest is behind 1 second with PIT/RTC/++ ticks, this should be
59 * reflected in the guest wall time as well.
60 *
61 * Now, there is any amount of trouble we can cause by changing the time.
62 * Most applications probably use the wall time when they need to measure
63 * things. A walltime that is being juggled about every so often, even if just
64 * a little bit, could occasionally upset these measurements by for instance
65 * yielding negative results.
66 *
67 * This bottom line here is that the time sync service isn't really supposed
68 * to do anything and will try avoid having to do anything when possible.
69 *
70 * The implementation uses the latency it takes to query host time as the
71 * absolute maximum precision to avoid messing up under timer tick catchup
72 * and/or heavy host/guest load. (Rationale is that a *lot* of stuff may
73 * happen on our way back from ring-3 and TM/VMMDev since we're taking the
74 * route thru the inner EM loop with its force flag processing.)
75 *
76 * But this latency has to be measured from our perspective, which means it
77 * could just as easily come out as 0. (OS/2 and Windows guests only update
78 * the current time when the timer ticks for instance.) The good thing is
79 * that this isn't really a problem since we won't ever do anything unless
80 * the drift is noticeable.
81 *
82 * It now boils down to these three (configuration) factors:
83 * -# g_cMsTimeSyncMinAdjust - The minimum drift we will ever bother with.
84 * -# g_TimeSyncLatencyFactor - The factor we multiply the latency by to
85 * calculate the dynamic minimum adjust factor.
86 * -# g_cMsTimeSyncMaxLatency - When to start discarding the data as utterly
87 * useless and take a rest (someone is too busy to give us good data).
88 * -# g_TimeSyncSetThreshold - The threshold at which we will just set the time
89 * instead of trying to adjust it (milliseconds).
90 */
91
92
93/*********************************************************************************************************************************
94* Header Files *
95*********************************************************************************************************************************/
96#ifdef RT_OS_WINDOWS
97# include <iprt/win/windows.h>
98#else
99# include <unistd.h>
100# include <errno.h>
101# include <time.h>
102# include <sys/time.h>
103#endif
104
105#include <iprt/assert.h>
106#include <iprt/string.h>
107#include <iprt/semaphore.h>
108#include <iprt/time.h>
109#include <iprt/thread.h>
110#include <VBox/err.h>
111#include <VBox/VBoxGuestLib.h>
112#include "VBoxServiceInternal.h"
113#include "VBoxServiceUtils.h"
114
115
116/*********************************************************************************************************************************
117* Global Variables *
118*********************************************************************************************************************************/
119/** The timesync interval (milliseconds). */
120static uint32_t g_TimeSyncInterval = 0;
121/**
122 * @see pg_vgsvc_timesync
123 *
124 * @remark OS/2: There is either a 1 second resolution on the DosSetDateTime
125 * API or a bug in my settimeofday implementation. Thus, don't
126 * bother unless there is at least a 1 second drift.
127 */
128#ifdef RT_OS_OS2
129static uint32_t g_cMsTimeSyncMinAdjust = 1000;
130#else
131static uint32_t g_cMsTimeSyncMinAdjust = 100;
132#endif
133/** @see pg_vgsvc_timesync */
134static uint32_t g_TimeSyncLatencyFactor = 8;
135/** @see pg_vgsvc_timesync */
136static uint32_t g_cMsTimeSyncMaxLatency = 250;
137/** @see pg_vgsvc_timesync */
138static uint32_t g_TimeSyncSetThreshold = 20*60*1000;
139/** Whether the next adjustment should just set the time instead of trying to
140 * adjust it. This is used to implement --timesync-set-start.
141 * For purposes of setting the kernel timezone, OS/2 always starts with this. */
142#ifdef RT_OS_OS2
143static bool volatile g_fTimeSyncSetOnStart = true;
144#else
145static bool volatile g_fTimeSyncSetOnStart = false;
146#endif
147/** Whether to set the time when the VM was restored. */
148static bool g_fTimeSyncSetOnRestore = true;
149/** The logging verbosity level.
150 * This uses the global verbosity level by default. */
151static uint32_t g_cTimeSyncVerbosity = 0;
152
153/** Current error count. Used to decide when to bitch and when not to. */
154static uint32_t g_cTimeSyncErrors = 0;
155
156/** The semaphore we're blocking on. */
157static RTSEMEVENTMULTI g_TimeSyncEvent = NIL_RTSEMEVENTMULTI;
158
159/** The VM session ID. Changes whenever the VM is restored or reset. */
160static uint64_t g_idTimeSyncSession;
161
162#ifdef RT_OS_WINDOWS
163/** Process token. */
164static HANDLE g_hTokenProcess = NULL;
165/** Old token privileges. */
166static TOKEN_PRIVILEGES g_TkOldPrivileges;
167/** Backup values for time adjustment. */
168static DWORD g_dwWinTimeAdjustment;
169static DWORD g_dwWinTimeIncrement;
170static BOOL g_bWinTimeAdjustmentDisabled;
171#endif
172
173
174/**
175 * @interface_method_impl{VBOXSERVICE,pfnPreInit}
176 */
177static DECLCALLBACK(int) vgsvcTimeSyncPreInit(void)
178{
179 /* Use global verbosity as default. */
180 g_cTimeSyncVerbosity = g_cVerbosity;
181
182#ifdef VBOX_WITH_GUEST_PROPS
183 /** @todo Merge this function with vgsvcTimeSyncOption() to generalize
184 * the "command line args override guest property values" behavior. */
185
186 /*
187 * Read the service options from the VM's guest properties.
188 * Note that these options can be overridden by the command line options later.
189 */
190 uint32_t uGuestPropSvcClientID;
191 int rc = VbglR3GuestPropConnect(&uGuestPropSvcClientID);
192 if (RT_FAILURE(rc))
193 {
194 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
195 {
196 VGSvcVerbose(0, "VMInfo: Guest property service is not available, skipping\n");
197 rc = VINF_SUCCESS;
198 }
199 else
200 VGSvcError("Failed to connect to the guest property service! Error: %Rrc\n", rc);
201 }
202 else
203 {
204 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-interval",
205 &g_TimeSyncInterval, 50, UINT32_MAX - 1);
206 if ( RT_SUCCESS(rc)
207 || rc == VERR_NOT_FOUND)
208 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-min-adjust",
209 &g_cMsTimeSyncMinAdjust, 0, 3600000);
210 if ( RT_SUCCESS(rc)
211 || rc == VERR_NOT_FOUND)
212 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-latency-factor",
213 &g_TimeSyncLatencyFactor, 1, 1024);
214 if ( RT_SUCCESS(rc)
215 || rc == VERR_NOT_FOUND)
216 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-max-latency",
217 &g_cMsTimeSyncMaxLatency, 1, 3600000);
218 if ( RT_SUCCESS(rc)
219 || rc == VERR_NOT_FOUND)
220 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold",
221 &g_TimeSyncSetThreshold, 0, 7*24*60*60*1000 /* a week */);
222
223 if (VbglR3GuestPropExist(uGuestPropSvcClientID,
224 "/VirtualBox/GuestAdd/VBoxService/--timesync-set-start"))
225 g_fTimeSyncSetOnStart = true;
226
227 if (VbglR3GuestPropExist(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-no-set-start"))
228 g_fTimeSyncSetOnStart = false;
229
230
231 if (VbglR3GuestPropExist(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-on-restore"))
232 g_fTimeSyncSetOnRestore = true;
233
234 if (VbglR3GuestPropExist(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-no-set-on-restore"))
235 g_fTimeSyncSetOnRestore = false;
236
237 uint32_t uValue;
238 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-verbosity",
239 &uValue, 0 /*uMin*/, 255 /*uMax*/);
240 if (RT_SUCCESS(rc))
241 g_cTimeSyncVerbosity = uValue;
242
243 VbglR3GuestPropDisconnect(uGuestPropSvcClientID);
244 }
245
246 if (rc == VERR_NOT_FOUND) /* If a value is not found, don't be sad! */
247 rc = VINF_SUCCESS;
248 return rc;
249#else
250 /* Nothing to do here yet. */
251 return VINF_SUCCESS;
252#endif
253}
254
255
256/**
257 * Displays a verbose message based on the currently
258 * set timesync verbosity level.
259 *
260 * @param iLevel Minimum log level required to display this message.
261 * @param pszFormat The message text.
262 * @param ... Format arguments.
263 */
264static void vgsvcTimeSyncLog(unsigned iLevel, const char *pszFormat, ...)
265{
266 if (iLevel <= g_cTimeSyncVerbosity)
267 {
268 va_list va;
269 va_start(va, pszFormat);
270 VGSvcLogV(pszFormat, va);
271 va_end(va);
272 }
273}
274
275
276/**
277 * @interface_method_impl{VBOXSERVICE,pfnOption}
278 */
279static DECLCALLBACK(int) vgsvcTimeSyncOption(const char **ppszShort, int argc, char **argv, int *pi)
280{
281 int rc = VINF_SUCCESS;
282 if (ppszShort)
283 rc = -1 ;/* no short options */
284 else if (!strcmp(argv[*pi], "--timesync-interval"))
285 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_TimeSyncInterval, 50, UINT32_MAX - 1);
286 else if (!strcmp(argv[*pi], "--timesync-min-adjust"))
287 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_cMsTimeSyncMinAdjust, 0, 3600000);
288 else if (!strcmp(argv[*pi], "--timesync-latency-factor"))
289 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_TimeSyncLatencyFactor, 1, 1024);
290 else if (!strcmp(argv[*pi], "--timesync-max-latency"))
291 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_cMsTimeSyncMaxLatency, 1, 3600000);
292 else if (!strcmp(argv[*pi], "--timesync-set-threshold"))
293 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_TimeSyncSetThreshold, 0, 7*24*60*60*1000); /* a week */
294 else if (!strcmp(argv[*pi], "--timesync-set-start"))
295 g_fTimeSyncSetOnStart = true;
296 else if (!strcmp(argv[*pi], "--timesync-no-set-start"))
297 g_fTimeSyncSetOnStart = false;
298 else if (!strcmp(argv[*pi], "--timesync-set-on-restore"))
299 g_fTimeSyncSetOnRestore = true;
300 else if (!strcmp(argv[*pi], "--timesync-no-set-on-restore"))
301 g_fTimeSyncSetOnRestore = false;
302 else if (!strcmp(argv[*pi], "--timesync-verbosity"))
303 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_cTimeSyncVerbosity, 0 /*uMin*/, 255 /*uMax*/);
304 else
305 rc = -1;
306
307 return rc;
308}
309
310
311/**
312 * @interface_method_impl{VBOXSERVICE,pfnInit}
313 */
314static DECLCALLBACK(int) vgsvcTimeSyncInit(void)
315{
316 /*
317 * If not specified, find the right interval default.
318 * Then create the event sem to block on.
319 */
320 if (!g_TimeSyncInterval)
321 g_TimeSyncInterval = g_DefaultInterval * 1000;
322 if (!g_TimeSyncInterval)
323 g_TimeSyncInterval = 10 * 1000;
324
325 VbglR3GetSessionId(&g_idTimeSyncSession);
326 /* The status code is ignored as this information is not available with VBox < 3.2.10. */
327
328 int rc = RTSemEventMultiCreate(&g_TimeSyncEvent);
329 AssertRC(rc);
330#ifdef RT_OS_WINDOWS
331 if (RT_SUCCESS(rc))
332 {
333 /*
334 * Adjust privileges of this process so we can make system time adjustments.
335 */
336 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &g_hTokenProcess))
337 {
338 TOKEN_PRIVILEGES tkPriv;
339 RT_ZERO(tkPriv);
340 tkPriv.PrivilegeCount = 1;
341 tkPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
342 if (LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkPriv.Privileges[0].Luid))
343 {
344 DWORD cbRet = sizeof(g_TkOldPrivileges);
345 if (AdjustTokenPrivileges(g_hTokenProcess, FALSE, &tkPriv, sizeof(TOKEN_PRIVILEGES), &g_TkOldPrivileges, &cbRet))
346 rc = VINF_SUCCESS;
347 else
348 {
349 DWORD dwErr = GetLastError();
350 rc = RTErrConvertFromWin32(dwErr);
351 VGSvcError("vgsvcTimeSyncInit: Adjusting token privileges (SE_SYSTEMTIME_NAME) failed with status code %u/%Rrc!\n",
352 dwErr, rc);
353 }
354 }
355 else
356 {
357 DWORD dwErr = GetLastError();
358 rc = RTErrConvertFromWin32(dwErr);
359 VGSvcError("vgsvcTimeSyncInit: Looking up token privileges (SE_SYSTEMTIME_NAME) failed with status code %u/%Rrc!\n",
360 dwErr, rc);
361 }
362 if (RT_FAILURE(rc))
363 {
364 CloseHandle(g_hTokenProcess);
365 g_hTokenProcess = NULL;
366 }
367 }
368 else
369 {
370 DWORD dwErr = GetLastError();
371 rc = RTErrConvertFromWin32(dwErr);
372 VGSvcError("vgsvcTimeSyncInit: Opening process token (SE_SYSTEMTIME_NAME) failed with status code %u/%Rrc!\n",
373 dwErr, rc);
374 g_hTokenProcess = NULL;
375 }
376 }
377
378 if (g_pfnGetSystemTimeAdjustment)
379 {
380 if (g_pfnGetSystemTimeAdjustment(&g_dwWinTimeAdjustment, &g_dwWinTimeIncrement, &g_bWinTimeAdjustmentDisabled))
381 vgsvcTimeSyncLog(0, "vgsvcTimeSyncInit: Initially %ld (100ns) units per %ld (100 ns) units interval, disabled=%d\n",
382 g_dwWinTimeAdjustment, g_dwWinTimeIncrement, g_bWinTimeAdjustmentDisabled ? 1 : 0);
383 else
384 {
385 DWORD dwErr = GetLastError();
386 rc = RTErrConvertFromWin32(dwErr);
387 VGSvcError("vgsvcTimeSyncInit: Could not get time adjustment values! Last error: %ld!\n", dwErr);
388 }
389 }
390#endif /* RT_OS_WINDOWS */
391
392 return rc;
393}
394
395
396/**
397 * Try adjusting the time using adjtime or similar.
398 *
399 * @returns true on success, false on failure.
400 *
401 * @param pDrift The time adjustment.
402 */
403static bool vgsvcTimeSyncAdjust(PCRTTIMESPEC pDrift)
404{
405#ifdef RT_OS_WINDOWS
406/** @todo r=bird: g_hTokenProcess cannot be NULL here.
407 * vgsvcTimeSyncInit will fail and the service will not be started with
408 * it being NULL. vgsvcTimeSyncInit OTOH will *NOT* be called until the
409 * service thread has terminated. If anything
410 * else is the case, there is buggy code somewhere.*/
411 if (g_hTokenProcess == NULL) /* Is the token already closed when shutting down? */
412 return false;
413
414 /* The API appeared in NT 3.50. */
415 if ( !g_pfnSetSystemTimeAdjustment
416 || !g_pfnGetSystemTimeAdjustment)
417 return false;
418
419 DWORD dwWinTimeAdjustment, dwWinNewTimeAdjustment, dwWinTimeIncrement;
420 BOOL fWinTimeAdjustmentDisabled;
421 if (g_pfnGetSystemTimeAdjustment(&dwWinTimeAdjustment, &dwWinTimeIncrement, &fWinTimeAdjustmentDisabled))
422 {
423 DWORD dwDiffMax = g_dwWinTimeAdjustment * 0.50;
424 DWORD dwDiffNew = dwWinTimeAdjustment * 0.10;
425
426 if (RTTimeSpecGetMilli(pDrift) > 0)
427 {
428 dwWinNewTimeAdjustment = dwWinTimeAdjustment + dwDiffNew;
429 if (dwWinNewTimeAdjustment > (g_dwWinTimeAdjustment + dwDiffMax))
430 {
431 dwWinNewTimeAdjustment = g_dwWinTimeAdjustment + dwDiffMax;
432 dwDiffNew = dwDiffMax;
433 }
434 }
435 else
436 {
437 dwWinNewTimeAdjustment = dwWinTimeAdjustment - dwDiffNew;
438 if (dwWinNewTimeAdjustment < (g_dwWinTimeAdjustment - dwDiffMax))
439 {
440 dwWinNewTimeAdjustment = g_dwWinTimeAdjustment - dwDiffMax;
441 dwDiffNew = dwDiffMax;
442 }
443 }
444
445 vgsvcTimeSyncLog(3, "vgsvcTimeSyncAdjust: Drift=%lldms\n", RTTimeSpecGetMilli(pDrift));
446 vgsvcTimeSyncLog(3, "vgsvcTimeSyncAdjust: OrgTA=%ld, CurTA=%ld, NewTA=%ld, DiffNew=%ld, DiffMax=%ld\n",
447 g_dwWinTimeAdjustment, dwWinTimeAdjustment, dwWinNewTimeAdjustment, dwDiffNew, dwDiffMax);
448 if (g_pfnSetSystemTimeAdjustment(dwWinNewTimeAdjustment, FALSE /* Periodic adjustments enabled. */))
449 {
450 g_cTimeSyncErrors = 0;
451 return true;
452 }
453
454 if (g_cTimeSyncErrors++ < 10)
455 VGSvcError("vgsvcTimeSyncAdjust: SetSystemTimeAdjustment failed, error=%u\n", GetLastError());
456 }
457 else if (g_cTimeSyncErrors++ < 10)
458 VGSvcError("vgsvcTimeSyncAdjust: GetSystemTimeAdjustment failed, error=%ld\n", GetLastError());
459
460#elif defined(RT_OS_OS2) || defined(RT_OS_HAIKU)
461 /* No API for doing gradual time adjustments. */
462
463#else /* PORTME */
464 /*
465 * Try using adjtime(), most unix-like systems have this.
466 */
467 struct timeval tv;
468 RTTimeSpecGetTimeval(pDrift, &tv);
469 if (adjtime(&tv, NULL) == 0)
470 {
471 vgsvcTimeSyncLog(1, "vgsvcTimeSyncAdjust: adjtime by %RDtimespec\n", pDrift);
472 g_cTimeSyncErrors = 0;
473 return true;
474 }
475#endif
476
477 /* failed */
478 return false;
479}
480
481
482/**
483 * Cancels any pending time adjustment.
484 *
485 * Called when we've caught up and before calls to vgsvcTimeSyncSet.
486 */
487static void vgsvcTimeSyncCancelAdjust(void)
488{
489#ifdef RT_OS_WINDOWS
490/** @todo r=bird: g_hTokenProcess cannot be NULL here. See argumentation in
491 * vgsvcTimeSyncAdjust. */
492 if (g_hTokenProcess == NULL) /* No process token (anymore)? */
493 return;
494 if (!g_pfnSetSystemTimeAdjustment)
495 return;
496 if (g_pfnSetSystemTimeAdjustment(0, TRUE /* Periodic adjustments disabled. */))
497 vgsvcTimeSyncLog(5, "vgsvcTimeSyncCancelAdjust: Windows Time Adjustment is now disabled.\n");
498 else if (g_cTimeSyncErrors++ < 10)
499 VGSvcError("vgsvcTimeSyncCancelAdjust: SetSystemTimeAdjustment(,disable) failed, error=%u\n", GetLastError());
500#endif /* !RT_OS_WINDOWS */
501}
502
503
504/**
505 * Set the wall clock to compensate for drift.
506 *
507 * @param pDrift The time adjustment.
508 */
509static void vgsvcTimeSyncSet(PCRTTIMESPEC pDrift)
510{
511 /*
512 * Query the current time, adjust it by adding the drift and set it.
513 */
514 RTTIMESPEC NewGuestTime;
515 int rc = RTTimeSet(RTTimeSpecAdd(RTTimeNow(&NewGuestTime), pDrift));
516 if (RT_SUCCESS(rc))
517 {
518 /* Succeeded - reset the error count and log the change. */
519 g_cTimeSyncErrors = 0;
520
521 if (g_cTimeSyncVerbosity >= 1)
522 {
523 char sz[64];
524 RTTIME Time;
525 vgsvcTimeSyncLog(1, "time set to %s\n", RTTimeToString(RTTimeExplode(&Time, &NewGuestTime), sz, sizeof(sz)));
526#ifdef DEBUG
527 RTTIMESPEC Tmp;
528 vgsvcTimeSyncLog(3, " now %s\n", RTTimeToString(RTTimeExplode(&Time, RTTimeNow(&Tmp)), sz, sizeof(sz)));
529#endif
530 }
531 }
532 else if (g_cTimeSyncErrors++ < 10)
533 VGSvcError("vgsvcTimeSyncSet: RTTimeSet(%RDtimespec) failed: %Rrc\n", &NewGuestTime, rc);
534}
535
536
537/**
538 * @interface_method_impl{VBOXSERVICE,pfnWorker}
539 */
540static DECLCALLBACK(int) vgsvcTimeSyncWorker(bool volatile *pfShutdown)
541{
542 RTTIME Time;
543 int rc = VINF_SUCCESS;
544
545 /*
546 * Tell the control thread that it can continue spawning services.
547 */
548 RTThreadUserSignal(RTThreadSelf());
549
550 /*
551 * Initialize the last host and guest times to prevent log message.
552 * We also track whether we set the time in the previous loop.
553 */
554 RTTIMESPEC HostLast;
555 if (RT_FAILURE(VbglR3GetHostTime(&HostLast)))
556 RTTimeSpecSetNano(&HostLast, 0);
557 RTTIMESPEC GuestLast;
558 RTTimeNow(&GuestLast);
559 bool fSetTimeLastLoop = false;
560
561 /*
562 * The Work Loop.
563 */
564 for (;;)
565 {
566 /*
567 * Try to get a reliable time reading.
568 */
569 int cTries = 3;
570 do
571 {
572 /*
573 * Query the session id (first to keep lantency low) and the time.
574 */
575 uint64_t idNewSession = g_idTimeSyncSession;
576 if (g_fTimeSyncSetOnRestore)
577 VbglR3GetSessionId(&idNewSession);
578
579 RTTIMESPEC GuestNow0;
580 RTTimeNow(&GuestNow0);
581
582 RTTIMESPEC HostNow;
583 int rc2 = VbglR3GetHostTime(&HostNow);
584 if (RT_FAILURE(rc2))
585 {
586 if (g_cTimeSyncErrors++ < 10)
587 VGSvcError("vgsvcTimeSyncWorker: VbglR3GetHostTime failed; rc2=%Rrc\n", rc2);
588 break;
589 }
590
591 RTTIMESPEC GuestNow;
592 RTTimeNow(&GuestNow);
593
594 /*
595 * Calc latency and check if it's ok.
596 */
597 RTTIMESPEC GuestElapsed = GuestNow;
598 RTTimeSpecSub(&GuestElapsed, &GuestNow0);
599 if ((uint32_t)RTTimeSpecGetMilli(&GuestElapsed) < g_cMsTimeSyncMaxLatency)
600 {
601 /*
602 * If we were just restored, set the adjustment threshold to zero to force a resync.
603 */
604 uint32_t TimeSyncSetThreshold = g_TimeSyncSetThreshold;
605 if ( g_fTimeSyncSetOnRestore
606 && idNewSession != g_idTimeSyncSession)
607 {
608 vgsvcTimeSyncLog(2, "vgsvcTimeSyncWorker: The VM session ID changed, forcing resync.\n");
609 g_idTimeSyncSession = idNewSession;
610 TimeSyncSetThreshold = 0;
611 }
612
613 /*
614 * Calculate the adjustment threshold and the current drift.
615 */
616 uint32_t MinAdjust = RTTimeSpecGetMilli(&GuestElapsed) * g_TimeSyncLatencyFactor;
617 if (MinAdjust < g_cMsTimeSyncMinAdjust)
618 MinAdjust = g_cMsTimeSyncMinAdjust;
619
620 RTTIMESPEC Drift = HostNow;
621 RTTimeSpecSub(&Drift, &GuestNow);
622 if (RTTimeSpecGetMilli(&Drift) < 0)
623 MinAdjust += g_cMsTimeSyncMinAdjust; /* extra buffer against moving time backwards. */
624
625 RTTIMESPEC AbsDrift = Drift;
626 RTTimeSpecAbsolute(&AbsDrift);
627
628 if (g_cTimeSyncVerbosity >= 4)
629 {
630 char sz1[64];
631 char sz2[64];
632 vgsvcTimeSyncLog(4, "vgsvcTimeSyncWorker: Host: %s (MinAdjust: %RU32 ms), Guest: %s => %RDtimespec drift\n",
633 RTTimeToString(RTTimeExplode(&Time, &HostNow), sz1, sizeof(sz1)), MinAdjust,
634 RTTimeToString(RTTimeExplode(&Time, &GuestNow), sz2, sizeof(sz2)), &Drift);
635 }
636
637 bool fSetTimeInThisLoop = false;
638 uint64_t AbsDriftMilli = RTTimeSpecGetMilli(&AbsDrift);
639 if ( AbsDriftMilli > MinAdjust
640 || g_fTimeSyncSetOnStart)
641 {
642 /*
643 * Ok, the drift is above the threshold.
644 *
645 * Try a gradual adjustment first, if that fails or the drift is
646 * too big, fall back on just setting the time.
647 */
648 if ( AbsDriftMilli > TimeSyncSetThreshold
649 || g_fTimeSyncSetOnStart
650 || !vgsvcTimeSyncAdjust(&Drift))
651 {
652 vgsvcTimeSyncCancelAdjust();
653 vgsvcTimeSyncSet(&Drift);
654 fSetTimeInThisLoop = true;
655 }
656
657 /*
658 * Log radical host time changes.
659 */
660 int64_t cNsHostDelta = RTTimeSpecGetNano(&HostNow) - RTTimeSpecGetNano(&HostLast);
661 if ((uint64_t)RT_ABS(cNsHostDelta) > RT_NS_1HOUR / 2)
662 vgsvcTimeSyncLog(0, "vgsvcTimeSyncWorker: Radical host time change: %'RI64ns (HostNow=%RDtimespec HostLast=%RDtimespec)\n",
663 cNsHostDelta, &HostNow, &HostLast);
664 }
665 else
666 vgsvcTimeSyncCancelAdjust();
667 HostLast = HostNow;
668
669 /*
670 * Log radical guest time changes (we could be the cause of these, mind).
671 * Note! Right now we don't care about an extra log line after we called
672 * vgsvcTimeSyncSet. fSetTimeLastLoop helps show it though.
673 */
674 int64_t cNsGuestDelta = RTTimeSpecGetNano(&GuestNow) - RTTimeSpecGetNano(&GuestLast);
675 if ((uint64_t)RT_ABS(cNsGuestDelta) > RT_NS_1HOUR / 2)
676 vgsvcTimeSyncLog(0, "vgsvcTimeSyncWorker: Radical guest time change: %'RI64ns (GuestNow=%RDtimespec GuestLast=%RDtimespec fSetTimeLastLoop=%RTbool)\n",
677 cNsGuestDelta, &GuestNow, &GuestLast, fSetTimeLastLoop);
678 GuestLast = GuestNow;
679 fSetTimeLastLoop = fSetTimeInThisLoop;
680 break;
681 }
682 vgsvcTimeSyncLog(3, "vgsvcTimeSyncWorker: %RDtimespec: latency too high (%RDtimespec, max %ums) sleeping 1s\n",
683 &GuestNow, &GuestElapsed, g_cMsTimeSyncMaxLatency);
684 RTThreadSleep(1000);
685 } while (--cTries > 0);
686
687 /* Clear the set-next/set-start flag. */
688 g_fTimeSyncSetOnStart = false;
689
690 /*
691 * Block for a while.
692 *
693 * The event semaphore takes care of ignoring interruptions and it
694 * allows us to implement service wakeup later.
695 */
696 if (*pfShutdown)
697 break;
698 int rc2 = RTSemEventMultiWait(g_TimeSyncEvent, g_TimeSyncInterval);
699 if (*pfShutdown)
700 break;
701 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
702 {
703 VGSvcError("vgsvcTimeSyncWorker: RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
704 rc = rc2;
705 break;
706 }
707 }
708
709 vgsvcTimeSyncCancelAdjust();
710 return rc;
711}
712
713
714/**
715 * @interface_method_impl{VBOXSERVICE,pfnStop}
716 */
717static DECLCALLBACK(void) vgsvcTimeSyncStop(void)
718{
719 if (g_TimeSyncEvent != NIL_RTSEMEVENTMULTI)
720 RTSemEventMultiSignal(g_TimeSyncEvent);
721}
722
723
724/**
725 * @interface_method_impl{VBOXSERVICE,pfnTerm}
726 */
727static DECLCALLBACK(void) vgsvcTimeSyncTerm(void)
728{
729#ifdef RT_OS_WINDOWS
730 /*
731 * Restore the SE_SYSTEMTIME_NAME token privileges (if init succeeded).
732 */
733 if (g_hTokenProcess)
734 {
735 if (!AdjustTokenPrivileges(g_hTokenProcess, FALSE, &g_TkOldPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
736 {
737 DWORD dwErr = GetLastError();
738 VGSvcError("vgsvcTimeSyncTerm: Restoring token privileges (SE_SYSTEMTIME_NAME) failed with code %u!\n", dwErr);
739 }
740 CloseHandle(g_hTokenProcess);
741 g_hTokenProcess = NULL;
742 }
743#endif /* !RT_OS_WINDOWS */
744
745 if (g_TimeSyncEvent != NIL_RTSEMEVENTMULTI)
746 {
747 RTSemEventMultiDestroy(g_TimeSyncEvent);
748 g_TimeSyncEvent = NIL_RTSEMEVENTMULTI;
749 }
750}
751
752
753/**
754 * The 'timesync' service description.
755 */
756VBOXSERVICE g_TimeSync =
757{
758 /* pszName. */
759 "timesync",
760 /* pszDescription. */
761 "Time synchronization",
762 /* pszUsage. */
763 " [--timesync-interval <ms>] [--timesync-min-adjust <ms>]\n"
764 " [--timesync-latency-factor <x>] [--timesync-max-latency <ms>]\n"
765 " [--timesync-set-threshold <ms>]\n"
766 " [--timesync-set-start|--timesync-no-set-start]\n"
767 " [--timesync-set-on-restore|--timesync-no-set-on-restore]\n"
768 " [--timesync-verbosity <level>]"
769 ,
770 /* pszOptions. */
771 " --timesync-interval Specifies the interval at which to synchronize the\n"
772 " time with the host. The default is 10000 ms.\n"
773 " --timesync-min-adjust The minimum absolute drift value measured in\n"
774 " milliseconds to make adjustments for.\n"
775 " The default is 1000 ms on OS/2 and 100 ms elsewhere.\n"
776 " --timesync-latency-factor\n"
777 " The factor to multiply the time query latency with\n"
778 " to calculate the dynamic minimum adjust time.\n"
779 " The default is 8 times.\n"
780 " --timesync-max-latency The max host timer query latency to accept.\n"
781 " The default is 250 ms.\n"
782 " --timesync-set-threshold\n"
783 " The absolute drift threshold, given as milliseconds,\n"
784 " where to start setting the time instead of trying to\n"
785 " adjust it. The default is 20 min.\n"
786 " --timesync-set-start, --timesync-no-set-start \n"
787 " Set the time when starting the time sync service.\n"
788#ifdef RT_OS_OS2
789 " Default: --timesync-set-start\n"
790#else
791 " Default: --timesync-no-set-start\n"
792#endif
793 " --timesync-set-on-restore, --timesync-no-set-on-restore\n"
794 " Whether to immediately set the time when the VM is\n"
795 " restored or not. Default: --timesync-set-on-restore\n"
796 " --timesync-verbosity Sets the verbosity level. Defaults to service wide\n"
797 " verbosity level.\n"
798 ,
799 /* methods */
800 vgsvcTimeSyncPreInit,
801 vgsvcTimeSyncOption,
802 vgsvcTimeSyncInit,
803 vgsvcTimeSyncWorker,
804 vgsvcTimeSyncStop,
805 vgsvcTimeSyncTerm
806};
807
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use