2 * SPDX-License-Identifier: LGPL-2.1-only
4 * Copyright (C) 2009-2012 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 * Copyright (C) 2019 Michael Jeanson <mjeanson@efficios.com>
7 * LTTng UST pid namespace context.
13 #include <sys/types.h>
16 #include <lttng/ust-events.h>
17 #include <lttng/ust-tracer.h>
18 #include <lttng/ust-ringbuffer-context.h>
20 #include "context-internal.h"
21 #include "common/ns.h"
24 * We cache the result to ensure we don't stat(2) the proc filesystem on
25 * each event. The PID namespace is global to the process.
27 static ino_t cached_pid_ns
= NS_INO_UNINITIALIZED
;
30 ino_t
get_pid_ns(void)
35 pid_ns
= CMM_LOAD_SHARED(cached_pid_ns
);
38 * If the cache is populated, do nothing and return the
39 * cached inode number.
41 if (caa_likely(pid_ns
!= NS_INO_UNINITIALIZED
))
45 * At this point we have to populate the cache, set the initial
46 * value to NS_INO_UNAVAILABLE (0), if we fail to get the inode
47 * number from the proc filesystem, this is the value we will
50 pid_ns
= NS_INO_UNAVAILABLE
;
52 if (stat("/proc/self/ns/pid", &sb
) == 0) {
57 * And finally, store the inode number in the cache.
59 CMM_STORE_SHARED(cached_pid_ns
, pid_ns
);
65 * A process's PID namespace membership is determined when the process is
66 * created and cannot be changed thereafter.
68 * The pid namespace can change only on clone(2) / fork(2) :
69 * - clone(2) with the CLONE_NEWPID flag
70 * - clone(2) / fork(2) after a call to unshare(2) with the CLONE_NEWPID flag
71 * - clone(2) / fork(2) after a call to setns(2) with a PID namespace fd
73 void lttng_context_pid_ns_reset(void)
75 CMM_STORE_SHARED(cached_pid_ns
, NS_INO_UNINITIALIZED
);
79 size_t pid_ns_get_size(void *priv
__attribute__((unused
)),
80 struct lttng_ust_probe_ctx
*probe_ctx
__attribute__((unused
)),
85 size
+= lttng_ust_ring_buffer_align(offset
, lttng_ust_rb_alignof(ino_t
));
86 size
+= sizeof(ino_t
);
91 void pid_ns_record(void *priv
__attribute__((unused
)),
92 struct lttng_ust_probe_ctx
*probe_ctx
__attribute__((unused
)),
93 struct lttng_ust_ring_buffer_ctx
*ctx
,
94 struct lttng_ust_channel_buffer
*chan
)
98 pid_ns
= get_pid_ns();
99 chan
->ops
->event_write(ctx
, &pid_ns
, sizeof(pid_ns
), lttng_ust_rb_alignof(pid_ns
));
103 void pid_ns_get_value(void *priv
__attribute__((unused
)),
104 struct lttng_ust_probe_ctx
*probe_ctx
__attribute__((unused
)),
105 struct lttng_ust_ctx_value
*value
)
107 value
->u
.u64
= get_pid_ns();
110 static const struct lttng_ust_ctx_field
*ctx_field
= lttng_ust_static_ctx_field(
111 lttng_ust_static_event_field("pid_ns",
112 lttng_ust_static_type_integer(sizeof(ino_t
) * CHAR_BIT
,
113 lttng_ust_rb_alignof(ino_t
) * CHAR_BIT
,
114 lttng_ust_is_signed_type(ino_t
),
115 LTTNG_UST_BYTE_ORDER
, 10),
122 int lttng_add_pid_ns_to_ctx(struct lttng_ust_ctx
**ctx
)
126 if (lttng_find_context(*ctx
, ctx_field
->event_field
->name
)) {
128 goto error_find_context
;
130 ret
= lttng_ust_context_append(ctx
, ctx_field
);