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 user namespace context.
13 #include <sys/types.h>
16 #include <lttng/ust-events.h>
17 #include <lttng/ust-tracer.h>
18 #include <lttng/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 user namespace is global to the process.
27 static ino_t cached_user_ns
= NS_INO_UNINITIALIZED
;
30 ino_t
get_user_ns(void)
35 user_ns
= CMM_LOAD_SHARED(cached_user_ns
);
38 * If the cache is populated, do nothing and return the
39 * cached inode number.
41 if (caa_likely(user_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 user_ns
= NS_INO_UNAVAILABLE
;
52 if (stat("/proc/self/ns/user", &sb
) == 0) {
57 * And finally, store the inode number in the cache.
59 CMM_STORE_SHARED(cached_user_ns
, user_ns
);
65 * The user namespace can change for 3 reasons
66 * * clone(2) called with CLONE_NEWUSER
67 * * setns(2) called with the fd of a different user ns
68 * * unshare(2) called with CLONE_NEWUSER
70 void lttng_context_user_ns_reset(void)
72 CMM_STORE_SHARED(cached_user_ns
, NS_INO_UNINITIALIZED
);
76 size_t user_ns_get_size(void *priv
__attribute__((unused
)),
81 size
+= lttng_ust_lib_ring_buffer_align(offset
, lttng_ust_rb_alignof(ino_t
));
82 size
+= sizeof(ino_t
);
87 void user_ns_record(void *priv
__attribute__((unused
)),
88 struct lttng_ust_lib_ring_buffer_ctx
*ctx
,
89 struct lttng_ust_channel_buffer
*chan
)
93 user_ns
= get_user_ns();
94 chan
->ops
->event_write(ctx
, &user_ns
, sizeof(user_ns
), lttng_ust_rb_alignof(user_ns
));
98 void user_ns_get_value(void *priv
__attribute__((unused
)),
99 struct lttng_ust_ctx_value
*value
)
101 value
->u
.s64
= get_user_ns();
104 static const struct lttng_ust_ctx_field
*ctx_field
= lttng_ust_static_ctx_field(
105 lttng_ust_static_event_field("user_ns",
106 lttng_ust_static_type_integer(sizeof(ino_t
) * CHAR_BIT
,
107 lttng_ust_rb_alignof(ino_t
) * CHAR_BIT
,
108 lttng_ust_is_signed_type(ino_t
),
116 int lttng_add_user_ns_to_ctx(struct lttng_ust_ctx
**ctx
)
120 if (lttng_find_context(*ctx
, ctx_field
->event_field
->name
)) {
122 goto error_find_context
;
124 ret
= lttng_ust_context_append(ctx
, ctx_field
);