Haiku Port
[p5sagit/p5-mst-13.2.git] / ext / Time / HiRes / HiRes.xs
1 /*
2  * 
3  * Copyright (c) 1996-2002 Douglas E. Wegscheid.  All rights reserved.
4  * 
5  * Copyright (c) 2002,2003,2004,2005,2006,2007,2008 Jarkko Hietaniemi.
6  * All rights reserved.
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the same terms as Perl itself.
10  */
11
12 #ifdef __cplusplus
13 extern "C" {
14 #endif
15 #define PERL_NO_GET_CONTEXT
16 #include "EXTERN.h"
17 #include "perl.h"
18 #include "XSUB.h"
19 #include "ppport.h"
20 #if defined(__CYGWIN__) && defined(HAS_W32API_WINDOWS_H)
21 # include <w32api/windows.h>
22 # define CYGWIN_WITH_W32API
23 #endif
24 #ifdef WIN32
25 # include <time.h>
26 #else
27 # include <sys/time.h>
28 #endif
29 #ifdef HAS_SELECT
30 # ifdef I_SYS_SELECT
31 #  include <sys/select.h>
32 # endif
33 #endif
34 #if defined(TIME_HIRES_CLOCK_GETTIME_SYSCALL) || defined(TIME_HIRES_CLOCK_GETRES_SYSCALL)
35 #include <syscall.h>
36 #endif
37 #ifdef __cplusplus
38 }
39 #endif
40
41 /* At least ppport.h 3.13 gets this wrong: one really cannot
42  * have NVgf as anything else than "g" under Perl 5.6.x. */
43 #if PERL_REVISION == 5 && PERL_VERSION == 6
44 # undef NVgf
45 # define NVgf "g"
46 #endif
47
48 #define IV_1E6 1000000
49 #define IV_1E7 10000000
50 #define IV_1E9 1000000000
51
52 #define NV_1E6 1000000.0
53 #define NV_1E7 10000000.0
54 #define NV_1E9 1000000000.0
55
56 #ifndef PerlProc_pause
57 #   define PerlProc_pause() Pause()
58 #endif
59
60 #ifdef HAS_PAUSE
61 #   define Pause   pause
62 #else
63 #   undef Pause /* In case perl.h did it already. */
64 #   define Pause() sleep(~0) /* Zzz for a long time. */
65 #endif
66
67 /* Though the cpp define ITIMER_VIRTUAL is available the functionality
68  * is not supported in Cygwin as of August 2004, ditto for Win32.
69  * Neither are ITIMER_PROF or ITIMER_REALPROF implemented.  --jhi
70  */
71 #if defined(__CYGWIN__) || defined(WIN32)
72 #   undef ITIMER_VIRTUAL
73 #   undef ITIMER_PROF
74 #   undef ITIMER_REALPROF
75 #endif
76
77 #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC)
78
79 /* HP-UX has CLOCK_XXX values but as enums, not as defines.
80  * The only way to detect these would be to test compile for each. */
81 # ifdef __hpux
82 /* However, it seems that at least in HP-UX 11.31 ia64 there *are*
83  * defines for these, so let's try detecting them. */
84 #  ifndef CLOCK_REALTIME
85 #    define CLOCK_REALTIME CLOCK_REALTIME
86 #    define CLOCK_VIRTUAL  CLOCK_VIRTUAL
87 #    define CLOCK_PROFILE  CLOCK_PROFILE
88 #  endif
89 # endif /* # ifdef __hpux */
90
91 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC) */
92
93 #if defined(WIN32) || defined(CYGWIN_WITH_W32API)
94
95 #ifndef HAS_GETTIMEOFDAY
96 #   define HAS_GETTIMEOFDAY
97 #endif
98
99 /* shows up in winsock.h?
100 struct timeval {
101  long tv_sec;
102  long tv_usec;
103 }
104 */
105
106 typedef union {
107     unsigned __int64    ft_i64;
108     FILETIME            ft_val;
109 } FT_t;
110
111 #define MY_CXT_KEY "Time::HiRes_" XS_VERSION
112
113 typedef struct {
114     unsigned long run_count;
115     unsigned __int64 base_ticks;
116     unsigned __int64 tick_frequency;
117     FT_t base_systime_as_filetime;
118     unsigned __int64 reset_time;
119 } my_cxt_t;
120
121 START_MY_CXT
122
123 /* Number of 100 nanosecond units from 1/1/1601 to 1/1/1970 */
124 #ifdef __GNUC__
125 # define Const64(x) x##LL
126 #else
127 # define Const64(x) x##i64
128 #endif
129 #define EPOCH_BIAS  Const64(116444736000000000)
130
131 #ifdef Const64
132 # ifdef __GNUC__
133 #  define IV_1E6LL  1000000LL /* Needed because of Const64() ##-appends LL (or i64). */
134 #  define IV_1E7LL  10000000LL
135 #  define IV_1E9LL  1000000000LL
136 # else
137 #  define IV_1E6i64 1000000i64
138 #  define IV_1E7i64 10000000i64
139 #  define IV_1E9i64 1000000000i64
140 # endif
141 #endif
142
143 /* NOTE: This does not compute the timezone info (doing so can be expensive,
144  * and appears to be unsupported even by glibc) */
145
146 /* dMY_CXT needs a Perl context and we don't want to call PERL_GET_CONTEXT
147    for performance reasons */
148
149 #undef gettimeofday
150 #define gettimeofday(tp, not_used) _gettimeofday(aTHX_ tp, not_used)
151
152 /* If the performance counter delta drifts more than 0.5 seconds from the
153  * system time then we recalibrate to the system time.  This means we may
154  * move *backwards* in time! */
155 #define MAX_PERF_COUNTER_SKEW Const64(5000000) /* 0.5 seconds */
156
157 /* Reset reading from the performance counter every five minutes.
158  * Many PC clocks just seem to be so bad. */
159 #define MAX_PERF_COUNTER_TICKS Const64(300000000) /* 300 seconds */
160
161 static int
162 _gettimeofday(pTHX_ struct timeval *tp, void *not_used)
163 {
164     dMY_CXT;
165
166     unsigned __int64 ticks;
167     FT_t ft;
168
169     if (MY_CXT.run_count++ == 0 ||
170         MY_CXT.base_systime_as_filetime.ft_i64 > MY_CXT.reset_time) {
171         QueryPerformanceFrequency((LARGE_INTEGER*)&MY_CXT.tick_frequency);
172         QueryPerformanceCounter((LARGE_INTEGER*)&MY_CXT.base_ticks);
173         GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
174         ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
175         MY_CXT.reset_time = ft.ft_i64 + MAX_PERF_COUNTER_TICKS;
176     }
177     else {
178         __int64 diff;
179         QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
180         ticks -= MY_CXT.base_ticks;
181         ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64
182                     + Const64(IV_1E7) * (ticks / MY_CXT.tick_frequency)
183                     +(Const64(IV_1E7) * (ticks % MY_CXT.tick_frequency)) / MY_CXT.tick_frequency;
184         diff = ft.ft_i64 - MY_CXT.base_systime_as_filetime.ft_i64;
185         if (diff < -MAX_PERF_COUNTER_SKEW || diff > MAX_PERF_COUNTER_SKEW) {
186             MY_CXT.base_ticks += ticks;
187             GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
188             ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
189         }
190     }
191
192     /* seconds since epoch */
193     tp->tv_sec = (long)((ft.ft_i64 - EPOCH_BIAS) / Const64(IV_1E7));
194
195     /* microseconds remaining */
196     tp->tv_usec = (long)((ft.ft_i64 / Const64(10)) % Const64(IV_1E6));
197
198     return 0;
199 }
200 #endif
201
202 #if defined(WIN32) && !defined(ATLEASTFIVEOHOHFIVE)
203 static unsigned int
204 sleep(unsigned int t)
205 {
206     Sleep(t*1000);
207     return 0;
208 }
209 #endif
210
211 #if !defined(HAS_GETTIMEOFDAY) && defined(VMS)
212 #define HAS_GETTIMEOFDAY
213
214 #include <lnmdef.h>
215 #include <time.h> /* gettimeofday */
216 #include <stdlib.h> /* qdiv */
217 #include <starlet.h> /* sys$gettim */
218 #include <descrip.h>
219 #ifdef __VAX
220 #include <lib$routines.h> /* lib$ediv() */
221 #endif
222
223 /*
224         VMS binary time is expressed in 100 nano-seconds since
225         system base time which is 17-NOV-1858 00:00:00.00
226 */
227
228 #define DIV_100NS_TO_SECS  10000000L
229 #define DIV_100NS_TO_USECS 10L
230
231 /* 
232         gettimeofday is supposed to return times since the epoch
233         so need to determine this in terms of VMS base time
234 */
235 static $DESCRIPTOR(dscepoch,"01-JAN-1970 00:00:00.00");
236
237 #ifdef __VAX
238 static long base_adjust[2]={0L,0L};
239 #else
240 static __int64 base_adjust=0;
241 #endif
242
243 /* 
244
245    If we don't have gettimeofday, then likely we are on a VMS machine that
246    operates on local time rather than UTC...so we have to zone-adjust.
247    This code gleefully swiped from VMS.C 
248
249 */
250 /* method used to handle UTC conversions:
251  *   1 == CRTL gmtime();  2 == SYS$TIMEZONE_DIFFERENTIAL;  3 == no correction
252  */
253 static int gmtime_emulation_type;
254 /* number of secs to add to UTC POSIX-style time to get local time */
255 static long int utc_offset_secs;
256 static struct dsc$descriptor_s fildevdsc = 
257   { 12, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$FILE_DEV" };
258 static struct dsc$descriptor_s *fildev[] = { &fildevdsc, NULL };
259
260 static time_t toutc_dst(time_t loc) {
261   struct tm *rsltmp;
262
263   if ((rsltmp = localtime(&loc)) == NULL) return -1;
264   loc -= utc_offset_secs;
265   if (rsltmp->tm_isdst) loc -= 3600;
266   return loc;
267 }
268
269 static time_t toloc_dst(time_t utc) {
270   struct tm *rsltmp;
271
272   utc += utc_offset_secs;
273   if ((rsltmp = localtime(&utc)) == NULL) return -1;
274   if (rsltmp->tm_isdst) utc += 3600;
275   return utc;
276 }
277
278 #define _toutc(secs)  ((secs) == (time_t) -1 ? (time_t) -1 : \
279        ((gmtime_emulation_type || timezone_setup()), \
280        (gmtime_emulation_type == 1 ? toutc_dst(secs) : \
281        ((secs) - utc_offset_secs))))
282
283 #define _toloc(secs)  ((secs) == (time_t) -1 ? (time_t) -1 : \
284        ((gmtime_emulation_type || timezone_setup()), \
285        (gmtime_emulation_type == 1 ? toloc_dst(secs) : \
286        ((secs) + utc_offset_secs))))
287
288 static int
289 timezone_setup(void) 
290 {
291   struct tm *tm_p;
292
293   if (gmtime_emulation_type == 0) {
294     int dstnow;
295     time_t base = 15 * 86400; /* 15jan71; to avoid month/year ends between    */
296                               /* results of calls to gmtime() and localtime() */
297                               /* for same &base */
298
299     gmtime_emulation_type++;
300     if ((tm_p = gmtime(&base)) == NULL) { /* CRTL gmtime() is a fake */
301       char off[LNM$C_NAMLENGTH+1];;
302
303       gmtime_emulation_type++;
304       if (!Perl_vmstrnenv("SYS$TIMEZONE_DIFFERENTIAL",off,0,fildev,0)) {
305         gmtime_emulation_type++;
306         utc_offset_secs = 0;
307         Perl_warn(aTHX_ "no UTC offset information; assuming local time is UTC");
308       }
309       else { utc_offset_secs = atol(off); }
310     }
311     else { /* We've got a working gmtime() */
312       struct tm gmt, local;
313
314       gmt = *tm_p;
315       tm_p = localtime(&base);
316       local = *tm_p;
317       utc_offset_secs  = (local.tm_mday - gmt.tm_mday) * 86400;
318       utc_offset_secs += (local.tm_hour - gmt.tm_hour) * 3600;
319       utc_offset_secs += (local.tm_min  - gmt.tm_min)  * 60;
320       utc_offset_secs += (local.tm_sec  - gmt.tm_sec);
321     }
322   }
323   return 1;
324 }
325
326
327 int
328 gettimeofday (struct timeval *tp, void *tpz)
329 {
330  long ret;
331 #ifdef __VAX
332  long quad[2];
333  long quad1[2];
334  long div_100ns_to_secs;
335  long div_100ns_to_usecs;
336  long quo,rem;
337  long quo1,rem1;
338 #else
339  __int64 quad;
340  __qdiv_t ans1,ans2;
341 #endif
342 /*
343         In case of error, tv_usec = 0 and tv_sec = VMS condition code.
344         The return from function is also set to -1.
345         This is not exactly as per the manual page.
346 */
347
348  tp->tv_usec = 0;
349
350 #ifdef __VAX
351  if (base_adjust[0]==0 && base_adjust[1]==0) {
352 #else
353  if (base_adjust==0) { /* Need to determine epoch adjustment */
354 #endif
355         ret=sys$bintim(&dscepoch,&base_adjust);
356         if (1 != (ret &&1)) {
357                 tp->tv_sec = ret;
358                 return -1;
359         }
360  }
361
362  ret=sys$gettim(&quad); /* Get VMS system time */
363  if ((1 && ret) == 1) {
364 #ifdef __VAX
365         quad[0] -= base_adjust[0]; /* convert to epoch offset */
366         quad[1] -= base_adjust[1]; /* convert 2nd half of quadword */
367         div_100ns_to_secs = DIV_100NS_TO_SECS;
368         div_100ns_to_usecs = DIV_100NS_TO_USECS;
369         lib$ediv(&div_100ns_to_secs,&quad,&quo,&rem);
370         quad1[0] = rem;
371         quad1[1] = 0L;
372         lib$ediv(&div_100ns_to_usecs,&quad1,&quo1,&rem1);
373         tp->tv_sec = quo; /* Whole seconds */
374         tp->tv_usec = quo1; /* Micro-seconds */
375 #else
376         quad -= base_adjust; /* convert to epoch offset */
377         ans1=qdiv(quad,DIV_100NS_TO_SECS);
378         ans2=qdiv(ans1.rem,DIV_100NS_TO_USECS);
379         tp->tv_sec = ans1.quot; /* Whole seconds */
380         tp->tv_usec = ans2.quot; /* Micro-seconds */
381 #endif
382  } else {
383         tp->tv_sec = ret;
384         return -1;
385  }
386 # ifdef VMSISH_TIME
387 # ifdef RTL_USES_UTC
388   if (VMSISH_TIME) tp->tv_sec = _toloc(tp->tv_sec);
389 # else
390   if (!VMSISH_TIME) tp->tv_sec = _toutc(tp->tv_sec);
391 # endif
392 # endif
393  return 0;
394 }
395 #endif
396
397
398  /* Do not use H A S _ N A N O S L E E P
399   * so that Perl Configure doesn't scan for it (and pull in -lrt and
400   * the like which are not usually good ideas for the default Perl).
401   * (We are part of the core perl now.)
402   * The TIME_HIRES_NANOSLEEP is set by Makefile.PL. */
403 #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP)
404 #define HAS_USLEEP
405 #define usleep hrt_nanosleep  /* could conflict with ncurses for static build */
406
407 void
408 hrt_nanosleep(unsigned long usec) /* This is used to emulate usleep. */
409 {
410     struct timespec res;
411     res.tv_sec = usec / IV_1E6;
412     res.tv_nsec = ( usec - res.tv_sec * IV_1E6 ) * 1000;
413     nanosleep(&res, NULL);
414 }
415
416 #endif /* #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP) */
417
418 #if !defined(HAS_USLEEP) && defined(HAS_SELECT)
419 #ifndef SELECT_IS_BROKEN
420 #define HAS_USLEEP
421 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
422
423 void
424 hrt_usleep(unsigned long usec)
425 {
426     struct timeval tv;
427     tv.tv_sec = 0;
428     tv.tv_usec = usec;
429     select(0, (Select_fd_set_t)NULL, (Select_fd_set_t)NULL,
430                 (Select_fd_set_t)NULL, &tv);
431 }
432 #endif
433 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_SELECT) */
434
435 #if !defined(HAS_USLEEP) && defined(WIN32)
436 #define HAS_USLEEP
437 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
438
439 void
440 hrt_usleep(unsigned long usec)
441 {
442     long msec;
443     msec = usec / 1000;
444     Sleep (msec);
445 }
446 #endif /* #if !defined(HAS_USLEEP) && defined(WIN32) */
447
448 #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP)
449 #define HAS_USLEEP
450 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
451
452 void
453 hrt_usleep(unsigned long usec)
454 {
455         struct timespec ts1;
456         ts1.tv_sec  = usec * 1000; /* Ignoring wraparound. */
457         ts1.tv_nsec = 0;
458         nanosleep(&ts1, NULL);
459 }
460
461 #endif /* #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP) */
462
463 #if !defined(HAS_USLEEP) && defined(HAS_POLL)
464 #define HAS_USLEEP
465 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
466
467 void
468 hrt_usleep(unsigned long usec)
469 {
470     int msec = usec / 1000;
471     poll(0, 0, msec);
472 }
473
474 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_POLL) */
475
476 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
477
478 static int
479 hrt_ualarm_itimero(struct itimerval* itv, int usec, int uinterval)
480 {
481    itv->it_value.tv_sec = usec / IV_1E6;
482    itv->it_value.tv_usec = usec % IV_1E6;
483    itv->it_interval.tv_sec = uinterval / IV_1E6;
484    itv->it_interval.tv_usec = uinterval % IV_1E6;
485    return setitimer(ITIMER_REAL, itv, 0);
486 }
487
488 int
489 hrt_ualarm_itimer(int usec, int uinterval)
490 {
491   struct itimerval itv;
492   return hrt_ualarm_itimero(&itv, usec, uinterval);
493 }
494
495 #ifdef HAS_UALARM
496 int
497 hrt_ualarm(int usec, int interval) /* for binary compat before 1.91 */
498 {
499    return hrt_ualarm_itimer(usec, interval);
500 }
501 #endif /* #ifdef HAS_UALARM */
502 #endif /* #if !defined(HAS_UALARM) && defined(HAS_SETITIMER) */
503
504 #if !defined(HAS_UALARM) && defined(HAS_SETITIMER)
505 #define HAS_UALARM
506 #define ualarm hrt_ualarm_itimer  /* could conflict with ncurses for static build */
507 #endif
508
509 #if !defined(HAS_UALARM) && defined(VMS)
510 #define HAS_UALARM
511 #define ualarm vms_ualarm 
512
513 #include <lib$routines.h>
514 #include <ssdef.h>
515 #include <starlet.h>
516 #include <descrip.h>
517 #include <signal.h>
518 #include <jpidef.h>
519 #include <psldef.h>
520
521 #define VMSERR(s)   (!((s)&1))
522
523 static void
524 us_to_VMS(useconds_t mseconds, unsigned long v[])
525 {
526     int iss;
527     unsigned long qq[2];
528
529     qq[0] = mseconds;
530     qq[1] = 0;
531     v[0] = v[1] = 0;
532
533     iss = lib$addx(qq,qq,qq);
534     if (VMSERR(iss)) lib$signal(iss);
535     iss = lib$subx(v,qq,v);
536     if (VMSERR(iss)) lib$signal(iss);
537     iss = lib$addx(qq,qq,qq);
538     if (VMSERR(iss)) lib$signal(iss);
539     iss = lib$subx(v,qq,v);
540     if (VMSERR(iss)) lib$signal(iss);
541     iss = lib$subx(v,qq,v);
542     if (VMSERR(iss)) lib$signal(iss);
543 }
544
545 static int
546 VMS_to_us(unsigned long v[])
547 {
548     int iss;
549     unsigned long div=10,quot, rem;
550
551     iss = lib$ediv(&div,v,&quot,&rem);
552     if (VMSERR(iss)) lib$signal(iss);
553
554     return quot;
555 }
556
557 typedef unsigned short word;
558 typedef struct _ualarm {
559     int function;
560     int repeat;
561     unsigned long delay[2];
562     unsigned long interval[2];
563     unsigned long remain[2];
564 } Alarm;
565
566
567 static int alarm_ef;
568 static Alarm *a0, alarm_base;
569 #define UAL_NULL   0
570 #define UAL_SET    1
571 #define UAL_CLEAR  2
572 #define UAL_ACTIVE 4
573 static void ualarm_AST(Alarm *a);
574
575 static int 
576 vms_ualarm(int mseconds, int interval)
577 {
578     Alarm *a, abase;
579     struct item_list3 {
580         word length;
581         word code;
582         void *bufaddr;
583         void *retlenaddr;
584     } ;
585     static struct item_list3 itmlst[2];
586     static int first = 1;
587     unsigned long asten;
588     int iss, enabled;
589
590     if (first) {
591         first = 0;
592         itmlst[0].code       = JPI$_ASTEN;
593         itmlst[0].length     = sizeof(asten);
594         itmlst[0].retlenaddr = NULL;
595         itmlst[1].code       = 0;
596         itmlst[1].length     = 0;
597         itmlst[1].bufaddr    = NULL;
598         itmlst[1].retlenaddr = NULL;
599
600         iss = lib$get_ef(&alarm_ef);
601         if (VMSERR(iss)) lib$signal(iss);
602
603         a0 = &alarm_base;
604         a0->function = UAL_NULL;
605     }
606     itmlst[0].bufaddr    = &asten;
607     
608     iss = sys$getjpiw(0,0,0,itmlst,0,0,0);
609     if (VMSERR(iss)) lib$signal(iss);
610     if (!(asten&0x08)) return -1;
611
612     a = &abase;
613     if (mseconds) {
614         a->function = UAL_SET;
615     } else {
616         a->function = UAL_CLEAR;
617     }
618
619     us_to_VMS(mseconds, a->delay);
620     if (interval) {
621         us_to_VMS(interval, a->interval);
622         a->repeat = 1;
623     } else 
624         a->repeat = 0;
625
626     iss = sys$clref(alarm_ef);
627     if (VMSERR(iss)) lib$signal(iss);
628
629     iss = sys$dclast(ualarm_AST,a,0);
630     if (VMSERR(iss)) lib$signal(iss);
631
632     iss = sys$waitfr(alarm_ef);
633     if (VMSERR(iss)) lib$signal(iss);
634
635     if (a->function == UAL_ACTIVE) 
636         return VMS_to_us(a->remain);
637     else
638         return 0;
639 }
640
641
642
643 static void
644 ualarm_AST(Alarm *a)
645 {
646     int iss;
647     unsigned long now[2];
648
649     iss = sys$gettim(now);
650     if (VMSERR(iss)) lib$signal(iss);
651
652     if (a->function == UAL_SET || a->function == UAL_CLEAR) {
653         if (a0->function == UAL_ACTIVE) {
654             iss = sys$cantim(a0,PSL$C_USER);
655             if (VMSERR(iss)) lib$signal(iss);
656
657             iss = lib$subx(a0->remain, now, a->remain);
658             if (VMSERR(iss)) lib$signal(iss);
659
660             if (a->remain[1] & 0x80000000) 
661                 a->remain[0] = a->remain[1] = 0;
662         }
663
664         if (a->function == UAL_SET) {
665             a->function = a0->function;
666             a0->function = UAL_ACTIVE;
667             a0->repeat = a->repeat;
668             if (a0->repeat) {
669                 a0->interval[0] = a->interval[0];
670                 a0->interval[1] = a->interval[1];
671             }
672             a0->delay[0] = a->delay[0];
673             a0->delay[1] = a->delay[1];
674
675             iss = lib$subx(now, a0->delay, a0->remain);
676             if (VMSERR(iss)) lib$signal(iss);
677
678             iss = sys$setimr(0,a0->delay,ualarm_AST,a0);
679             if (VMSERR(iss)) lib$signal(iss);
680         } else {
681             a->function = a0->function;
682             a0->function = UAL_NULL;
683         }
684         iss = sys$setef(alarm_ef);
685         if (VMSERR(iss)) lib$signal(iss);
686     } else if (a->function == UAL_ACTIVE) {
687         if (a->repeat) {
688             iss = lib$subx(now, a->interval, a->remain);
689             if (VMSERR(iss)) lib$signal(iss);
690
691             iss = sys$setimr(0,a->interval,ualarm_AST,a);
692             if (VMSERR(iss)) lib$signal(iss);
693         } else {
694             a->function = UAL_NULL;
695         }
696         iss = sys$wake(0,0);
697         if (VMSERR(iss)) lib$signal(iss);
698         lib$signal(SS$_ASTFLT);
699     } else {
700         lib$signal(SS$_BADPARAM);
701     }
702 }
703
704 #endif /* #if !defined(HAS_UALARM) && defined(VMS) */
705
706 #ifdef HAS_GETTIMEOFDAY
707
708 static int
709 myU2time(pTHX_ UV *ret)
710 {
711   struct timeval Tp;
712   int status;
713   status = gettimeofday (&Tp, NULL);
714   ret[0] = Tp.tv_sec;
715   ret[1] = Tp.tv_usec;
716   return status;
717 }
718
719 static NV
720 myNVtime()
721 {
722 #ifdef WIN32
723   dTHX;
724 #endif
725   struct timeval Tp;
726   int status;
727   status = gettimeofday (&Tp, NULL);
728   return status == 0 ? Tp.tv_sec + (Tp.tv_usec / NV_1E6) : -1.0;
729 }
730
731 #endif /* #ifdef HAS_GETTIMEOFDAY */
732
733 static void
734 hrstatns(UV atime, UV mtime, UV ctime, UV *atime_nsec, UV *mtime_nsec, UV *ctime_nsec)
735 {
736   dTHXR;
737   *atime_nsec = 0;
738   *mtime_nsec = 0;
739   *ctime_nsec = 0;
740 #ifdef TIME_HIRES_STAT
741 #if TIME_HIRES_STAT == 1
742   *atime_nsec = PL_statcache.st_atimespec.tv_nsec;
743   *mtime_nsec = PL_statcache.st_mtimespec.tv_nsec;
744   *ctime_nsec = PL_statcache.st_ctimespec.tv_nsec;
745 #endif
746 #if TIME_HIRES_STAT == 2
747   *atime_nsec = PL_statcache.st_atimensec;
748   *mtime_nsec = PL_statcache.st_mtimensec;
749   *ctime_nsec = PL_statcache.st_ctimensec;
750 #endif
751 #if TIME_HIRES_STAT == 3
752   *atime_nsec = PL_statcache.st_atime_n;
753   *mtime_nsec = PL_statcache.st_mtime_n;
754   *ctime_nsec = PL_statcache.st_ctime_n;
755 #endif
756 #if TIME_HIRES_STAT == 4
757   *atime_nsec = PL_statcache.st_atim.tv_nsec;
758   *mtime_nsec = PL_statcache.st_mtim.tv_nsec;
759   *ctime_nsec = PL_statcache.st_ctim.tv_nsec;
760 #endif
761 #if TIME_HIRES_STAT == 5
762   *atime_nsec = PL_statcache.st_uatime * 1000;
763   *mtime_nsec = PL_statcache.st_umtime * 1000;
764   *ctime_nsec = PL_statcache.st_uctime * 1000;
765 #endif
766 #endif
767 }
768
769 #include "const-c.inc"
770
771 MODULE = Time::HiRes            PACKAGE = Time::HiRes
772
773 PROTOTYPES: ENABLE
774
775 BOOT:
776 {
777 #ifdef MY_CXT_KEY
778   MY_CXT_INIT;
779 #endif
780 #ifdef ATLEASTFIVEOHOHFIVE
781 #   ifdef HAS_GETTIMEOFDAY
782   {
783     hv_store(PL_modglobal, "Time::NVtime", 12, newSViv(PTR2IV(myNVtime)), 0);
784     hv_store(PL_modglobal, "Time::U2time", 12, newSViv(PTR2IV(myU2time)), 0);
785   }
786 #   endif
787 #endif
788 }
789
790 #if defined(USE_ITHREADS) && defined(MY_CXT_KEY)
791
792 void
793 CLONE(...)
794     CODE:
795     MY_CXT_CLONE;
796
797 #endif
798
799 INCLUDE: const-xs.inc
800
801 #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY)
802
803 NV
804 usleep(useconds)
805         NV useconds
806         PREINIT:
807         struct timeval Ta, Tb;
808         CODE:
809         gettimeofday(&Ta, NULL);
810         if (items > 0) {
811             if (useconds > 1E6) {
812                 IV seconds = (IV) (useconds / 1E6);
813                 /* If usleep() has been implemented using setitimer()
814                  * then this contortion is unnecessary-- but usleep()
815                  * may be implemented in some other way, so let's contort. */
816                 if (seconds) {
817                     sleep(seconds);
818                     useconds -= 1E6 * seconds;
819                 }
820             } else if (useconds < 0.0)
821                 croak("Time::HiRes::usleep(%"NVgf"): negative time not invented yet", useconds);
822             usleep((U32)useconds);
823         } else
824             PerlProc_pause();
825         gettimeofday(&Tb, NULL);
826 #if 0
827         printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
828 #endif
829         RETVAL = 1E6*(Tb.tv_sec-Ta.tv_sec)+(NV)((IV)Tb.tv_usec-(IV)Ta.tv_usec);
830
831         OUTPUT:
832         RETVAL
833
834 #if defined(TIME_HIRES_NANOSLEEP)
835
836 NV
837 nanosleep(nsec)
838         NV nsec
839         PREINIT:
840         struct timespec sleepfor, unslept;
841         CODE:
842         if (nsec < 0.0)
843             croak("Time::HiRes::nanosleep(%"NVgf"): negative time not invented yet", nsec);
844         sleepfor.tv_sec = (Time_t)(nsec / 1e9);
845         sleepfor.tv_nsec = (long)(nsec - ((NV)sleepfor.tv_sec) * 1e9);
846         if (!nanosleep(&sleepfor, &unslept)) {
847             RETVAL = nsec;
848         } else {
849             sleepfor.tv_sec -= unslept.tv_sec;
850             sleepfor.tv_nsec -= unslept.tv_nsec;
851             if (sleepfor.tv_nsec < 0) {
852                 sleepfor.tv_sec--;
853                 sleepfor.tv_nsec += 1000000000;
854             }
855             RETVAL = ((NV)sleepfor.tv_sec) * 1e9 + ((NV)sleepfor.tv_nsec);
856         }
857     OUTPUT:
858         RETVAL
859
860 #else  /* #if defined(TIME_HIRES_NANOSLEEP) */
861
862 NV
863 nanosleep(nsec)
864         NV nsec
865     CODE:
866         croak("Time::HiRes::nanosleep(): unimplemented in this platform");
867         RETVAL = 0.0;
868
869 #endif /* #if defined(TIME_HIRES_NANOSLEEP) */
870
871 NV
872 sleep(...)
873         PREINIT:
874         struct timeval Ta, Tb;
875         CODE:
876         gettimeofday(&Ta, NULL);
877         if (items > 0) {
878             NV seconds  = SvNV(ST(0));
879             if (seconds >= 0.0) {
880                  UV useconds = (UV)(1E6 * (seconds - (UV)seconds));
881                  if (seconds >= 1.0)
882                      sleep((U32)seconds);
883                  if ((IV)useconds < 0) {
884 #if defined(__sparc64__) && defined(__GNUC__)
885                    /* Sparc64 gcc 2.95.3 (e.g. on NetBSD) has a bug
886                     * where (0.5 - (UV)(0.5)) will under certain
887                     * circumstances (if the double is cast to UV more
888                     * than once?) evaluate to -0.5, instead of 0.5. */
889                    useconds = -(IV)useconds;
890 #endif /* #if defined(__sparc64__) && defined(__GNUC__) */
891                    if ((IV)useconds < 0)
892                      croak("Time::HiRes::sleep(%"NVgf"): internal error: useconds < 0 (unsigned %"UVuf" signed %"IVdf")", seconds, useconds, (IV)useconds);
893                  }
894                  usleep(useconds);
895             } else
896                 croak("Time::HiRes::sleep(%"NVgf"): negative time not invented yet", seconds);
897         } else
898             PerlProc_pause();
899         gettimeofday(&Tb, NULL);
900 #if 0
901         printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
902 #endif
903         RETVAL = (NV)(Tb.tv_sec-Ta.tv_sec)+0.000001*(NV)(Tb.tv_usec-Ta.tv_usec);
904
905         OUTPUT:
906         RETVAL
907
908 #else  /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
909
910 NV
911 usleep(useconds)
912         NV useconds
913     CODE:
914         croak("Time::HiRes::usleep(): unimplemented in this platform");
915         RETVAL = 0.0;
916
917 #endif /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
918
919 #ifdef HAS_UALARM
920
921 IV
922 ualarm(useconds,uinterval=0)
923         int useconds
924         int uinterval
925         CODE:
926         if (useconds < 0 || uinterval < 0)
927             croak("Time::HiRes::ualarm(%d, %d): negative time not invented yet", useconds, uinterval);
928         if (useconds >= IV_1E6 || uinterval >= IV_1E6) 
929 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
930           {
931                 struct itimerval itv;
932                 if (hrt_ualarm_itimero(&itv, useconds, uinterval)) {
933                   RETVAL = itv.it_value.tv_sec + IV_1E6 * itv.it_value.tv_usec;
934                 } else {
935                   RETVAL = 0;
936                 }
937           }
938 #else
939                 croak("Time::HiRes::ualarm(%d, %d): useconds or uinterval equal to or more than %"IVdf, useconds, uinterval, IV_1E6);
940 #endif
941         else
942                 RETVAL = ualarm(useconds, uinterval);
943
944         OUTPUT:
945         RETVAL
946
947 NV
948 alarm(seconds,interval=0)
949         NV seconds
950         NV interval
951         CODE:
952         if (seconds < 0.0 || interval < 0.0)
953             croak("Time::HiRes::alarm(%"NVgf", %"NVgf"): negative time not invented yet", seconds, interval);
954         {
955           IV useconds     = IV_1E6 * seconds;
956           IV uinterval    = IV_1E6 * interval;
957           if (seconds >= IV_1E6 || interval >= IV_1E6)
958 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
959           {
960                 struct itimerval itv;
961                 if (hrt_ualarm_itimero(&itv, useconds, uinterval)) {
962                   RETVAL = (NV)itv.it_value.tv_sec + (NV)itv.it_value.tv_usec / NV_1E6;
963                 } else {
964                   RETVAL = 0;
965                 }
966           }
967 #else
968             RETVAL = (NV)ualarm((IV)(seconds  * IV_1E6),
969                                 (IV)(interval * IV_1E6)) / NV_1E6;
970 #endif
971         }
972
973         OUTPUT:
974         RETVAL
975
976 #else
977
978 int
979 ualarm(useconds,interval=0)
980         int useconds
981         int interval
982     CODE:
983         croak("Time::HiRes::ualarm(): unimplemented in this platform");
984         RETVAL = -1;
985
986 NV
987 alarm(seconds,interval=0)
988         NV seconds
989         NV interval
990     CODE:
991         croak("Time::HiRes::alarm(): unimplemented in this platform");
992         RETVAL = 0.0;
993
994 #endif /* #ifdef HAS_UALARM */
995
996 #ifdef HAS_GETTIMEOFDAY
997 #    ifdef MACOS_TRADITIONAL    /* fix epoch TZ and use unsigned time_t */
998 void
999 gettimeofday()
1000         PREINIT:
1001         struct timeval Tp;
1002         struct timezone Tz;
1003         PPCODE:
1004         int status;
1005         status = gettimeofday (&Tp, &Tz);
1006
1007         if (status == 0) {
1008              Tp.tv_sec += Tz.tz_minuteswest * 60;       /* adjust for TZ */
1009              if (GIMME == G_ARRAY) {
1010                  EXTEND(sp, 2);
1011                  /* Mac OS (Classic) has unsigned time_t */
1012                  PUSHs(sv_2mortal(newSVuv(Tp.tv_sec)));
1013                  PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1014              } else {
1015                  EXTEND(sp, 1);
1016                  PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1017              }
1018         }
1019
1020 NV
1021 time()
1022         PREINIT:
1023         struct timeval Tp;
1024         struct timezone Tz;
1025         CODE:
1026         int status;
1027         status = gettimeofday (&Tp, &Tz);
1028         if (status == 0) {
1029             Tp.tv_sec += Tz.tz_minuteswest * 60;        /* adjust for TZ */
1030             RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1031         } else {
1032             RETVAL = -1.0;
1033         }
1034         OUTPUT:
1035         RETVAL
1036
1037 #    else       /* MACOS_TRADITIONAL */
1038 void
1039 gettimeofday()
1040         PREINIT:
1041         struct timeval Tp;
1042         PPCODE:
1043         int status;
1044         status = gettimeofday (&Tp, NULL);
1045         if (status == 0) {
1046              if (GIMME == G_ARRAY) {
1047                  EXTEND(sp, 2);
1048                  PUSHs(sv_2mortal(newSViv(Tp.tv_sec)));
1049                  PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1050              } else {
1051                  EXTEND(sp, 1);
1052                  PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1053              }
1054         }
1055
1056 NV
1057 time()
1058         PREINIT:
1059         struct timeval Tp;
1060         CODE:
1061         int status;
1062         status = gettimeofday (&Tp, NULL);
1063         if (status == 0) {
1064             RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1065         } else {
1066             RETVAL = -1.0;
1067         }
1068         OUTPUT:
1069         RETVAL
1070
1071 #    endif      /* MACOS_TRADITIONAL */
1072 #endif /* #ifdef HAS_GETTIMEOFDAY */
1073
1074 #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER)
1075
1076 #define TV2NV(tv) ((NV)((tv).tv_sec) + 0.000001 * (NV)((tv).tv_usec))
1077
1078 void
1079 setitimer(which, seconds, interval = 0)
1080         int which
1081         NV seconds
1082         NV interval
1083     PREINIT:
1084         struct itimerval newit;
1085         struct itimerval oldit;
1086     PPCODE:
1087         if (seconds < 0.0 || interval < 0.0)
1088             croak("Time::HiRes::setitimer(%"IVdf", %"NVgf", %"NVgf"): negative time not invented yet", (IV)which, seconds, interval);
1089         newit.it_value.tv_sec  = (IV)seconds;
1090         newit.it_value.tv_usec =
1091           (IV)((seconds  - (NV)newit.it_value.tv_sec)    * NV_1E6);
1092         newit.it_interval.tv_sec  = (IV)interval;
1093         newit.it_interval.tv_usec =
1094           (IV)((interval - (NV)newit.it_interval.tv_sec) * NV_1E6);
1095         if (setitimer(which, &newit, &oldit) == 0) {
1096           EXTEND(sp, 1);
1097           PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_value))));
1098           if (GIMME == G_ARRAY) {
1099             EXTEND(sp, 1);
1100             PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_interval))));
1101           }
1102         }
1103
1104 void
1105 getitimer(which)
1106         int which
1107     PREINIT:
1108         struct itimerval nowit;
1109     PPCODE:
1110         if (getitimer(which, &nowit) == 0) {
1111           EXTEND(sp, 1);
1112           PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_value))));
1113           if (GIMME == G_ARRAY) {
1114             EXTEND(sp, 1);
1115             PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_interval))));
1116           }
1117         }
1118
1119 #endif /* #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER) */
1120
1121 #if defined(TIME_HIRES_CLOCK_GETTIME)
1122
1123 NV
1124 clock_gettime(clock_id = CLOCK_REALTIME)
1125         int clock_id
1126     PREINIT:
1127         struct timespec ts;
1128         int status = -1;
1129     CODE:
1130 #ifdef TIME_HIRES_CLOCK_GETTIME_SYSCALL
1131         status = syscall(SYS_clock_gettime, clock_id, &ts);
1132 #else
1133         status = clock_gettime(clock_id, &ts);
1134 #endif
1135         RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / (NV) 1e9 : -1;
1136
1137     OUTPUT:
1138         RETVAL
1139
1140 #else  /* if defined(TIME_HIRES_CLOCK_GETTIME) */
1141
1142 NV
1143 clock_gettime(clock_id = 0)
1144         int clock_id
1145     CODE:
1146         croak("Time::HiRes::clock_gettime(): unimplemented in this platform");
1147         RETVAL = 0.0;
1148
1149 #endif /*  #if defined(TIME_HIRES_CLOCK_GETTIME) */
1150
1151 #if defined(TIME_HIRES_CLOCK_GETRES)
1152
1153 NV
1154 clock_getres(clock_id = CLOCK_REALTIME)
1155         int clock_id
1156     PREINIT:
1157         int status = -1;
1158         struct timespec ts;
1159     CODE:
1160 #ifdef TIME_HIRES_CLOCK_GETRES_SYSCALL
1161         status = syscall(SYS_clock_getres, clock_id, &ts);
1162 #else
1163         status = clock_getres(clock_id, &ts);
1164 #endif
1165         RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / (NV) 1e9 : -1;
1166
1167     OUTPUT:
1168         RETVAL
1169
1170 #else  /* if defined(TIME_HIRES_CLOCK_GETRES) */
1171
1172 NV
1173 clock_getres(clock_id = 0)
1174         int clock_id
1175     CODE:
1176         croak("Time::HiRes::clock_getres(): unimplemented in this platform");
1177         RETVAL = 0.0;
1178
1179 #endif /*  #if defined(TIME_HIRES_CLOCK_GETRES) */
1180
1181 #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME)
1182
1183 NV
1184 clock_nanosleep(clock_id, nsec, flags = 0)
1185         int clock_id
1186         NV  nsec
1187         int flags
1188     PREINIT:
1189         struct timespec sleepfor, unslept;
1190     CODE:
1191         if (nsec < 0.0)
1192             croak("Time::HiRes::clock_nanosleep(..., %"NVgf"): negative time not invented yet", nsec);
1193         sleepfor.tv_sec = (Time_t)(nsec / 1e9);
1194         sleepfor.tv_nsec = (long)(nsec - ((NV)sleepfor.tv_sec) * 1e9);
1195         if (!clock_nanosleep(clock_id, flags, &sleepfor, &unslept)) {
1196             RETVAL = nsec;
1197         } else {
1198             sleepfor.tv_sec -= unslept.tv_sec;
1199             sleepfor.tv_nsec -= unslept.tv_nsec;
1200             if (sleepfor.tv_nsec < 0) {
1201                 sleepfor.tv_sec--;
1202                 sleepfor.tv_nsec += 1000000000;
1203             }
1204             RETVAL = ((NV)sleepfor.tv_sec) * 1e9 + ((NV)sleepfor.tv_nsec);
1205         }
1206     OUTPUT:
1207         RETVAL
1208
1209 #else  /* if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1210
1211 NV
1212 clock_nanosleep()
1213     CODE:
1214         croak("Time::HiRes::clock_nanosleep(): unimplemented in this platform");
1215         RETVAL = 0.0;
1216
1217 #endif /*  #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1218
1219 #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC)
1220
1221 NV
1222 clock()
1223     PREINIT:
1224         clock_t clocks;
1225     CODE:
1226         clocks = clock();
1227         RETVAL = clocks == -1 ? -1 : (NV)clocks / (NV)CLOCKS_PER_SEC;
1228
1229     OUTPUT:
1230         RETVAL
1231
1232 #else  /* if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1233
1234 NV
1235 clock()
1236     CODE:
1237         croak("Time::HiRes::clock(): unimplemented in this platform");
1238         RETVAL = 0.0;
1239
1240 #endif /*  #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1241
1242 void
1243 stat(...)
1244 PROTOTYPE: ;$
1245     PPCODE:
1246         PUSHMARK(SP);
1247         XPUSHs(sv_2mortal(newSVsv(items == 1 ? ST(0) : DEFSV)));
1248         PUTBACK;
1249         ENTER;
1250         PL_laststatval = -1;
1251         (void)*(PL_ppaddr[OP_STAT])(aTHXR);
1252         SPAGAIN;
1253         LEAVE;
1254         if (PL_laststatval == 0) {
1255           /* We assume that pp_stat() left us with 13 valid stack items,
1256            * and that the timestamps are at offsets 8, 9, and 10. */
1257           UV atime = SvUV(ST( 8));
1258           UV mtime = SvUV(ST( 9));
1259           UV ctime = SvUV(ST(10));
1260           UV atime_nsec;
1261           UV mtime_nsec;
1262           UV ctime_nsec;
1263           hrstatns(atime, mtime, ctime,
1264                    &atime_nsec, &mtime_nsec, &ctime_nsec);
1265           if (atime_nsec)
1266             ST( 8) = sv_2mortal(newSVnv(atime + 1e-9 * (NV) atime_nsec));
1267           if (mtime_nsec)
1268             ST( 9) = sv_2mortal(newSVnv(mtime + 1e-9 * (NV) mtime_nsec));
1269           if (ctime_nsec)
1270             ST(10) = sv_2mortal(newSVnv(ctime + 1e-9 * (NV) ctime_nsec));
1271           XSRETURN(13);
1272         }
1273         XSRETURN(0);