aboutsummaryrefslogtreecommitdiffstats
path: root/erts/emulator/sys/win32/sys_time.c
blob: b292d9279e9158d92af38b42746ea47de488691f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
/*
 * %CopyrightBegin%
 * 
 * Copyright Ericsson AB 1997-2013. All Rights Reserved.
 * 
 * The contents of this file are subject to the Erlang Public License,
 * Version 1.1, (the "License"); you may not use this file except in
 * compliance with the License. You should have received a copy of the
 * Erlang Public License along with this software. If not, it can be
 * retrieved online at http://www.erlang.org/.
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 * the License for the specific language governing rights and limitations
 * under the License.
 * 
 * %CopyrightEnd%
 */
/*
 * Purpose: System-dependent time functions.
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif
#include "sys.h"
#include "assert.h"
#include "erl_os_monotonic_time_extender.h"
#include "erl_time.h"

#define LL_LITERAL(X) ERTS_I64_LITERAL(X)

/******************* Routines for time measurement *********************/

#define EPOCH_JULIAN_DIFF LL_LITERAL(11644473600)
#define TICKS_PER_SECOND LL_LITERAL(10000000)
#define SECONDS_PER_DAY LL_LITERAL(86400)

#define ULI_TO_FILETIME(ft,ull)			\
 do {						\
     (ft).dwLowDateTime = (ull).LowPart;	\
     (ft).dwHighDateTime = (ull).HighPart;	\
 } while (0)

#define FILETIME_TO_ULI(ull,ft)			\
 do {						\
     (ull).LowPart = (ft).dwLowDateTime;	\
     (ull).HighPart = (ft).dwHighDateTime;	\
 } while (0)


#define EPOCH_TO_FILETIME(ft, epoch) \
    do { \
	ULARGE_INTEGER ull; \
	ull.QuadPart = (((epoch) + EPOCH_JULIAN_DIFF) * TICKS_PER_SECOND); \
	ULI_TO_FILETIME(ft,ull); \
    } while(0)

#define FILETIME_TO_EPOCH(epoch, ft) \
    do { \
	ULARGE_INTEGER ull; \
	FILETIME_TO_ULI(ull,ft); \
	(epoch) = ((ull.QuadPart / TICKS_PER_SECOND) - EPOCH_JULIAN_DIFF); \
    } while(0)
 
/* Getting timezone information is a heavy operation, so we want to do this 
   only once */

static TIME_ZONE_INFORMATION static_tzi;
static int have_static_tzi = 0;

static int days_in_month[2][13] = {
    {0,31,28,31,30,31,30,31,31,30,31,30,31},
    {0,31,29,31,30,31,30,31,31,30,31,30,31}};

#define ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT 10

/*
 * erts_os_monotonic_time()
 */

struct sys_time_internal_state_read_only__ {
    ULONGLONG (WINAPI *pGetTickCount64)(void);
    BOOL (WINAPI *pQueryPerformanceCounter)(LARGE_INTEGER *);
    Sint32 pcf;
    int using_get_tick_count_time_unit;
};

struct sys_time_internal_state_read_mostly__ {
    ErtsOsMonotonicTimeExtendState os_mtime_xtnd;
};

struct sys_time_internal_state_write_freq__ {
    erts_smp_mtx_t mtime_mtx;
    ULONGLONG wrap;
    ULONGLONG last_tick_count;
};

__declspec(align(ASSUMED_CACHE_LINE_SIZE)) struct {
    union {
	struct sys_time_internal_state_read_only__ o;
	char align__[(((sizeof(struct sys_time_internal_state_read_only__) - 1)
		       / ASSUMED_CACHE_LINE_SIZE) + 1)
		     * ASSUMED_CACHE_LINE_SIZE];
    } r;
    union {
	struct sys_time_internal_state_read_mostly__ m;
	char align__[(((sizeof(struct sys_time_internal_state_read_mostly__) - 1)
		       / ASSUMED_CACHE_LINE_SIZE) + 1)
		     * ASSUMED_CACHE_LINE_SIZE];
    } wr;
    union {
	struct sys_time_internal_state_write_freq__ f;
	char align__[(((sizeof(struct sys_time_internal_state_write_freq__) - 1)
		       / ASSUMED_CACHE_LINE_SIZE) + 1)
		     * ASSUMED_CACHE_LINE_SIZE];
    } w;
} internal_state;

__declspec(align(ASSUMED_CACHE_LINE_SIZE)) ErtsSysTimeData__ erts_sys_time_data__;


static ERTS_INLINE ErtsSystemTime
SystemTime2MilliSec(SYSTEMTIME *stp)
{
    ErtsSystemTime stime;
    FILETIME ft;
    ULARGE_INTEGER ull;

    SystemTimeToFileTime(stp, &ft);
    FILETIME_TO_ULI(ull,ft);
    /* now in 100 ns units */
    stime = (ErtsSystemTime) ull.QuadPart;
    stime -= (((ErtsSystemTime) EPOCH_JULIAN_DIFF)
	      * ((ErtsSystemTime) (10*1000*1000)));
    stime /= (ErtsSystemTime) (10*1000); /* ms */
    return stime;
}

static ErtsMonotonicTime
os_monotonic_time_qpc(void)
{
    LARGE_INTEGER pc;

    if (!(*internal_state.r.o.pQueryPerformanceCounter)(&pc))
	erl_exit(ERTS_ABORT_EXIT, "QueryPerformanceCounter() failed\n");

    return (ErtsMonotonicTime) pc.QuadPart;
}

static void
os_times_qpc(ErtsMonotonicTime *mtimep, ErtsSystemTime *stimep)
{
    LARGE_INTEGER pc;
    SYSTEMTIME st;
    ErtsSystemTime stime;
    BOOL qpcr;

    qpcr = (*internal_state.r.o.pQueryPerformanceCounter)(&pc);
    GetSystemTime(&st);

    if (!qpcr)
	erl_exit(ERTS_ABORT_EXIT, "QueryPerformanceCounter() failed\n");

    *mtimep = (ErtsMonotonicTime) pc.QuadPart;

    stime = SystemTime2MilliSec(&st);

    *stimep = ((ErtsSystemTime)
	       erts_time_unit_conversion((Uint64) stime,
					 (Uint32) 1000,
					 internal_state.r.o.pcf));
}

static Uint32
get_tick_count(void)
{
    return (Uint32) GetTickCount();
}

static ErtsMonotonicTime
os_monotonic_time_gtc32(void) 
{
    ErtsMonotonicTime mtime;
    Uint32 ticks = (Uint32) GetTickCount();
    ERTS_CHK_EXTEND_OS_MONOTONIC_TIME(&internal_state.wr.m.os_mtime_xtnd,
				      ticks);
    mtime = ERTS_EXTEND_OS_MONOTONIC_TIME(&internal_state.wr.m.os_mtime_xtnd,
					  ticks);
    mtime <<= ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
    return mtime;
}

static void
os_times_gtc32(ErtsMonotonicTime *mtimep, ErtsSystemTime *stimep)
{
    SYSTEMTIME st;
    ErtsSystemTime stime, mtime;
    Uint32 ticks;

    ticks = (Uint32) GetTickCount();
    GetSystemTime(&st);

    ERTS_CHK_EXTEND_OS_MONOTONIC_TIME(&internal_state.wr.m.os_mtime_xtnd,
				      ticks);
    mtime = ERTS_EXTEND_OS_MONOTONIC_TIME(&internal_state.wr.m.os_mtime_xtnd,
					  ticks);
    mtime <<= ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
    *mtimep = mtime;

    stime = SystemTime2MilliSec(&st);
    stime <<= ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
    *stimep = stime;

}

static ErtsMonotonicTime
os_monotonic_time_gtc64(void) 
{
    ULONGLONG ticks = (*internal_state.r.o.pGetTickCount64)();
    ErtsMonotonicTime mtime = (ErtsMonotonicTime) ticks;
    return mtime << ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
}

static void
os_times_gtc64(ErtsMonotonicTime *mtimep, ErtsSystemTime *stimep)
{
    SYSTEMTIME st;
    ErtsSystemTime stime, mtime;
    ULONGLONG ticks;

    ticks = (*internal_state.r.o.pGetTickCount64)();
    GetSystemTime(&st);

    mtime = (ErtsMonotonicTime) ticks;
    mtime <<= ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
    *mtimep = mtime;

    stime = SystemTime2MilliSec(&st);
    stime <<= ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
    *stimep = stime;
}

static ErtsSysHrTime
sys_hrtime_qpc(void)
{
    LARGE_INTEGER pc;

    if (!(*internal_state.r.o.pQueryPerformanceCounter)(&pc))
	erl_exit(ERTS_ABORT_EXIT, "QueryPerformanceCounter() failed\n");

    ASSERT(pc.QuadPart > 0);

    return (ErtsSysHrTime) erts_time_unit_conversion((Uint64) pc.QuadPart,
						     internal_state.r.o.pcf,
						     (Uint32) 1000*1000*1000);
}

static ErtsSysHrTime
sys_hrtime_gtc32(void)
{
    ErtsSysHrTime time;
    Uint32 ticks = (Uint32) GetTickCount();
    ERTS_CHK_EXTEND_OS_MONOTONIC_TIME(&internal_state.wr.m.os_mtime_xtnd,
				      tick_count);
    time = (ErtsSysHrTime) ERTS_EXTEND_OS_MONOTONIC_TIME(&internal_state.wr.m.os_mtime_xtnd,
							 ticks);
    time *= (ErtsSysHrTime) (1000 * 1000);
    return time;
}

static ErtsSysHrTime
sys_hrtime_gtc64(void)
{
    ErtsSysHrTime time = (*internal_state.r.o.pGetTickCount64)();
    time *= (ErtsSysHrTime) (1000*1000);
    return time;
}

/*
 * Init
 */

void
sys_init_time(ErtsSysInitTimeResult *init_resp)
{
    ErtsMonotonicTime (*os_mtime_func)(void);
    void (*os_times_func)(ErtsMonotonicTime *, ErtsSystemTime *);
    ErtsSysHrTime (*sys_hrtime_func)(void) = NULL;
    ErtsMonotonicTime time_unit;
    char kernel_dll_name[] = "kernel32";
    HMODULE module;

    init_resp->os_monotonic_time_info.clock_id = NULL;

    module = GetModuleHandle(kernel_dll_name);
    if (!module) {
    get_tick_count:
	erts_smp_mtx_init(&internal_state.w.f.mtime_mtx,
			  "os_monotonic_time");
	internal_state.w.f.wrap = 0;
	internal_state.w.f.last_tick_count = 0;

	init_resp->os_monotonic_time_info.func = "GetTickCount";
	init_resp->os_monotonic_time_info.locked_use = 0;
	/* 10-16 ms resolution according to MicroSoft documentation */
	init_resp->os_monotonic_time_info.resolution = 100; /* 10 ms */
	time_unit = (ErtsMonotonicTime) 1000;
	time_unit <<= ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
	internal_state.r.o.using_get_tick_count_time_unit = 1;
	os_mtime_func = os_monotonic_time_gtc32;
	os_times_func = os_times_gtc32;
	init_resp->os_monotonic_time_info.extended = 1;
	erts_init_os_monotonic_time_extender(&internal_state.wr.m.os_mtime_xtnd,
					     get_tick_count,
					     60*60*24*7); /* Check once a week */
	if (!sys_hrtime_func)
	    sys_hrtime_func = sys_hrtime_gtc32;
    }
    else {
	int major, minor, build;

	os_version(&major, &minor, &build);

	if (major < 6) {

	get_tick_count64:

	    internal_state.r.o.pGetTickCount64
		= ((ULONGLONG (WINAPI *)(void))
		   GetProcAddress(module, "GetTickCount64"));
	    if (!internal_state.r.o.pGetTickCount64)
		goto get_tick_count;

	    init_resp->os_monotonic_time_info.func = "GetTickCount64";
	    init_resp->os_monotonic_time_info.locked_use = 0;
	    /* 10-16 ms resolution according to MicroSoft documentation */
	    init_resp->os_monotonic_time_info.resolution = 100; /* 10 ms */
	    time_unit = (ErtsMonotonicTime) 1000;
	    time_unit <<= ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
	    internal_state.r.o.using_get_tick_count_time_unit = 1;
	    os_mtime_func = os_monotonic_time_gtc64;
	    os_times_func = os_times_gtc64;
	    if (!sys_hrtime_func)
		sys_hrtime_func = sys_hrtime_gtc64;
	}
	else { /* Vista or newer... */

	    LARGE_INTEGER pf;
	    BOOL (WINAPI *QPF)(LARGE_INTEGER *);

	    QPF = ((BOOL (WINAPI *)(LARGE_INTEGER *))
		   GetProcAddress(module, "QueryPerformanceFrequency"));
	    if (!QPF)
		goto get_tick_count64;
	    if (!(*QPF)(&pf))
		goto get_tick_count64;

	    internal_state.r.o.pQueryPerformanceCounter
		= ((BOOL (WINAPI *)(LARGE_INTEGER *))
		   GetProcAddress(module, "QueryPerformanceCounter"));
	    if (!internal_state.r.o.pQueryPerformanceCounter)
		goto get_tick_count64;

	    if (pf.QuadPart < (((LONGLONG) 1) << 32)) {
		internal_state.r.o.pcf = (Uint32) pf.QuadPart;
		sys_hrtime_func = sys_hrtime_qpc;
	    }
	    
	    /*
	     * We only use QueryPerformanceCounter() for
	     * os-monotonic-time if its frequency is equal
	     * to, or larger than GHz in order to ensure
	     * that the user wont be able to observe faulty
	     * order between values retrieved on different threads.
	     */
	    if (pf.QuadPart < (LONGLONG) 1000*1000*1000)
		goto get_tick_count64;

	    init_resp->os_monotonic_time_info.func = "QueryPerformanceCounter";
	    init_resp->os_monotonic_time_info.locked_use = 0;
	    time_unit = (ErtsMonotonicTime) pf.QuadPart;
	    internal_state.r.o.using_get_tick_count_time_unit = 0;
	    init_resp->os_monotonic_time_info.resolution = time_unit;
	    os_mtime_func = os_monotonic_time_qpc;
	    os_times_func = os_times_qpc;
	}
    }

    erts_sys_time_data__.r.o.os_monotonic_time = os_mtime_func;
    erts_sys_time_data__.r.o.os_times = os_times_func;
    init_resp->os_monotonic_time_unit = time_unit;
    init_resp->have_os_monotonic_time = 1;
    init_resp->sys_clock_resolution = 1;

    init_resp->os_system_time_info.func = "GetSystemTime";    
    init_resp->os_system_time_info.clock_id = NULL;
    init_resp->os_system_time_info.resolution = 100;
    init_resp->os_system_time_info.locked_use = 0;

    if(GetTimeZoneInformation(&static_tzi) && 
       static_tzi.StandardDate.wMonth != 0 &&
       static_tzi.DaylightDate.wMonth != 0) {
	have_static_tzi = 1;
    }
}

void
erts_late_sys_init_time(void)
{
    if (erts_sys_time_data__.r.o.os_monotonic_time == os_monotonic_time_gtc32)
	erts_late_init_os_monotonic_time_extender(&internal_state.wr.m.os_mtime_xtnd);
}

/* Returns a switchtimes for DST as UTC filetimes given data from a 
   TIME_ZONE_INFORMATION, see sys_localtime_r for usage. */ 
static void 
get_dst_switchtime(DWORD year, 
		   SYSTEMTIME dstinfo, LONG bias,
		   FILETIME *utc_switchtime) 
{
    DWORD occu;
    DWORD weekday,wday_1st;
    DWORD day, days_in;
    FILETIME tmp,tmp2;
    ULARGE_INTEGER ull;
    int leap_year = 0;
    if (dstinfo.wYear != 0) {
	/* A year specific transition, in which case the data in the structure
	   is already properly set for a specific year. Compare year
	   with parameter and see if they correspond, in that case generate a 
	   filetime directly, otherwise set the filetime to 0 */
	if (year != dstinfo.wYear) {
	    utc_switchtime->dwLowDateTime = utc_switchtime->dwHighDateTime = 0;
	    return;
	} 
    } else {
	occu = dstinfo.wDay;
	weekday = dstinfo.wDayOfWeek;

	dstinfo.wDayOfWeek = 0;
	dstinfo.wDay = 1;
	dstinfo.wYear = year;
	
	SystemTimeToFileTime(&dstinfo,&tmp);
	ull.LowPart = tmp.dwLowDateTime;
	ull.HighPart = tmp.dwHighDateTime;
    
	ull.QuadPart /= (TICKS_PER_SECOND*SECONDS_PER_DAY); /* Julian Day */
	wday_1st = (DWORD) ((ull.QuadPart + LL_LITERAL(1)) % LL_LITERAL(7));
	day = (weekday >= wday_1st) ? 
	    weekday - wday_1st + 1 :
	    weekday - wday_1st + 8;
	--occu;
	if (((dstinfo.wYear % 4) == 0 && (dstinfo.wYear % 100) > 0) ||
	    ((dstinfo.wYear % 400) == 0)) {
	    leap_year = 1;
	}
	days_in = days_in_month[leap_year][dstinfo.wMonth];
	while (occu > 0 && (day + 7 <= days_in)) {
	    --occu;
	    day += 7;
	}
	dstinfo.wDay = day;
    }
    SystemTimeToFileTime(&dstinfo,&tmp);
    /* correct for bias */
    ull.LowPart = tmp.dwLowDateTime;
    ull.HighPart = tmp.dwHighDateTime;
    ull.QuadPart += (((LONGLONG) bias) * LL_LITERAL(60) * TICKS_PER_SECOND);
    utc_switchtime->dwLowDateTime = ull.LowPart;
    utc_switchtime->dwHighDateTime = ull.HighPart;
    return;
}

/* This function gives approximately the correct year from a FILETIME
   Around the actual new year, it may return the wrong value, but that's OK
   as DST never switches around new year. */
static DWORD 
approx_year(FILETIME ft)
{
    ULARGE_INTEGER ull;
    FILETIME_TO_ULI(ull,ft);
    ull.QuadPart /= LL_LITERAL(1000);
    ull.QuadPart /= SECONDS_PER_DAY;
    ull.QuadPart /= LL_LITERAL(3652425);
    ull.QuadPart += 1601;
    return (DWORD) ull.QuadPart;
}

struct tm *
sys_localtime_r(time_t *epochs, struct tm *ptm)
{
    FILETIME ft,lft;
    SYSTEMTIME st;
    
    if ((((*epochs) + EPOCH_JULIAN_DIFF) * TICKS_PER_SECOND) < 0LL) {
	fprintf(stderr,"1\r\n"); fflush(stderr);
	return NULL;
    }
    
    EPOCH_TO_FILETIME(ft,*epochs);
    ptm->tm_isdst = 0;
    if (have_static_tzi) {
	FILETIME dst_start, dst_stop;
	ULARGE_INTEGER ull;
	DWORD year = approx_year(ft);
	get_dst_switchtime(year,static_tzi.DaylightDate,
			   static_tzi.Bias+static_tzi.StandardBias,&dst_start);
	get_dst_switchtime(year,static_tzi.StandardDate,
			   static_tzi.Bias+static_tzi.StandardBias+
			   static_tzi.DaylightBias,
			   &dst_stop);
	FILETIME_TO_ULI(ull,ft);

	if (CompareFileTime(&ft,&dst_start) >= 0 && 
	    CompareFileTime(&ft,&dst_stop) < 0) {
	    ull.QuadPart -= 
		((LONGLONG) static_tzi.Bias+static_tzi.StandardBias+
		 static_tzi.DaylightBias) * 
		LL_LITERAL(60) * TICKS_PER_SECOND;
	    ptm->tm_isdst = 1;
	} else {
	    ull.QuadPart -= 
		((LONGLONG) static_tzi.Bias+static_tzi.StandardBias) 
		* LL_LITERAL(60) * TICKS_PER_SECOND;
	}
	ULI_TO_FILETIME(ft,ull);
    } else {
	if (!FileTimeToLocalFileTime(&ft,&lft)) {
	    return NULL;
	}
	ft = lft;
    }
    
    if (!FileTimeToSystemTime(&ft,&st)) {
	return NULL;
    }
    
    ptm->tm_year = (int) st.wYear - 1900;
    ptm->tm_mon  = (int) st.wMonth - 1;
    ptm->tm_mday = (int) st.wDay;
    ptm->tm_hour = (int) st.wHour;
    ptm->tm_min  = (int) st.wMinute;
    ptm->tm_sec  = (int) st.wSecond;
    ptm->tm_wday  = (int) st.wDayOfWeek;
    {
	int yday = ptm->tm_mday - 1;
	int m =  ptm->tm_mon;
	int leap_year = 0;
	if (((st.wYear % 4) == 0 && (st.wYear % 100) > 0) ||
	    ((st.wYear % 400) == 0)) {
	    leap_year = 1;
	}
	while (m > 0) {
	    yday +=days_in_month[leap_year][m];
	    --m;
	}
	ptm->tm_yday = yday;
    }
    return ptm;
}

struct tm * 
sys_gmtime_r(time_t *epochs, struct tm *ptm)
{
    FILETIME ft;
    SYSTEMTIME st;
    
    if ((((*epochs) + EPOCH_JULIAN_DIFF) * TICKS_PER_SECOND) < 0LL) {
	return NULL;
    }
    
    EPOCH_TO_FILETIME(ft,*epochs);
    
    if (!FileTimeToSystemTime(&ft,&st)) {
	return NULL;
    }
    
    ptm->tm_year = (int) st.wYear - 1900;
    ptm->tm_mon  = (int) st.wMonth - 1;
    ptm->tm_mday = (int) st.wDay;
    ptm->tm_hour = (int) st.wHour;
    ptm->tm_min  = (int) st.wMinute;
    ptm->tm_sec  = (int) st.wSecond;
    ptm->tm_wday  = (int) st.wDayOfWeek;
    ptm->tm_isdst  = 0;
    {
	int yday = ptm->tm_mday - 1;
	int m =  ptm->tm_mon;
	int leap_year = 0;
	if (((st.wYear % 4) == 0 && (st.wYear % 100) > 0) ||
	    ((st.wYear % 400) == 0)) {
	    leap_year = 1;
	}
	while (m > 0) {
	    yday +=days_in_month[leap_year][m];
	    --m;
	}
	ptm->tm_yday = yday;
    }

    return ptm;
}

time_t 
sys_mktime(struct tm *ptm) 
{
    FILETIME ft;
    SYSTEMTIME st;
    int dst = 0;
    time_t epochs;

    memset(&st,0,sizeof(st));
    /* Convert relevant parts of truct tm to SYSTEMTIME */
    st.wYear =  (USHORT) (ptm->tm_year + 1900);
    st.wMonth =  (USHORT) (ptm->tm_mon + 1);
    st.wDay =  (USHORT) ptm->tm_mday;
    st.wHour =  (USHORT) ptm->tm_hour;
    st.wMinute =  (USHORT) ptm->tm_min;
    st.wSecond = (USHORT) ptm->tm_sec;

    SystemTimeToFileTime(&st,&ft);
    
    /* ft is now some kind of local file time, but it may be wrong depending 
       on what is in the tm_dst field. We need to manually convert it to
       UTC before turning it into epochs */

    if (have_static_tzi) {
	FILETIME dst_start, dst_stop;
	ULARGE_INTEGER ull_start,ull_stop,ull_ft;

	FILETIME_TO_ULI(ull_ft,ft);

	/* Correct everything except DST */
	ull_ft.QuadPart += (static_tzi.Bias+static_tzi.StandardBias) 
	    * LL_LITERAL(60) * TICKS_PER_SECOND;

	/* Determine if DST is active */
	if (ptm->tm_isdst >= 0) {
	    dst = ptm->tm_isdst;
	} else if (static_tzi.DaylightDate.wMonth != 0){
	    /* This is how windows mktime does it, meaning it does not
	       take nonexisting local times into account */
	    get_dst_switchtime(st.wYear,static_tzi.DaylightDate,
			       static_tzi.Bias+static_tzi.StandardBias,
			       &dst_start);
	    get_dst_switchtime(st.wYear,static_tzi.StandardDate,
			       static_tzi.Bias+static_tzi.StandardBias+
			       static_tzi.DaylightBias,
			       &dst_stop);
	    FILETIME_TO_ULI(ull_start,dst_start);
	    FILETIME_TO_ULI(ull_stop,dst_stop);
	    if ((ull_ft.QuadPart >= ull_start.QuadPart) &&
		(ull_ft.QuadPart < ull_stop.QuadPart)) {
		/* We are in DST */
		dst = 1;
	    }
	}
	/* Correct for DST */
	if (dst) {
	    ull_ft.QuadPart += static_tzi.DaylightBias * 
		LL_LITERAL(60) * TICKS_PER_SECOND;
	}
	epochs = ((ull_ft.QuadPart / TICKS_PER_SECOND) - EPOCH_JULIAN_DIFF);
    } else {
	/* No DST, life is easy... */
	FILETIME lft;
	LocalFileTimeToFileTime(&ft,&lft);
	FILETIME_TO_EPOCH(epochs,lft);
    }
    /* Normalize the struct tm */
    sys_localtime_r(&epochs,ptm);
    return epochs;
}

void 
sys_gettimeofday(SysTimeval *tv)
{
    SYSTEMTIME t;
    FILETIME ft;
    ULARGE_INTEGER ull;

    GetSystemTime(&t);
    SystemTimeToFileTime(&t, &ft);
    FILETIME_TO_ULI(ull,ft);
    tv->tv_usec = (long) ((ull.QuadPart / LL_LITERAL(10)) % 
			  LL_LITERAL(1000000));
    tv->tv_sec = (long) ((ull.QuadPart / LL_LITERAL(10000000)) - 
			 EPOCH_JULIAN_DIFF);
}

ErtsSystemTime
erts_os_system_time(void)
{
    SYSTEMTIME st;
    ErtsSystemTime stime;

    GetSystemTime(&st);
    stime = SystemTime2MilliSec(&st);

    if (internal_state.r.o.using_get_tick_count_time_unit) {
	stime <<= ERTS_GET_TICK_COUNT_TIME_UNIT_SHIFT;
	return stime;
    }

    return ((ErtsSystemTime)
	    erts_time_unit_conversion((Uint64) stime,
				      (Uint32) 1000,
				      internal_state.r.o.pcf));
}


clock_t 
sys_times(SysTimes *buffer) {
    clock_t kernel_ticks = (GetTickCount() / 
			    (1000 / SYS_CLK_TCK)) & 0x7FFFFFFF;
    FILETIME dummy;
    LONGLONG user;
    LONGLONG system;
    
    buffer->tms_utime = buffer->tms_stime = buffer->tms_cutime = 
	buffer->tms_cstime = 0;

    if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
			(FILETIME *) &system, (FILETIME *) &user) == 0)
	return kernel_ticks;
    system /= (LONGLONG)(10000000 / SYS_CLK_TCK);
    user /= (LONGLONG)(10000000 / SYS_CLK_TCK);
    
    buffer->tms_utime = (clock_t) (user & LL_LITERAL(0x7FFFFFFF));
    buffer->tms_stime = (clock_t) (system & LL_LITERAL(0x7FFFFFFF));
    return kernel_ticks;
}