1 /* 2 * This file and its contents are supplied under the terms of the 3 * Common Development and Distribution License ("CDDL"), version 1.0. 4 * You may only use this file in accordance with the terms of version 5 * 1.0 of the CDDL. 6 * 7 * A full copy of the text of the CDDL should have accompanied this 8 * source. A copy of the CDDL is also available via the Internet at 9 * http://www.illumos.org/license/CDDL. 10 */ 11 12 /* 13 * Copyright (c) 2015 Joyent, Inc. 14 * Copyright 2025 Oxide Computer Company 15 */ 16 17 /* 18 * Implementation of C11 and C23 timespec_*() functions. Note, the standard does 19 * not have us return values of errno if there are failures for whatever reason, 20 * only zero. At least we don't have to preserve errno though. 21 */ 22 23 #include <time.h> 24 #include <stdbool.h> 25 26 static bool 27 timespec_base_to_clock(int base, clockid_t *clock) 28 { 29 switch (base) { 30 case TIME_UTC: 31 *clock = CLOCK_REALTIME; 32 break; 33 case TIME_MONOTONIC: 34 *clock = CLOCK_HIGHRES; 35 break; 36 case TIME_ACTIVE: 37 *clock = CLOCK_PROCESS_CPUTIME_ID; 38 break; 39 case TIME_THREAD_ACTIVE: 40 *clock = CLOCK_THREAD_CPUTIME_ID; 41 break; 42 case TIME_THREAD_ACTIVE_USR: 43 *clock = CLOCK_VIRTUAL; 44 break; 45 default: 46 return (false); 47 } 48 49 return (true); 50 } 51 52 int 53 timespec_get(struct timespec *ts, int base) 54 { 55 clockid_t clock; 56 57 if (!timespec_base_to_clock(base, &clock)) 58 return (0); 59 60 if (clock_gettime(clock, ts) != 0) 61 return (0); 62 63 return (base); 64 } 65 66 int 67 timespec_getres(struct timespec *ts, int base) 68 { 69 clockid_t clock; 70 71 if (!timespec_base_to_clock(base, &clock)) 72 return (0); 73 74 if (clock_getres(clock, ts) != 0) 75 return (0); 76 77 return (base); 78 } 79