From b03d55c2b841731c8194cb12566cad1d6d2ad3cb Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Fri, 4 Oct 2024 18:00:21 +0200
Subject: [PATCH] Avoid mutex locking in krb5int_trace()

Trace logging doesn't need unique timestamps, so the locking within
krb5_crypto_us_timeofday() makes trace logging slower for no reason.
Add a new helper k5_us_timeofday(), which is merely a wrapper around
the existing get_time_now(), and use it in krb5int_trace().

[ghudson@mit.edu: edited commit message]
---
 src/include/k5-int.h       |  1 +
 src/lib/krb5/os/c_ustime.c | 15 +++++++++++++++
 src/lib/krb5/os/trace.c    |  2 +-
 3 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/src/include/k5-int.h b/src/include/k5-int.h
index fd79d7c..f492acb 100644
--- a/src/include/k5-int.h
+++ b/src/include/k5-int.h
@@ -697,6 +697,7 @@ krb5_error_code krb5int_c_copy_keyblock_contents(krb5_context context,
                                                  const krb5_keyblock *from,
                                                  krb5_keyblock *to);
 
+krb5_error_code k5_us_timeofday(krb5_timestamp *, krb5_int32 *);
 krb5_error_code krb5_crypto_us_timeofday(krb5_timestamp *, krb5_int32 *);
 
 /*
diff --git a/src/lib/krb5/os/c_ustime.c b/src/lib/krb5/os/c_ustime.c
index f69f2ea..265c3b3 100644
--- a/src/lib/krb5/os/c_ustime.c
+++ b/src/lib/krb5/os/c_ustime.c
@@ -73,6 +73,21 @@ get_time_now(struct time_now *n)
 
 #endif
 
+krb5_error_code
+k5_us_timeofday(krb5_timestamp *seconds, krb5_int32 *microseconds)
+{
+    struct time_now now;
+    krb5_error_code err;
+
+    err = get_time_now(&now);
+    if (err)
+        return err;
+
+    *seconds = now.sec;
+    *microseconds = now.usec;
+    return 0;
+}
+
 static struct time_now last_time;
 
 krb5_error_code
diff --git a/src/lib/krb5/os/trace.c b/src/lib/krb5/os/trace.c
index c4058dd..2af459d 100644
--- a/src/lib/krb5/os/trace.c
+++ b/src/lib/krb5/os/trace.c
@@ -411,7 +411,7 @@ krb5int_trace(krb5_context context, const char *fmt, ...)
     str = trace_format(context, fmt, ap);
     if (str == NULL)
         goto cleanup;
-    if (krb5_crypto_us_timeofday(&sec, &usec) != 0)
+    if (k5_us_timeofday(&sec, &usec) != 0)
         goto cleanup;
     if (asprintf(&msg, "[%d] %u.%06d: %s\n", (int)getpid(),
                  (unsigned int)sec, (int)usec, str) < 0)
-- 
2.43.0

