Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDP/BPF: Is there an user-space alternative to `bpf_ktime_get_ns`?

Tags:

c

linux

xdp-bpf

I want to insert a timestamp into the packets I receive in my XDP program. The only way I know how to get a timestamp is by calling bpf_ktime_get_ns.

But what would be the user-space equivalent function which creates comparable timestamps? As far as I know, ktime_get_ns returns the time since system start (in nanoseconds). There is

$ uptime
 11:45:35 up 2 days,  3:15,  3 users,  load average: 0.19, 0.29, 0.27

but this only returns the time since system start in seconds. So no precise measurement possible here (microsecond-level would be nice).

Edit: It was purely my fault. @Qeole and @tuilagio are completely right. I made a mistake in pointer arithmetic in my user space code where I was obtaining the pointer of the timestamp.

like image 479
binaryBigInt Avatar asked Dec 09 '25 21:12

binaryBigInt


1 Answers

You can use clock_gettime() :

static unsigned long get_nsecs(void)
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000000000UL + ts.tv_nsec;
}

and call it with unsigned long now = get_nsecs(); or uint64_t now = get_nsecs();

This return timestamp in nsec resolution.

Source: https://github.com/torvalds/linux/blob/master/samples/bpf/xdpsock_user.c#L114

like image 142
Que0Le Avatar answered Dec 12 '25 12:12

Que0Le