1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright(c) 2015 Intel Corporation
15 #define NSEC_PER_SEC 1000000000L
18 * Structure to hold the parameters of a running cycle counter to assist
19 * in converting cycles to nanoseconds.
21 struct rte_timecounter {
22 /** Last cycle counter value read. */
24 /** Nanoseconds count. */
26 /** Bitmask separating nanosecond and sub-nanoseconds. */
28 /** Sub-nanoseconds count. */
30 /** Bitmask for two's complement subtraction of non-64 bit counters. */
32 /** Cycle to nanosecond divisor (power of two). */
37 * Converts cyclecounter cycles to nanoseconds.
39 static inline uint64_t
40 rte_cyclecounter_cycles_to_ns(struct rte_timecounter *tc, uint64_t cycles)
44 /* Add fractional nanoseconds. */
45 ns = cycles + tc->nsec_frac;
46 tc->nsec_frac = ns & tc->nsec_mask;
48 /* Shift to get only nanoseconds. */
49 return ns >> tc->cc_shift;
53 * Update the internal nanosecond count in the structure.
55 static inline uint64_t
56 rte_timecounter_update(struct rte_timecounter *tc, uint64_t cycle_now)
58 uint64_t cycle_delta, ns_offset;
60 /* Calculate the delta since the last call. */
61 if (tc->cycle_last <= cycle_now)
62 cycle_delta = (cycle_now - tc->cycle_last) & tc->cc_mask;
64 /* Handle cycle counts that have wrapped around . */
65 cycle_delta = (~(tc->cycle_last - cycle_now) & tc->cc_mask) + 1;
67 /* Convert to nanoseconds. */
68 ns_offset = rte_cyclecounter_cycles_to_ns(tc, cycle_delta);
70 /* Store current cycle counter for next call. */
71 tc->cycle_last = cycle_now;
73 /* Update the nanosecond count. */
74 tc->nsec += ns_offset;
80 * Convert from timespec structure into nanosecond units.
82 static inline uint64_t
83 rte_timespec_to_ns(const struct timespec *ts)
85 return ((uint64_t) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
89 * Convert from nanosecond units into timespec structure.
91 static inline struct timespec
92 rte_ns_to_timespec(uint64_t nsec)
94 struct timespec ts = {0, 0};
99 ts.tv_sec = nsec / NSEC_PER_SEC;
100 ts.tv_nsec = nsec % NSEC_PER_SEC;
109 #endif /* _RTE_TIME_H_ */