summaryrefslogtreecommitdiff
path: root/src/kernel/arch/amd64/driver/time.c
blob: 8ae6fb2fda3c1885c4ac057a72a7d20a7411f5fd (plain)
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
/* This is already sort of deprecated as I introduce it --
 * it doesn't seem to provide much benefit over _sys_time, which I think I
 * have to keep anyways, so processes in an empty namespace can still keep
 * time. */
#include <camellia/errno.h>
#include <camellia/fsutil.h>
#include <kernel/arch/amd64/driver/driver.h>
#include <kernel/arch/amd64/driver/util.h>
#include <kernel/malloc.h>
#include <kernel/panic.h>
#include <kernel/proc.h>
#include <kernel/util.h>
#include <kernel/vfs/mount.h>
#include <kernel/vfs/request.h>
#include <shared/mem.h>

typedef struct {
	uint64_t base;
} TimeObj;

static long
handle(VfsReq *req)
{
	TimeObj *h;
	if (req->type == VFSOP_OPEN) {
		if (reqpathcmp(req, "")) {
			h = kmalloc(sizeof *h, "dev/time");
			h->base = uptime_ns();
			return (uintptr_t)h;
		} else {
			return -ENOENT;
		}
	}
	h = (__force void*)req->id;

	if (req->type == VFSOP_CLOSE) {
		assert(h);
		kfree(h);
		return 0;
	}

	uint64_t now = uptime_ns();

	union {
		char buf[8];
		uint64_t t;
	} u;
	switch (req->type) {
	case VFSOP_READ:
		u.t = now - h->base;
		return req_readcopy(req, u.buf, sizeof u.buf);
	case VFSOP_GETSIZE:
		return 8;
	case VFSOP_WRITE:
		if (req->input.len == 8) {
			assert(!req->input.kern);
			if (pcpy_from(req->caller, u.buf, req->input.buf, sizeof u.buf) != sizeof(u.buf)) {
				return -EGENERIC;
			}
			h->base = now - u.t;
			assert(u.t == now - h->base);
			return 8;
		}
		return -EGENERIC;
	default:
		return -ENOSYS;
	}
}

static void
accept(VfsReq *req)
{
	vfsreq_finish_short(req, handle(req));
}

void
time_init(void)
{
	vfs_root_register("/dev/bintime", accept);
}