VirtualBox

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

Last change on this file since 83563 was 82968, checked in by vboxsync, 5 years ago

Copyright year updates by scm.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette