1 /* $OpenBSD: ktime.h,v 1.5 2020/07/29 09:52:21 jsg Exp $ */ 2 /* 3 * Copyright (c) 2013, 2014, 2015 Mark Kettenis 4 * 5 * Permission to use, copy, modify, and distribute this software for any 6 * purpose with or without fee is hereby granted, provided that the above 7 * copyright notice and this permission notice appear in all copies. 8 * 9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 */ 17 18 #ifndef _LINUX_KTIME_H 19 #define _LINUX_KTIME_H 20 21 #include <sys/time.h> 22 #include <linux/time.h> 23 #include <linux/jiffies.h> 24 25 typedef int64_t ktime_t; 26 27 static inline ktime_t 28 ktime_get(void) 29 { 30 struct timespec ts; 31 nanouptime(&ts); 32 return TIMESPEC_TO_NSEC(&ts); 33 } 34 35 static inline ktime_t 36 ktime_get_raw(void) 37 { 38 struct timespec ts; 39 nanouptime(&ts); 40 return TIMESPEC_TO_NSEC(&ts); 41 } 42 43 static inline int64_t 44 ktime_to_ms(ktime_t k) 45 { 46 return k / NSEC_PER_MSEC; 47 } 48 49 static inline int64_t 50 ktime_to_us(ktime_t k) 51 { 52 return k / NSEC_PER_USEC; 53 } 54 55 static inline int64_t 56 ktime_to_ns(ktime_t k) 57 { 58 return k; 59 } 60 61 static inline int64_t 62 ktime_get_raw_ns(void) 63 { 64 return ktime_to_ns(ktime_get_raw()); 65 } 66 67 static inline struct timespec64 68 ktime_to_timespec64(ktime_t k) 69 { 70 struct timespec64 ts; 71 ts.tv_sec = k / NSEC_PER_SEC; 72 ts.tv_nsec = k % NSEC_PER_SEC; 73 if (ts.tv_nsec < 0) { 74 ts.tv_sec--; 75 ts.tv_nsec += NSEC_PER_SEC; 76 } 77 return ts; 78 } 79 80 static inline ktime_t 81 ktime_sub(ktime_t a, ktime_t b) 82 { 83 return a - b; 84 } 85 86 static inline ktime_t 87 ktime_add(ktime_t a, ktime_t b) 88 { 89 return a + b; 90 } 91 92 static inline ktime_t 93 ktime_add_us(ktime_t k, uint64_t us) 94 { 95 return k + (us * NSEC_PER_USEC); 96 } 97 98 static inline ktime_t 99 ktime_add_ns(ktime_t k, int64_t ns) 100 { 101 return k + ns; 102 } 103 104 static inline ktime_t 105 ktime_sub_ns(ktime_t k, int64_t ns) 106 { 107 return k - ns; 108 } 109 110 static inline int64_t 111 ktime_us_delta(ktime_t a, ktime_t b) 112 { 113 return ktime_to_us(ktime_sub(a, b)); 114 } 115 116 static inline int64_t 117 ktime_ms_delta(ktime_t a, ktime_t b) 118 { 119 return ktime_to_ms(ktime_sub(a, b)); 120 } 121 122 static inline bool 123 ktime_after(ktime_t a, ktime_t b) 124 { 125 return a > b; 126 } 127 128 static inline ktime_t 129 ns_to_ktime(uint64_t ns) 130 { 131 return ns; 132 } 133 134 #include <linux/timekeeping.h> 135 136 #endif 137