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/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 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
)),
77 struct lttng_ust_probe_ctx
*probe_ctx
__attribute__((unused
)),
82 size
+= lttng_ust_ring_buffer_align(offset
, lttng_ust_rb_alignof(ino_t
));
83 size
+= sizeof(ino_t
);
88 void user_ns_record(void *priv
__attribute__((unused
)),
89 struct lttng_ust_probe_ctx
*probe_ctx
__attribute__((unused
)),
90 struct lttng_ust_ring_buffer_ctx
*ctx
,
91 struct lttng_ust_channel_buffer
*chan
)
95 user_ns
= get_user_ns();
96 chan
->ops
->event_write(ctx
, &user_ns
, sizeof(user_ns
), lttng_ust_rb_alignof(user_ns
));
100 void user_ns_get_value(void *priv
__attribute__((unused
)),
101 struct lttng_ust_probe_ctx
*probe_ctx
__attribute__((unused
)),
102 struct lttng_ust_ctx_value
*value
)
104 value
->u
.u64
= get_user_ns();
107 static const struct lttng_ust_ctx_field
*ctx_field
= lttng_ust_static_ctx_field(
108 lttng_ust_static_event_field("user_ns",
109 lttng_ust_static_type_integer(sizeof(ino_t
) * CHAR_BIT
,
110 lttng_ust_rb_alignof(ino_t
) * CHAR_BIT
,
111 lttng_ust_is_signed_type(ino_t
),
112 LTTNG_UST_BYTE_ORDER
, 10),
119 int lttng_add_user_ns_to_ctx(struct lttng_ust_ctx
**ctx
)
123 if (lttng_find_context(*ctx
, ctx_field
->event_field
->name
)) {
125 goto error_find_context
;
127 ret
= lttng_ust_context_append(ctx
, ctx_field
);