xref: /plan9/sys/src/ape/lib/bsd/gettimeofday.c (revision b39189fd423aed869c5cf5189bc504918cff969b)
1 #include <sys/types.h>
2 #include <time.h>
3 #include <sys/time.h>
4 #include <string.h>
5 #include "sys9.h"
6 
7 typedef unsigned long long uvlong;
8 typedef long long vlong;
9 typedef unsigned char uchar;
10 
11 static uvlong order = 0x0001020304050607ULL;
12 
13 static void
be2vlong(vlong * to,uchar * f)14 be2vlong(vlong *to, uchar *f)
15 {
16 	uchar *t, *o;
17 	int i;
18 
19 	t = (uchar*)to;
20 	o = (uchar*)&order;
21 	for(i = 0; i < 8; i++)
22 		t[o[i]] = f[i];
23 }
24 
25 int
gettimeofday(struct timeval * tp,struct timezone * tzp)26 gettimeofday(struct timeval *tp, struct timezone *tzp)
27 {
28 	uchar b[8];
29 	vlong t;
30 	int opened;
31 	static int fd = -1;
32 
33 	opened = 0;
34 	for(;;) {
35 		if(fd < 0)
36 			if(opened++ ||
37 			    (fd = _OPEN("/dev/bintime", OREAD|OCEXEC)) < 0)
38 				return 0;
39 		if(_PREAD(fd, b, sizeof b, 0) == sizeof b)
40 			break;		/* leave fd open for future use */
41 		/* short read, perhaps try again */
42 		_CLOSE(fd);
43 		fd = -1;
44 	}
45 	be2vlong(&t, b);
46 
47 	tp->tv_sec = t/1000000000;
48 	tp->tv_usec = (t/1000)%1000000;
49 
50 	if(tzp) {
51 		tzp->tz_minuteswest = 4*60;	/* BUG */
52 		tzp->tz_dsttime = 1;
53 	}
54 
55 	return 0;
56 }
57