VirtualBox

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

Last change on this file since 44248 was 43363, checked in by vboxsync, 12 years ago

Haiku Additions.

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