From 7167c39d24f54b3361eb70b7863292f234699ee3 Mon Sep 17 00:00:00 2001 From: Victoria Fischer Date: Mon, 12 Dec 2022 12:43:02 +0100 Subject: [PATCH] dlt-system: Avoid expensive getpid() syscalls Since glibc 2.25, getpid() no longer caches the PID, instead performing a full syscall every time. This means we're performing a full syscall roundtrip for *every* *single* *log* *message* on the system. This patch caches the result of getpid() when appropriate, avoiding unnessicary syscalls. Signed-off-by: Aleix Pol Gonzalez --- include/dlt/dlt_user.h.in | 4 ++++ src/lib/dlt_user.c | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/include/dlt/dlt_user.h.in b/include/dlt/dlt_user.h.in index 42254acec..8762cf5bd 100644 --- a/include/dlt/dlt_user.h.in +++ b/include/dlt/dlt_user.h.in @@ -271,6 +271,10 @@ typedef struct #ifdef DLT_TRACE_LOAD_CTRL_ENABLE pthread_rwlock_t trace_load_limit_lock; #endif + // Since glibc 2.25, getpid() no longer caches the PID, instead performing a + // full syscall every time. This means we're performing a full syscall + // roundtrip for *every* *single* *log* *message* on the system. + pid_t local_pid; } DltUser; typedef int (*dlt_injection_callback_id)(uint32_t, void *, uint32_t, void *); diff --git a/src/lib/dlt_user.c b/src/lib/dlt_user.c index 4dfe0bd16..c6e84f7d6 100644 --- a/src/lib/dlt_user.c +++ b/src/lib/dlt_user.c @@ -771,6 +771,9 @@ DltReturnValue dlt_init_common(void) /* set to unknown state of connected client */ dlt_user.log_state = -1; + /* set pid cache to none until we need it */ + dlt_user.local_pid = -1; + dlt_user.dlt_log_handle = -1; dlt_user.dlt_user_handle = DLT_FD_INIT; @@ -4011,7 +4014,11 @@ DltReturnValue dlt_user_log_send_log(DltContextData *log, const int mtype, int * /* send session id */ if (dlt_user.with_session_id) { msg.standardheader->htyp |= DLT_HTYP_WSID; - msg.headerextra.seid = (uint32_t) getpid(); + // 99.99999% of the time, we'll already have a PID set. + if (__builtin_expect(!!(dlt_user.local_pid == -1), false)) { + dlt_user.local_pid = getpid(); + } + msg.headerextra.seid = (uint32_t) dlt_user.local_pid; } if (is_verbose_mode(dlt_user.verbose_mode, log)) @@ -5377,6 +5384,7 @@ static void dlt_fork_child_fork_handler() g_dlt_is_child = 1; dlt_user_init_state = INIT_UNITIALIZED; dlt_user.dlt_log_handle = -1; + dlt_user.local_pid = -1; #ifdef DLT_TRACE_LOAD_CTRL_ENABLE pthread_rwlock_unlock(&trace_load_rw_lock); #endif