VirtualBox

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

Last change on this file since 28112 was 26231, checked in by vboxsync, 15 years ago

VBoxServiceTimeSyncSet: Drop the return value, nobody is using it.

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