3 Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010, 2011 Red Hat, Inc.
6 This file is part of Cygwin.
8 This software is a copyrighted work licensed under the terms of the
9 Cygwin license. Please consult the file "CYGWIN_LICENSE" for
12 #define __timezonefunc__
14 #include <sys/times.h>
15 #include <sys/timeb.h>
30 /* Max allowed diversion in 100ns of internal timer from system time. If
31 this difference is exceeded, the internal timer gets re-primed. */
32 #define JITTER (40 * 10000LL)
34 /* TODO: Putting this variable in the shared cygwin region partially solves
35 the problem of cygwin processes not recognizing date changes when other
36 cygwin processes set the date. There is still an additional problem of
37 long-running cygwin processes becoming confused when a non-cygwin process
38 sets the date. Unfortunately, it looks like a minor redesign is required
39 to handle that case. */
40 hires_ms gtod __attribute__((section (".cygwin_dll_common"), shared));
42 hires_ns NO_COPY ntod;
44 static inline LONGLONG
48 GetSystemTimeAsFileTime ((LPFILETIME) &x);
49 x.QuadPart -= FACTOR; /* Add conversion factor for UNIX vs. Windows base time */
54 static unsigned long long __stdcall
55 __to_clock_t (FILETIME *src, int flag)
57 unsigned long long total = ((unsigned long long) src->dwHighDateTime << 32) + ((unsigned)src->dwLowDateTime);
58 syscall_printf ("dwHighDateTime %u, dwLowDateTime %u", src->dwHighDateTime, src->dwLowDateTime);
60 /* Convert into clock ticks - the total is in 10ths of a usec. */
64 total /= (unsigned long long) (NSPERSEC / CLOCKS_PER_SEC);
65 syscall_printf ("total %08x %08x", (unsigned) (total>>32), (unsigned) (total));
69 /* times: POSIX 4.5.2.1 */
71 times (struct tms *buf)
73 FILETIME creation_time, exit_time, kernel_time, user_time;
76 if (efault.faulted (EFAULT))
77 return ((clock_t) -1);
79 LONGLONG ticks = gtod.uptime ();
80 /* Ticks is in milliseconds, convert to our ticks. Use long long to prevent
82 clock_t tc = (clock_t) (ticks * CLOCKS_PER_SEC / 1000);
84 GetProcessTimes (GetCurrentProcess (), &creation_time, &exit_time,
85 &kernel_time, &user_time);
87 syscall_printf ("ticks %d, CLOCKS_PER_SEC %d", ticks, CLOCKS_PER_SEC);
88 syscall_printf ("user_time %d, kernel_time %d, creation_time %d, exit_time %d",
89 user_time, kernel_time, creation_time, exit_time);
90 buf->tms_stime = __to_clock_t (&kernel_time, 0);
91 buf->tms_utime = __to_clock_t (&user_time, 0);
92 timeval_to_filetime (&myself->rusage_children.ru_stime, &kernel_time);
93 buf->tms_cstime = __to_clock_t (&kernel_time, 1);
94 timeval_to_filetime (&myself->rusage_children.ru_utime, &user_time);
95 buf->tms_cutime = __to_clock_t (&user_time, 1);
100 EXPORT_ALIAS (times, _times)
102 /* settimeofday: BSD */
104 settimeofday (const struct timeval *tv, const struct timezone *tz)
111 if (efault.faulted (EFAULT))
114 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000)
120 ptm = gmtime (&tv->tv_sec);
121 st.wYear = ptm->tm_year + 1900;
122 st.wMonth = ptm->tm_mon + 1;
123 st.wDayOfWeek = ptm->tm_wday;
124 st.wDay = ptm->tm_mday;
125 st.wHour = ptm->tm_hour;
126 st.wMinute = ptm->tm_min;
127 st.wSecond = ptm->tm_sec;
128 st.wMilliseconds = tv->tv_usec / 1000;
130 res = -!SetSystemTime (&st);
133 syscall_printf ("%d = settimeofday (%x, %x)", res, tv, tz);
141 /* timezone: standards? */
145 char *b = _my_tls.locals.timezone_buf;
148 __small_sprintf (b,"GMT%+d:%02d", (int) (-_timezone / 3600), (int) (abs (_timezone / 60) % 60));
152 /* Cygwin internal */
154 totimeval (struct timeval *dst, FILETIME *src, int sub, int flag)
156 long long x = __to_clock_t (src, flag);
158 x *= (int) (1e6) / CLOCKS_PER_SEC; /* Turn x into usecs */
159 x -= (long long) sub * (int) (1e6);
161 dst->tv_usec = x % (long long) (1e6); /* And split */
162 dst->tv_sec = x / (long long) (1e6);
165 /* FIXME: Make thread safe */
167 gettimeofday (struct timeval *tv, void *tzvp)
169 struct timezone *tz = (struct timezone *) tzvp;
171 LONGLONG now = gtod.usecs ();
173 if (now == (LONGLONG) -1)
176 tv->tv_sec = now / 1000000;
177 tv->tv_usec = now % 1000000;
186 tz->tz_minuteswest = _timezone / 60;
187 tz->tz_dsttime = _daylight;
193 EXPORT_ALIAS (gettimeofday, _gettimeofday)
195 /* Cygwin internal */
197 time_t_to_filetime (time_t time_in, FILETIME *out)
199 long long x = time_in * NSPERSEC + FACTOR;
200 out->dwHighDateTime = x >> 32;
201 out->dwLowDateTime = x;
204 /* Cygwin internal */
206 timespec_to_filetime (const struct timespec *time_in, FILETIME *out)
208 if (time_in->tv_nsec == UTIME_OMIT)
209 out->dwHighDateTime = out->dwLowDateTime = 0;
212 long long x = time_in->tv_sec * NSPERSEC +
213 time_in->tv_nsec / (1000000000/NSPERSEC) + FACTOR;
214 out->dwHighDateTime = x >> 32;
215 out->dwLowDateTime = x;
219 /* Cygwin internal */
221 timeval_to_filetime (const struct timeval *time_in, FILETIME *out)
223 long long x = time_in->tv_sec * NSPERSEC +
224 time_in->tv_usec * (NSPERSEC/1000000) + FACTOR;
225 out->dwHighDateTime = x >> 32;
226 out->dwLowDateTime = x;
229 /* Cygwin internal */
230 static timeval __stdcall
231 time_t_to_timeval (time_t in)
239 /* Cygwin internal */
240 static const struct timespec *
241 timeval_to_timespec (const struct timeval *tvp, struct timespec *tmp)
246 tmp[0].tv_sec = tvp[0].tv_sec;
247 tmp[0].tv_nsec = tvp[0].tv_usec * 1000;
248 if (tmp[0].tv_nsec < 0)
250 else if (tmp[0].tv_nsec > 999999999)
251 tmp[0].tv_nsec = 999999999;
253 tmp[1].tv_sec = tvp[1].tv_sec;
254 tmp[1].tv_nsec = tvp[1].tv_usec * 1000;
255 if (tmp[1].tv_nsec < 0)
257 else if (tmp[1].tv_nsec > 999999999)
258 tmp[1].tv_nsec = 999999999;
263 /* Cygwin internal */
264 /* Convert a Win32 time to "UNIX" format. */
266 to_time_t (FILETIME *ptr)
268 /* A file time is the number of 100ns since jan 1 1601
269 stuffed into two long words.
270 A time_t is the number of seconds since jan 1 1970. */
272 long long x = ((long long) ptr->dwHighDateTime << 32) + ((unsigned)ptr->dwLowDateTime);
274 /* pass "no time" as epoch */
278 x -= FACTOR; /* number of 100ns between 1601 and 1970 */
279 x /= (long long) NSPERSEC; /* number of 100ns in a second */
283 /* Cygwin internal */
284 /* Convert a Win32 time to "UNIX" timestruc_t format. */
286 to_timestruc_t (FILETIME *ptr, timestruc_t *out)
288 /* A file time is the number of 100ns since jan 1 1601
289 stuffed into two long words.
290 A timestruc_t is the number of seconds and microseconds since jan 1 1970
291 stuffed into a time_t and a long. */
294 long long x = ((long long) ptr->dwHighDateTime << 32) + ((unsigned)ptr->dwLowDateTime);
296 /* pass "no time" as epoch */
304 x -= FACTOR; /* number of 100ns between 1601 and 1970 */
305 rem = x % ((long long)NSPERSEC);
306 x /= (long long) NSPERSEC; /* number of 100ns in a second */
307 out->tv_nsec = rem * 100; /* as tv_nsec is in nanoseconds */
311 /* Cygwin internal */
312 /* Get the current time as a "UNIX" timestruc_t format. */
314 time_as_timestruc_t (timestruc_t * out)
318 GetSystemTimeAsFileTime (&filetime);
319 to_timestruc_t (&filetime, out);
322 /* time: POSIX 4.5.1.1, C 4.12.2.4 */
323 /* Return number of seconds since 00:00 UTC on jan 1, 1970 */
330 GetSystemTimeAsFileTime (&filetime);
331 res = to_time_t (&filetime);
335 syscall_printf ("%d = time (%x)", res, ptr);
341 utimens_worker (path_conv &win32, const struct timespec *tvp)
346 set_errno (win32.error);
349 fhandler_base *fh = NULL;
352 cygheap_fdenum cfd (true);
353 while (cfd.next () >= 0)
354 if (cfd->get_access () & (FILE_WRITE_ATTRIBUTES | GENERIC_WRITE)
355 && RtlEqualUnicodeString (cfd->pc.get_nt_native_path (),
356 win32.get_nt_native_path (),
357 cfd->pc.objcaseinsensitive ()))
366 if (!(fh = build_fh_pc (win32)))
371 debug_printf ("got %d error from build_fh_pc", fh->error ());
372 set_errno (fh->error ());
376 res = fh->utimens (tvp);
383 syscall_printf ("%d = utimes (%S, %p)",
384 res, win32.get_nt_native_path (), tvp);
388 /* utimes: POSIX/SUSv3 */
390 utimes (const char *path, const struct timeval *tvp)
392 path_conv win32 (path, PC_POSIX | PC_SYM_FOLLOW, stat_suffixes);
393 struct timespec tmp[2];
394 return utimens_worker (win32, timeval_to_timespec (tvp, tmp));
399 lutimes (const char *path, const struct timeval *tvp)
401 path_conv win32 (path, PC_POSIX | PC_SYM_NOFOLLOW, stat_suffixes);
402 struct timespec tmp[2];
403 return utimens_worker (win32, timeval_to_timespec (tvp, tmp));
406 /* futimens: POSIX/SUSv4 */
408 futimens (int fd, const struct timespec *tvp)
412 cygheap_fdget cfd (fd);
415 else if (cfd->get_access () & (FILE_WRITE_ATTRIBUTES | GENERIC_WRITE))
416 res = cfd->utimens (tvp);
418 res = utimens_worker (cfd->pc, tvp);
419 syscall_printf ("%d = futimens (%d, %p)", res, fd, tvp);
425 futimes (int fd, const struct timeval *tvp)
427 struct timespec tmp[2];
428 return futimens (fd, timeval_to_timespec (tvp, tmp));
431 /* utime: POSIX 5.6.6.1 */
433 utime (const char *path, const struct utimbuf *buf)
435 struct timeval tmp[2];
438 return utimes (path, 0);
440 debug_printf ("incoming utime act %x", buf->actime);
441 tmp[0] = time_t_to_timeval (buf->actime);
442 tmp[1] = time_t_to_timeval (buf->modtime);
444 return utimes (path, tmp);
447 /* ftime: standards? */
449 ftime (struct timeb *tp)
454 if (gettimeofday (&tv, &tz) < 0)
457 tp->time = tv.tv_sec;
458 tp->millitm = tv.tv_usec / 1000;
459 tp->timezone = tz.tz_minuteswest;
460 tp->dstflag = tz.tz_dsttime;
465 #define stupid_printf if (cygwin_finished_initializing) debug_printf
470 if (!QueryPerformanceFrequency (&ifreq))
476 int priority = GetThreadPriority (GetCurrentThread ());
478 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_TIME_CRITICAL);
479 if (!QueryPerformanceCounter (&primed_pc))
481 SetThreadPriority (GetCurrentThread (), priority);
486 freq = (double) ((double) 1000000000. / (double) ifreq.QuadPart);
488 SetThreadPriority (GetCurrentThread (), priority);
499 return (long long) -1;
503 if (!QueryPerformanceCounter (&now))
509 // FIXME: Use round() here?
510 now.QuadPart = (LONGLONG) (freq * (double) (now.QuadPart - primed_pc.QuadPart));
515 hires_ms::timeGetTime_ns ()
519 /* This is how timeGetTime is implemented in winmm.dll.
520 The real timeGetTime subtracts and adds some values which are constant
521 over the lifetime of the process. Since we don't need absolute accuracy
522 of the value returned by timeGetTime, only relative accuracy, we can skip
523 this step. However, if we ever find out that we need absolute accuracy,
524 here's how it works in it's full beauty:
526 - At process startup, winmm initializes two calibration values:
528 DWORD tick_count_start;
529 LARGE_INTEGER int_time_start;
532 tick_count_start = GetTickCount ();
535 int_time_start.HighPart = SharedUserData.InterruptTime.High1Time;
536 int_time_start.LowPart = SharedUserData.InterruptTime.LowPart;
538 while (int_time_start.HighPart
539 != SharedUserData.InterruptTime.High2Time);
541 while (tick_count_start != GetTickCount ();
543 - timeGetTime computes its return value in the loop as below, and then:
545 t.QuadPart -= int_time_start.QuadPart;
547 t.LowPart += tick_count_start;
552 t.HighPart = SharedUserData.InterruptTime.High1Time;
553 t.LowPart = SharedUserData.InterruptTime.LowPart;
555 while (t.HighPart != SharedUserData.InterruptTime.High2Time);
556 /* We use the value in full 100ns resolution in the calling functions
557 anyway, so we can skip dividing by 10000 here. */
566 int priority = GetThreadPriority (GetCurrentThread ());
567 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_TIME_CRITICAL);
568 initime_ns = systime_ns () - timeGetTime_ns ();
570 SetThreadPriority (GetCurrentThread (), priority);
581 LONGLONG t = systime_ns ();
582 LONGLONG res = initime_ns + timeGetTime_ns ();
583 if (llabs (res - t) > JITTER)
587 res = initime_ns + timeGetTime_ns ();
593 clock_gettime (clockid_t clk_id, struct timespec *tp)
595 if (CLOCKID_IS_PROCESS (clk_id))
597 pid_t pid = CLOCKID_TO_PID (clk_id);
599 KERNEL_USER_TIMES kut;
600 ULONG sizeof_kut = sizeof (KERNEL_USER_TIMES);
613 hProcess = OpenProcess (PROCESS_QUERY_INFORMATION, 0, p->dwProcessId);
614 NtQueryInformationProcess (hProcess, ProcessTimes, &kut, sizeof_kut, &sizeof_kut);
616 x = kut.KernelTime.QuadPart + kut.UserTime.QuadPart;
617 tp->tv_sec = x / (long long) NSPERSEC;
618 tp->tv_nsec = (x % (long long) NSPERSEC) * 100LL;
620 CloseHandle (hProcess);
624 if (CLOCKID_IS_THREAD (clk_id))
626 long thr_id = CLOCKID_TO_THREADID (clk_id);
628 KERNEL_USER_TIMES kut;
629 ULONG sizeof_kut = sizeof (KERNEL_USER_TIMES);
633 thr_id = pthread::self ()->getsequence_np ();
635 hThread = OpenThread (THREAD_QUERY_INFORMATION, 0, thr_id);
642 NtQueryInformationThread (hThread, ThreadTimes, &kut, sizeof_kut, &sizeof_kut);
644 x = kut.KernelTime.QuadPart + kut.UserTime.QuadPart;
645 tp->tv_sec = x / (long long) NSPERSEC;
646 tp->tv_nsec = (x % (long long) NSPERSEC) * 100LL;
648 CloseHandle (hThread);
656 LONGLONG now = gtod.nsecs ();
657 if (now == (LONGLONG) -1)
659 tp->tv_sec = now / NSPERSEC;
660 tp->tv_nsec = (now % NSPERSEC) * (1000000000 / NSPERSEC);
664 case CLOCK_MONOTONIC:
666 LONGLONG now = ntod.nsecs ();
667 if (now == (LONGLONG) -1)
670 tp->tv_sec = now / 1000000000;
671 tp->tv_nsec = (now % 1000000000);
684 clock_settime (clockid_t clk_id, const struct timespec *tp)
688 if (CLOCKID_IS_PROCESS (clk_id) || CLOCKID_IS_THREAD (clk_id))
689 /* According to POSIX, the privileges to set a particular clock
690 * are implementation-defined. On Linux, CPU-time clocks are not
691 * settable; do the same here.
698 if (clk_id != CLOCK_REALTIME)
704 tv.tv_sec = tp->tv_sec;
705 tv.tv_usec = tp->tv_nsec / 1000;
707 return settimeofday (&tv, NULL);
710 static DWORD minperiod; // FIXME: Maintain period after a fork.
713 hires_ns::resolution ()
720 return (long long) -1;
723 return (LONGLONG) freq;
727 hires_ms::resolution ()
732 ULONG coarsest, finest, actual;
734 status = NtQueryTimerResolution (&coarsest, &finest, &actual);
735 if (NT_SUCCESS (status))
736 minperiod = (DWORD) actual;
739 /* Try to empirically determine current timer resolution */
740 int priority = GetThreadPriority (GetCurrentThread ());
741 SetThreadPriority (GetCurrentThread (),
742 THREAD_PRIORITY_TIME_CRITICAL);
744 for (int i = 0; i < 4; i++)
747 LONGLONG then = timeGetTime_ns ();
748 while ((now = timeGetTime_ns ()) == then)
751 while ((now = timeGetTime_ns ()) == then)
753 period += now - then;
755 SetThreadPriority (GetCurrentThread (), priority);
757 minperiod = (DWORD) period;
764 clock_getres (clockid_t clk_id, struct timespec *tp)
766 if (CLOCKID_IS_PROCESS (clk_id) || CLOCKID_IS_THREAD (clk_id))
768 ULONG coarsest, finest, actual;
770 NtQueryTimerResolution (&coarsest, &finest, &actual);
771 tp->tv_sec = coarsest / NSPERSEC;
772 tp->tv_nsec = (coarsest % NSPERSEC) * 100;
780 DWORD period = gtod.resolution ();
781 tp->tv_sec = period / NSPERSEC;
782 tp->tv_nsec = (period % NSPERSEC) * 100;
786 case CLOCK_MONOTONIC:
788 LONGLONG period = ntod.resolution ();
789 tp->tv_sec = period / 1000000000;
790 tp->tv_nsec = period % 1000000000;
803 clock_setres (clockid_t clk_id, struct timespec *tp)
805 static NO_COPY bool period_set;
808 if (clk_id != CLOCK_REALTIME)
814 /* Convert to 100ns to match OS resolution. The OS uses ULONG values
815 to express resolution in 100ns units, so the coarsest timer resolution
816 is < 430 secs. Actually the coarsest timer resolution is only slightly
817 beyond 15ms, but this might change in future OS versions, so we play nice
819 ULONGLONG period = (tp->tv_sec * 10000000ULL) + ((tp->tv_nsec) / 100ULL);
821 /* clock_setres is non-POSIX/non-Linux. On QNX, the function always
822 rounds the incoming value to the nearest supported value. */
823 ULONG coarsest, finest, actual;
824 if (NT_SUCCESS (NtQueryTimerResolution (&coarsest, &finest, &actual)))
826 if (period > coarsest)
828 else if (finest > period)
833 && NT_SUCCESS (NtSetTimerResolution (minperiod, FALSE, &actual)))
836 status = NtSetTimerResolution (period, TRUE, &actual);
837 if (!NT_SUCCESS (status))
839 __seterrno_from_nt_status (status);
848 clock_getcpuclockid (pid_t pid, clockid_t *clk_id)
850 if (pid != 0 && !pinfo (pid)->exists ())
852 *clk_id = (clockid_t) PID_TO_CLOCKID (pid);