-
Notifications
You must be signed in to change notification settings - Fork 7
/
time.go
75 lines (63 loc) · 1.68 KB
/
time.go
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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package conntrack
import (
"fmt"
"github.com/cilium/cilium/pkg/datapath/linux/probes"
"golang.org/x/sys/unix"
)
var hertz uint16
func init() {
var err error
hertz, err = getKernelHZ()
if err != nil {
hertz = 1
}
}
type ClockSource string
const (
ClockSourceKtime ClockSource = "ktime"
ClockSourceJiffies ClockSource = "jiffies"
)
// Make linter happy. It's used for linux build target.
var _ = kernelTimeDiffSecondsFunc
// kernelTimeDiffSecondsFunc returns time diff function based on clock source.
func kernelTimeDiffSecondsFunc(clockSource ClockSource) (func(t int64) int64, error) {
switch clockSource {
case ClockSourceKtime:
now, err := getMtime()
if err != nil {
return nil, err
}
now = now / 1000000000
return func(t int64) int64 {
return t - int64(now)
}, nil
case ClockSourceJiffies:
now, err := probes.Jiffies()
if err != nil {
return nil, err
}
return func(t int64) int64 {
diff := t - int64(now)
diff = diff << 8
diff = diff / int64(hertz)
return diff
}, nil
default:
return nil, fmt.Errorf("unknown clock source %q", clockSource)
}
}
// getMtime returns monotonic time that can be used to compare
// values with ktime_get_ns() BPF helper, e.g. needed to check
// the timeout in sec for BPF entries. We return the raw nsec,
// although that is not quite usable for comparison. Go has
// runtime.nanotime() but doesn't expose it as API.
func getMtime() (uint64, error) {
var ts unix.Timespec
err := unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts)
if err != nil {
return 0, fmt.Errorf("Unable get time: %w", err)
}
return uint64(unix.TimespecToNsec(ts)), nil
}