Add userspace namespace contexts
[lttng-ust.git] / liblttng-ust / lttng-ust-comm.c
CommitLineData
2691221a
MD
1/*
2 * lttng-ust-comm.c
3 *
4 * Copyright (C) 2011 David Goulet <david.goulet@polymtl.ca>
5 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; only
10 * version 2.1 of the License.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
80e2814b 22#define _LGPL_SOURCE
5e1b7b8b 23#define _GNU_SOURCE
2691221a
MD
24#include <sys/types.h>
25#include <sys/socket.h>
7fc90dca
MD
26#include <sys/mman.h>
27#include <sys/stat.h>
58d4b2a2
MD
28#include <sys/types.h>
29#include <sys/wait.h>
b2292d85 30#include <dlfcn.h>
7fc90dca 31#include <fcntl.h>
2691221a
MD
32#include <unistd.h>
33#include <errno.h>
d9e99d10 34#include <pthread.h>
11ff9c7d
MD
35#include <semaphore.h>
36#include <time.h>
1ea11eab 37#include <assert.h>
e822f505 38#include <signal.h>
6f97f9c2 39#include <limits.h>
95259bd0 40#include <urcu/uatomic.h>
80e2814b 41#include <urcu/futex.h>
c117fb1b 42#include <urcu/compiler.h>
1ea11eab 43
4318ae1b 44#include <lttng/ust-events.h>
4318ae1b 45#include <lttng/ust-abi.h>
4318ae1b 46#include <lttng/ust.h>
7bc53e94 47#include <lttng/ust-error.h>
74d81a6c 48#include <lttng/ust-ctl.h>
8c90a710 49#include <urcu/tls-compat.h>
44c72f10 50#include <ust-comm.h>
6548fca4 51#include <ust-fd.h>
44c72f10 52#include <usterr-signal-safe.h>
cd54f6d9 53#include <helper.h>
44c72f10 54#include "tracepoint-internal.h"
7dd08bec 55#include "lttng-tracer-core.h"
08114193 56#include "compat.h"
6f97f9c2 57#include "../libringbuffer/rb-init.h"
cf73e0fe 58#include "lttng-ust-statedump.h"
f9364363 59#include "clock.h"
5e1b7b8b 60#include "../libringbuffer/getcpu.h"
13efba44 61#include "getenv.h"
edaa1431 62
b2292d85 63/* Concatenate lttng ust shared library name with its major version number. */
6be9efc1 64#define LTTNG_UST_LIB_SO_NAME "liblttng-ust.so." __ust_stringify(CONFIG_LTTNG_UST_LIBRARY_VERSION_MAJOR)
b2292d85 65
edaa1431
MD
66/*
67 * Has lttng ust comm constructor been called ?
68 */
69static int initialized;
70
1ea11eab 71/*
17dfb34b
MD
72 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
73 * Held when handling a command, also held by fork() to deal with
74 * removal of threads, and by exit path.
3327ac33
MD
75 *
76 * The UST lock is the centralized mutex across UST tracing control and
77 * probe registration.
78 *
79 * ust_exit_mutex must never nest in ust_mutex.
d58d1454 80 *
4770bd47
MD
81 * ust_fork_mutex must never nest in ust_mutex.
82 *
d58d1454
MD
83 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
84 * counter lazy initialization called by events within the statedump,
85 * which traces while the ust_mutex is held.
4770bd47
MD
86 *
87 * ust_lock nests within the dynamic loader lock (within glibc) because
88 * it is taken within the library constructor.
c1be081a
MD
89 *
90 * The ust fd tracker lock nests within the ust_mutex.
3327ac33
MD
91 */
92static pthread_mutex_t ust_mutex = PTHREAD_MUTEX_INITIALIZER;
93
d58d1454 94/* Allow nesting the ust_mutex within the same thread. */
16adecf1 95static DEFINE_URCU_TLS(int, ust_mutex_nest);
d58d1454 96
3327ac33
MD
97/*
98 * ust_exit_mutex protects thread_active variable wrt thread exit. It
99 * cannot be done by ust_mutex because pthread_cancel(), which takes an
100 * internal libc lock, cannot nest within ust_mutex.
101 *
102 * It never nests within a ust_mutex.
1ea11eab 103 */
3327ac33 104static pthread_mutex_t ust_exit_mutex = PTHREAD_MUTEX_INITIALIZER;
1ea11eab 105
458d678c
PW
106/*
107 * ust_fork_mutex protects base address statedump tracing against forks. It
108 * prevents the dynamic loader lock to be taken (by base address statedump
109 * tracing) while a fork is happening, thus preventing deadlock issues with
110 * the dynamic loader lock.
111 */
112static pthread_mutex_t ust_fork_mutex = PTHREAD_MUTEX_INITIALIZER;
113
1ea11eab
MD
114/* Should the ust comm thread quit ? */
115static int lttng_ust_comm_should_quit;
116
07b57e5e
MD
117/*
118 * This variable can be tested by applications to check whether
119 * lttng-ust is loaded. They simply have to define their own
120 * "lttng_ust_loaded" weak symbol, and test it. It is set to 1 by the
121 * library constructor.
122 */
123int lttng_ust_loaded __attribute__((weak));
124
3327ac33 125/*
d58d1454 126 * Return 0 on success, -1 if should quit.
3327ac33 127 * The lock is taken in both cases.
d58d1454 128 * Signal-safe.
3327ac33
MD
129 */
130int ust_lock(void)
131{
d58d1454 132 sigset_t sig_all_blocked, orig_mask;
e446ad80 133 int ret, oldstate;
d58d1454 134
e446ad80
MD
135 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
136 if (ret) {
137 ERR("pthread_setcancelstate: %s", strerror(ret));
138 }
139 if (oldstate != PTHREAD_CANCEL_ENABLE) {
140 ERR("pthread_setcancelstate: unexpected oldstate");
141 }
d58d1454
MD
142 sigfillset(&sig_all_blocked);
143 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
144 if (ret) {
145 ERR("pthread_sigmask: %s", strerror(ret));
146 }
147 if (!URCU_TLS(ust_mutex_nest)++)
148 pthread_mutex_lock(&ust_mutex);
149 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
150 if (ret) {
151 ERR("pthread_sigmask: %s", strerror(ret));
152 }
3327ac33
MD
153 if (lttng_ust_comm_should_quit) {
154 return -1;
155 } else {
156 return 0;
157 }
158}
159
160/*
161 * ust_lock_nocheck() can be used in constructors/destructors, because
162 * they are already nested within the dynamic loader lock, and therefore
163 * have exclusive access against execution of liblttng-ust destructor.
d58d1454 164 * Signal-safe.
3327ac33
MD
165 */
166void ust_lock_nocheck(void)
167{
d58d1454 168 sigset_t sig_all_blocked, orig_mask;
e446ad80 169 int ret, oldstate;
d58d1454 170
e446ad80
MD
171 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
172 if (ret) {
173 ERR("pthread_setcancelstate: %s", strerror(ret));
174 }
175 if (oldstate != PTHREAD_CANCEL_ENABLE) {
176 ERR("pthread_setcancelstate: unexpected oldstate");
177 }
d58d1454
MD
178 sigfillset(&sig_all_blocked);
179 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
180 if (ret) {
181 ERR("pthread_sigmask: %s", strerror(ret));
182 }
183 if (!URCU_TLS(ust_mutex_nest)++)
184 pthread_mutex_lock(&ust_mutex);
185 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
186 if (ret) {
187 ERR("pthread_sigmask: %s", strerror(ret));
188 }
3327ac33
MD
189}
190
d58d1454
MD
191/*
192 * Signal-safe.
193 */
3327ac33
MD
194void ust_unlock(void)
195{
d58d1454 196 sigset_t sig_all_blocked, orig_mask;
e446ad80 197 int ret, oldstate;
d58d1454
MD
198
199 sigfillset(&sig_all_blocked);
200 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
201 if (ret) {
202 ERR("pthread_sigmask: %s", strerror(ret));
203 }
204 if (!--URCU_TLS(ust_mutex_nest))
205 pthread_mutex_unlock(&ust_mutex);
206 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
207 if (ret) {
208 ERR("pthread_sigmask: %s", strerror(ret));
209 }
e446ad80
MD
210 ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
211 if (ret) {
212 ERR("pthread_setcancelstate: %s", strerror(ret));
213 }
214 if (oldstate != PTHREAD_CANCEL_DISABLE) {
215 ERR("pthread_setcancelstate: unexpected oldstate");
216 }
3327ac33
MD
217}
218
11ff9c7d
MD
219/*
220 * Wait for either of these before continuing to the main
221 * program:
222 * - the register_done message from sessiond daemon
223 * (will let the sessiond daemon enable sessions before main
224 * starts.)
225 * - sessiond daemon is not reachable.
226 * - timeout (ensuring applications are resilient to session
227 * daemon problems).
228 */
229static sem_t constructor_wait;
950aab0c
MD
230/*
231 * Doing this for both the global and local sessiond.
232 */
eb0e6022
GAPG
233enum {
234 sem_count_initial_value = 4,
235};
236
237static int sem_count = sem_count_initial_value;
11ff9c7d 238
e8508a49
MD
239/*
240 * Counting nesting within lttng-ust. Used to ensure that calling fork()
241 * from liblttng-ust does not execute the pre/post fork handlers.
242 */
8c90a710 243static DEFINE_URCU_TLS(int, lttng_ust_nest_count);
e8508a49 244
1ea11eab
MD
245/*
246 * Info about socket and associated listener thread.
247 */
248struct sock_info {
11ff9c7d 249 const char *name;
1ea11eab 250 pthread_t ust_listener; /* listener thread */
46050b1a 251 int root_handle;
eb0e6022 252 int registration_done;
8d20bf54 253 int allowed;
44e073f5 254 int global;
e33f3265 255 int thread_active;
7fc90dca
MD
256
257 char sock_path[PATH_MAX];
258 int socket;
32ce8569 259 int notify_socket;
7fc90dca
MD
260
261 char wait_shm_path[PATH_MAX];
262 char *wait_shm_mmap;
37dddb65
MD
263 /* Keep track of lazy state dump not performed yet. */
264 int statedump_pending;
eb0e6022 265 int initial_statedump_done;
1ea11eab 266};
2691221a
MD
267
268/* Socket from app (connect) to session daemon (listen) for communication */
1ea11eab 269struct sock_info global_apps = {
11ff9c7d 270 .name = "global",
44e073f5 271 .global = 1,
7fc90dca 272
46050b1a 273 .root_handle = -1,
eb0e6022 274 .registration_done = 0,
060577e3 275 .allowed = 0,
e33f3265 276 .thread_active = 0,
7fc90dca 277
32ce8569 278 .sock_path = LTTNG_DEFAULT_RUNDIR "/" LTTNG_UST_SOCK_FILENAME,
7fc90dca 279 .socket = -1,
32ce8569 280 .notify_socket = -1,
7fc90dca 281
32ce8569 282 .wait_shm_path = "/" LTTNG_UST_WAIT_FILENAME,
95c25348 283
37dddb65 284 .statedump_pending = 0,
eb0e6022 285 .initial_statedump_done = 0,
1ea11eab 286};
2691221a
MD
287
288/* TODO: allow global_apps_sock_path override */
289
1ea11eab 290struct sock_info local_apps = {
11ff9c7d 291 .name = "local",
44e073f5 292 .global = 0,
46050b1a 293 .root_handle = -1,
eb0e6022 294 .registration_done = 0,
8d20bf54 295 .allowed = 0, /* Check setuid bit first */
e33f3265 296 .thread_active = 0,
7fc90dca
MD
297
298 .socket = -1,
32ce8569 299 .notify_socket = -1,
95c25348 300
37dddb65 301 .statedump_pending = 0,
eb0e6022 302 .initial_statedump_done = 0,
1ea11eab 303};
2691221a 304
37ed587a
MD
305static int wait_poll_fallback;
306
74d81a6c
MD
307static const char *cmd_name_mapping[] = {
308 [ LTTNG_UST_RELEASE ] = "Release",
309 [ LTTNG_UST_SESSION ] = "Create Session",
310 [ LTTNG_UST_TRACER_VERSION ] = "Get Tracer Version",
311
312 [ LTTNG_UST_TRACEPOINT_LIST ] = "Create Tracepoint List",
313 [ LTTNG_UST_WAIT_QUIESCENT ] = "Wait for Quiescent State",
314 [ LTTNG_UST_REGISTER_DONE ] = "Registration Done",
315 [ LTTNG_UST_TRACEPOINT_FIELD_LIST ] = "Create Tracepoint Field List",
316
317 /* Session FD commands */
318 [ LTTNG_UST_CHANNEL ] = "Create Channel",
319 [ LTTNG_UST_SESSION_START ] = "Start Session",
320 [ LTTNG_UST_SESSION_STOP ] = "Stop Session",
321
322 /* Channel FD commands */
323 [ LTTNG_UST_STREAM ] = "Create Stream",
324 [ LTTNG_UST_EVENT ] = "Create Event",
325
326 /* Event and Channel FD commands */
327 [ LTTNG_UST_CONTEXT ] = "Create Context",
328 [ LTTNG_UST_FLUSH_BUFFER ] = "Flush Buffer",
329
330 /* Event, Channel and Session commands */
331 [ LTTNG_UST_ENABLE ] = "Enable",
332 [ LTTNG_UST_DISABLE ] = "Disable",
333
334 /* Tracepoint list commands */
335 [ LTTNG_UST_TRACEPOINT_LIST_GET ] = "List Next Tracepoint",
336 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET ] = "List Next Tracepoint Field",
337
338 /* Event FD commands */
339 [ LTTNG_UST_FILTER ] = "Create Filter",
75582b3a 340 [ LTTNG_UST_EXCLUSION ] = "Add exclusions to event",
74d81a6c
MD
341};
342
ff517991
MD
343static const char *str_timeout;
344static int got_timeout_env;
345
7dd08bec 346extern void lttng_ring_buffer_client_overwrite_init(void);
34a91bdb 347extern void lttng_ring_buffer_client_overwrite_rt_init(void);
7dd08bec 348extern void lttng_ring_buffer_client_discard_init(void);
34a91bdb 349extern void lttng_ring_buffer_client_discard_rt_init(void);
7dd08bec
MD
350extern void lttng_ring_buffer_metadata_client_init(void);
351extern void lttng_ring_buffer_client_overwrite_exit(void);
34a91bdb 352extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
7dd08bec 353extern void lttng_ring_buffer_client_discard_exit(void);
34a91bdb 354extern void lttng_ring_buffer_client_discard_rt_exit(void);
7dd08bec 355extern void lttng_ring_buffer_metadata_client_exit(void);
edaa1431 356
060577e3
JR
357static char *get_map_shm(struct sock_info *sock_info);
358
405be658
MD
359ssize_t lttng_ust_read(int fd, void *buf, size_t len)
360{
361 ssize_t ret;
362 size_t copied = 0, to_copy = len;
363
364 do {
365 ret = read(fd, buf + copied, to_copy);
366 if (ret > 0) {
367 copied += ret;
368 to_copy -= ret;
369 }
370 } while ((ret > 0 && to_copy > 0)
371 || (ret < 0 && errno == EINTR));
372 if (ret > 0) {
373 ret = copied;
374 }
375 return ret;
376}
3c6f6263
AM
377/*
378 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
379 * pointer.
380 */
381static
382const char *get_lttng_home_dir(void)
383{
384 const char *val;
385
6f626d28 386 val = (const char *) lttng_getenv("LTTNG_HOME");
3c6f6263
AM
387 if (val != NULL) {
388 return val;
389 }
6f626d28 390 return (const char *) lttng_getenv("HOME");
3c6f6263
AM
391}
392
a903623f
MD
393/*
394 * Force a read (imply TLS fixup for dlopen) of TLS variables.
395 */
396static
397void lttng_fixup_nest_count_tls(void)
398{
8c90a710 399 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count)));
a903623f
MD
400}
401
d58d1454
MD
402static
403void lttng_fixup_ust_mutex_nest_tls(void)
404{
405 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest)));
406}
407
1556a549
MD
408/*
409 * Fixup urcu bp TLS.
410 */
411static
412void lttng_fixup_urcu_bp_tls(void)
413{
414 rcu_read_lock();
415 rcu_read_unlock();
416}
417
c362addf
MD
418void lttng_ust_fixup_tls(void)
419{
420 lttng_fixup_urcu_bp_tls();
421 lttng_fixup_ringbuffer_tls();
422 lttng_fixup_vtid_tls();
423 lttng_fixup_nest_count_tls();
424 lttng_fixup_procname_tls();
425 lttng_fixup_ust_mutex_nest_tls();
20142124 426 lttng_ust_fixup_perf_counter_tls();
6548fca4 427 lttng_ust_fixup_fd_tracker_tls();
735bef47
MJ
428 lttng_fixup_cgroup_ns_tls();
429 lttng_fixup_ipc_ns_tls();
430 lttng_fixup_net_ns_tls();
431 lttng_fixup_uts_ns_tls();
c362addf
MD
432}
433
32ce8569
MD
434int lttng_get_notify_socket(void *owner)
435{
436 struct sock_info *info = owner;
437
438 return info->notify_socket;
439}
440
74d81a6c
MD
441static
442void print_cmd(int cmd, int handle)
443{
444 const char *cmd_name = "Unknown";
445
fd67a004
MD
446 if (cmd >= 0 && cmd < LTTNG_ARRAY_SIZE(cmd_name_mapping)
447 && cmd_name_mapping[cmd]) {
74d81a6c
MD
448 cmd_name = cmd_name_mapping[cmd];
449 }
fd67a004
MD
450 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
451 cmd_name, cmd,
74d81a6c
MD
452 lttng_ust_obj_get_name(handle), handle);
453}
454
060577e3
JR
455static
456int setup_global_apps(void)
457{
458 int ret = 0;
459 assert(!global_apps.wait_shm_mmap);
460
461 global_apps.wait_shm_mmap = get_map_shm(&global_apps);
462 if (!global_apps.wait_shm_mmap) {
463 WARN("Unable to get map shm for global apps. Disabling LTTng-UST global tracing.");
464 global_apps.allowed = 0;
465 ret = -EIO;
466 goto error;
467 }
468
469 global_apps.allowed = 1;
470error:
471 return ret;
472}
2691221a 473static
8d20bf54 474int setup_local_apps(void)
2691221a 475{
060577e3 476 int ret = 0;
2691221a 477 const char *home_dir;
7fc90dca 478 uid_t uid;
2691221a 479
060577e3
JR
480 assert(!local_apps.wait_shm_mmap);
481
7fc90dca 482 uid = getuid();
8d20bf54
MD
483 /*
484 * Disallow per-user tracing for setuid binaries.
485 */
7fc90dca 486 if (uid != geteuid()) {
9ec6895c 487 assert(local_apps.allowed == 0);
060577e3
JR
488 ret = 0;
489 goto end;
8d20bf54 490 }
3c6f6263 491 home_dir = get_lttng_home_dir();
9ec6895c
MD
492 if (!home_dir) {
493 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
494 assert(local_apps.allowed == 0);
060577e3
JR
495 ret = -ENOENT;
496 goto end;
9ec6895c
MD
497 }
498 local_apps.allowed = 1;
32ce8569
MD
499 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
500 home_dir,
501 LTTNG_DEFAULT_HOME_RUNDIR,
502 LTTNG_UST_SOCK_FILENAME);
503 snprintf(local_apps.wait_shm_path, PATH_MAX, "/%s-%u",
504 LTTNG_UST_WAIT_FILENAME,
505 uid);
060577e3
JR
506
507 local_apps.wait_shm_mmap = get_map_shm(&local_apps);
508 if (!local_apps.wait_shm_mmap) {
509 WARN("Unable to get map shm for local apps. Disabling LTTng-UST per-user tracing.");
510 local_apps.allowed = 0;
511 ret = -EIO;
512 goto end;
513 }
514end:
515 return ret;
2691221a
MD
516}
517
ff517991 518/*
451d66b2 519 * Get socket timeout, in ms.
28515902 520 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
ff517991
MD
521 */
522static
523long get_timeout(void)
524{
525 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
526
527 if (!got_timeout_env) {
6f626d28 528 str_timeout = lttng_getenv("LTTNG_UST_REGISTER_TIMEOUT");
ff517991
MD
529 got_timeout_env = 1;
530 }
531 if (str_timeout)
532 constructor_delay_ms = strtol(str_timeout, NULL, 10);
5cf81d53
MD
533 /* All negative values are considered as "-1". */
534 if (constructor_delay_ms < -1)
535 constructor_delay_ms = -1;
ff517991
MD
536 return constructor_delay_ms;
537}
538
451d66b2 539/* Timeout for notify socket send and recv. */
ff517991
MD
540static
541long get_notify_sock_timeout(void)
542{
543 return get_timeout();
544}
545
451d66b2
MD
546/* Timeout for connecting to cmd and notify sockets. */
547static
548long get_connect_sock_timeout(void)
549{
550 return get_timeout();
551}
552
ff517991 553/*
28515902 554 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
ff517991
MD
555 */
556static
557int get_constructor_timeout(struct timespec *constructor_timeout)
558{
559 long constructor_delay_ms;
560 int ret;
561
562 constructor_delay_ms = get_timeout();
563
564 switch (constructor_delay_ms) {
565 case -1:/* fall-through */
566 case 0:
567 return constructor_delay_ms;
568 default:
569 break;
570 }
571
572 /*
573 * If we are unable to find the current time, don't wait.
574 */
575 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
576 if (ret) {
28515902
JG
577 /* Don't wait. */
578 return 0;
ff517991
MD
579 }
580 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
581 constructor_timeout->tv_nsec +=
582 (constructor_delay_ms % 1000UL) * 1000000UL;
583 if (constructor_timeout->tv_nsec >= 1000000000UL) {
584 constructor_timeout->tv_sec++;
585 constructor_timeout->tv_nsec -= 1000000000UL;
586 }
28515902 587 /* Timeout wait (constructor_delay_ms). */
ff517991
MD
588 return 1;
589}
590
6f97f9c2 591static
b2c5f61a 592void get_allow_blocking(void)
6f97f9c2 593{
b2c5f61a
MD
594 const char *str_allow_blocking =
595 lttng_getenv("LTTNG_UST_ALLOW_BLOCKING");
596
597 if (str_allow_blocking) {
598 DBG("%s environment variable is set",
599 "LTTNG_UST_ALLOW_BLOCKING");
600 lttng_ust_ringbuffer_set_allow_blocking();
6f97f9c2
MD
601 }
602}
603
2691221a 604static
32ce8569 605int register_to_sessiond(int socket, enum ustctl_socket_type type)
2691221a 606{
32ce8569
MD
607 return ustcomm_send_reg_msg(socket,
608 type,
609 CAA_BITS_PER_LONG,
610 lttng_alignof(uint8_t) * CHAR_BIT,
611 lttng_alignof(uint16_t) * CHAR_BIT,
612 lttng_alignof(uint32_t) * CHAR_BIT,
613 lttng_alignof(uint64_t) * CHAR_BIT,
614 lttng_alignof(unsigned long) * CHAR_BIT);
2691221a
MD
615}
616
d9e99d10 617static
57773204 618int send_reply(int sock, struct ustcomm_ust_reply *lur)
d9e99d10 619{
9eb62b9c 620 ssize_t len;
d3a492d1 621
57773204 622 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
d3a492d1 623 switch (len) {
a4be8962 624 case sizeof(*lur):
d3a492d1
MD
625 DBG("message successfully sent");
626 return 0;
7bc53e94
MD
627 default:
628 if (len == -ECONNRESET) {
629 DBG("remote end closed connection");
d3a492d1
MD
630 return 0;
631 }
7bc53e94
MD
632 if (len < 0)
633 return len;
634 DBG("incorrect message size: %zd", len);
635 return -EINVAL;
d3a492d1
MD
636 }
637}
638
639static
eb0e6022 640void decrement_sem_count(unsigned int count)
11ff9c7d
MD
641{
642 int ret;
643
eb0e6022
GAPG
644 assert(uatomic_read(&sem_count) >= count);
645
56cd7e2f 646 if (uatomic_read(&sem_count) <= 0) {
eb0e6022 647 return;
56cd7e2f 648 }
eb0e6022
GAPG
649
650 ret = uatomic_add_return(&sem_count, -count);
95259bd0
MD
651 if (ret == 0) {
652 ret = sem_post(&constructor_wait);
653 assert(!ret);
654 }
eb0e6022
GAPG
655}
656
657static
658int handle_register_done(struct sock_info *sock_info)
659{
660 if (sock_info->registration_done)
661 return 0;
662 sock_info->registration_done = 1;
663
664 decrement_sem_count(1);
04682184
MD
665 if (!sock_info->statedump_pending) {
666 sock_info->initial_statedump_done = 1;
667 decrement_sem_count(1);
668 }
eb0e6022
GAPG
669
670 return 0;
671}
672
673static
674int handle_register_failed(struct sock_info *sock_info)
675{
676 if (sock_info->registration_done)
677 return 0;
678 sock_info->registration_done = 1;
679 sock_info->initial_statedump_done = 1;
680
681 decrement_sem_count(2);
682
11ff9c7d
MD
683 return 0;
684}
685
37dddb65
MD
686/*
687 * Only execute pending statedump after the constructor semaphore has
eb0e6022
GAPG
688 * been posted by the current listener thread. This means statedump will
689 * only be performed after the "registration done" command is received
690 * from this thread's session daemon.
37dddb65
MD
691 *
692 * This ensures we don't run into deadlock issues with the dynamic
693 * loader mutex, which is held while the constructor is called and
694 * waiting on the constructor semaphore. All operations requiring this
695 * dynamic loader lock need to be postponed using this mechanism.
eb0e6022
GAPG
696 *
697 * In a scenario with two session daemons connected to the application,
698 * it is possible that the first listener thread which receives the
699 * registration done command issues its statedump while the dynamic
700 * loader lock is still held by the application constructor waiting on
701 * the semaphore. It will however be allowed to proceed when the
702 * second session daemon sends the registration done command to the
703 * second listener thread. This situation therefore does not produce
704 * a deadlock.
37dddb65
MD
705 */
706static
707void handle_pending_statedump(struct sock_info *sock_info)
708{
eb0e6022 709 if (sock_info->registration_done && sock_info->statedump_pending) {
37dddb65 710 sock_info->statedump_pending = 0;
2932a87f 711 pthread_mutex_lock(&ust_fork_mutex);
37dddb65 712 lttng_handle_pending_statedump(sock_info);
458d678c 713 pthread_mutex_unlock(&ust_fork_mutex);
eb0e6022
GAPG
714
715 if (!sock_info->initial_statedump_done) {
716 sock_info->initial_statedump_done = 1;
717 decrement_sem_count(1);
718 }
37dddb65
MD
719 }
720}
721
11ff9c7d
MD
722static
723int handle_message(struct sock_info *sock_info,
57773204 724 int sock, struct ustcomm_ust_msg *lum)
d3a492d1 725{
1ea11eab 726 int ret = 0;
b61ce3b2 727 const struct lttng_ust_objd_ops *ops;
57773204 728 struct ustcomm_ust_reply lur;
ef9ff354 729 union ust_args args;
8e696cfa 730 char ctxstr[LTTNG_UST_SYM_NAME_LEN]; /* App context string. */
40003310 731 ssize_t len;
1ea11eab 732
46050b1a
MD
733 memset(&lur, 0, sizeof(lur));
734
3327ac33 735 if (ust_lock()) {
74d81a6c 736 ret = -LTTNG_UST_ERR_EXITING;
0dafcd63 737 goto error;
1ea11eab 738 }
9eb62b9c 739
46050b1a
MD
740 ops = objd_ops(lum->handle);
741 if (!ops) {
742 ret = -ENOENT;
0dafcd63 743 goto error;
1ea11eab 744 }
46050b1a
MD
745
746 switch (lum->cmd) {
11ff9c7d
MD
747 case LTTNG_UST_REGISTER_DONE:
748 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
edaa1431 749 ret = handle_register_done(sock_info);
11ff9c7d
MD
750 else
751 ret = -EINVAL;
752 break;
46050b1a
MD
753 case LTTNG_UST_RELEASE:
754 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
755 ret = -EPERM;
756 else
1849ef7c 757 ret = lttng_ust_objd_unref(lum->handle, 1);
d9e99d10 758 break;
2d78951a
MD
759 case LTTNG_UST_FILTER:
760 {
761 /* Receive filter data */
f488575f 762 struct lttng_ust_filter_bytecode_node *bytecode;
2d78951a 763
cd54f6d9 764 if (lum->u.filter.data_size > FILTER_BYTECODE_MAX_LEN) {
7bc53e94 765 ERR("Filter data size is too large: %u bytes",
2d78951a
MD
766 lum->u.filter.data_size);
767 ret = -EINVAL;
768 goto error;
769 }
2734ca65 770
885b1dfd 771 if (lum->u.filter.reloc_offset > lum->u.filter.data_size) {
7bc53e94 772 ERR("Filter reloc offset %u is not within data",
2734ca65
CB
773 lum->u.filter.reloc_offset);
774 ret = -EINVAL;
775 goto error;
776 }
777
cd54f6d9
MD
778 bytecode = zmalloc(sizeof(*bytecode) + lum->u.filter.data_size);
779 if (!bytecode) {
780 ret = -ENOMEM;
781 goto error;
782 }
f488575f 783 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data,
2d78951a
MD
784 lum->u.filter.data_size);
785 switch (len) {
786 case 0: /* orderly shutdown */
787 ret = 0;
cd54f6d9 788 free(bytecode);
2d78951a 789 goto error;
2d78951a
MD
790 default:
791 if (len == lum->u.filter.data_size) {
7bc53e94 792 DBG("filter data received");
2d78951a 793 break;
7bc53e94
MD
794 } else if (len < 0) {
795 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
796 if (len == -ECONNRESET) {
797 ERR("%s remote end closed connection", sock_info->name);
798 ret = len;
799 free(bytecode);
800 goto error;
801 }
802 ret = len;
eb8bf361 803 free(bytecode);
0dafcd63 804 goto error;
2d78951a 805 } else {
7bc53e94 806 DBG("incorrect filter data message size: %zd", len);
2d78951a 807 ret = -EINVAL;
cd54f6d9 808 free(bytecode);
0dafcd63 809 goto error;
2d78951a
MD
810 }
811 }
f488575f
MD
812 bytecode->bc.len = lum->u.filter.data_size;
813 bytecode->bc.reloc_offset = lum->u.filter.reloc_offset;
3f6fd224 814 bytecode->bc.seqnum = lum->u.filter.seqnum;
cd54f6d9 815 if (ops->cmd) {
2d78951a 816 ret = ops->cmd(lum->handle, lum->cmd,
cd54f6d9 817 (unsigned long) bytecode,
f59ed768 818 &args, sock_info);
cd54f6d9
MD
819 if (ret) {
820 free(bytecode);
821 }
822 /* don't free bytecode if everything went fine. */
823 } else {
2d78951a 824 ret = -ENOSYS;
cd54f6d9
MD
825 free(bytecode);
826 }
2d78951a
MD
827 break;
828 }
86e36163
JI
829 case LTTNG_UST_EXCLUSION:
830 {
831 /* Receive exclusion names */
832 struct lttng_ust_excluder_node *node;
833 unsigned int count;
834
835 count = lum->u.exclusion.count;
836 if (count == 0) {
837 /* There are no names to read */
838 ret = 0;
839 goto error;
840 }
841 node = zmalloc(sizeof(*node) +
842 count * LTTNG_UST_SYM_NAME_LEN);
843 if (!node) {
844 ret = -ENOMEM;
845 goto error;
846 }
847 node->excluder.count = count;
848 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
849 count * LTTNG_UST_SYM_NAME_LEN);
850 switch (len) {
851 case 0: /* orderly shutdown */
852 ret = 0;
853 free(node);
854 goto error;
855 default:
856 if (len == count * LTTNG_UST_SYM_NAME_LEN) {
857 DBG("Exclusion data received");
858 break;
859 } else if (len < 0) {
860 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
861 if (len == -ECONNRESET) {
862 ERR("%s remote end closed connection", sock_info->name);
863 ret = len;
864 free(node);
865 goto error;
866 }
867 ret = len;
868 free(node);
0dafcd63 869 goto error;
86e36163
JI
870 } else {
871 DBG("Incorrect exclusion data message size: %zd", len);
872 ret = -EINVAL;
873 free(node);
0dafcd63 874 goto error;
86e36163
JI
875 }
876 }
877 if (ops->cmd) {
878 ret = ops->cmd(lum->handle, lum->cmd,
879 (unsigned long) node,
880 &args, sock_info);
881 if (ret) {
882 free(node);
883 }
884 /* Don't free exclusion data if everything went fine. */
885 } else {
886 ret = -ENOSYS;
887 free(node);
888 }
889 break;
890 }
74d81a6c
MD
891 case LTTNG_UST_CHANNEL:
892 {
893 void *chan_data;
ff0f5728 894 int wakeup_fd;
74d81a6c
MD
895
896 len = ustcomm_recv_channel_from_sessiond(sock,
ff0f5728
MD
897 &chan_data, lum->u.channel.len,
898 &wakeup_fd);
74d81a6c
MD
899 switch (len) {
900 case 0: /* orderly shutdown */
901 ret = 0;
902 goto error;
903 default:
904 if (len == lum->u.channel.len) {
905 DBG("channel data received");
906 break;
907 } else if (len < 0) {
908 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
909 if (len == -ECONNRESET) {
910 ERR("%s remote end closed connection", sock_info->name);
911 ret = len;
912 goto error;
913 }
914 ret = len;
0dafcd63 915 goto error;
74d81a6c
MD
916 } else {
917 DBG("incorrect channel data message size: %zd", len);
918 ret = -EINVAL;
0dafcd63 919 goto error;
74d81a6c
MD
920 }
921 }
922 args.channel.chan_data = chan_data;
ff0f5728 923 args.channel.wakeup_fd = wakeup_fd;
74d81a6c
MD
924 if (ops->cmd)
925 ret = ops->cmd(lum->handle, lum->cmd,
926 (unsigned long) &lum->u,
927 &args, sock_info);
928 else
929 ret = -ENOSYS;
930 break;
931 }
932 case LTTNG_UST_STREAM:
933 {
934 /* Receive shm_fd, wakeup_fd */
935 ret = ustcomm_recv_stream_from_sessiond(sock,
61e520fb 936 NULL,
74d81a6c
MD
937 &args.stream.shm_fd,
938 &args.stream.wakeup_fd);
939 if (ret) {
0dafcd63 940 goto error;
74d81a6c 941 }
973eac63 942
74d81a6c
MD
943 if (ops->cmd)
944 ret = ops->cmd(lum->handle, lum->cmd,
945 (unsigned long) &lum->u,
946 &args, sock_info);
947 else
948 ret = -ENOSYS;
949 break;
950 }
8e696cfa
MD
951 case LTTNG_UST_CONTEXT:
952 switch (lum->u.context.ctx) {
953 case LTTNG_UST_CONTEXT_APP_CONTEXT:
954 {
955 char *p;
956 size_t ctxlen, recvlen;
957
958 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
959 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
960 if (ctxlen >= LTTNG_UST_SYM_NAME_LEN) {
961 ERR("Application context string length size is too large: %zu bytes",
962 ctxlen);
963 ret = -EINVAL;
964 goto error;
965 }
966 strcpy(ctxstr, "$app.");
967 p = &ctxstr[strlen("$app.")];
968 recvlen = ctxlen - strlen("$app.");
969 len = ustcomm_recv_unix_sock(sock, p, recvlen);
970 switch (len) {
971 case 0: /* orderly shutdown */
972 ret = 0;
973 goto error;
974 default:
975 if (len == recvlen) {
976 DBG("app context data received");
977 break;
978 } else if (len < 0) {
979 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
980 if (len == -ECONNRESET) {
981 ERR("%s remote end closed connection", sock_info->name);
982 ret = len;
983 goto error;
984 }
985 ret = len;
986 goto error;
987 } else {
988 DBG("incorrect app context data message size: %zd", len);
989 ret = -EINVAL;
990 goto error;
991 }
992 }
993 /* Put : between provider and ctxname. */
994 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
995 args.app_context.ctxname = ctxstr;
996 break;
997 }
998 default:
999 break;
1000 }
1001 if (ops->cmd) {
1002 ret = ops->cmd(lum->handle, lum->cmd,
1003 (unsigned long) &lum->u,
1004 &args, sock_info);
1005 } else {
1006 ret = -ENOSYS;
1007 }
1008 break;
d9e99d10 1009 default:
46050b1a
MD
1010 if (ops->cmd)
1011 ret = ops->cmd(lum->handle, lum->cmd,
ef9ff354 1012 (unsigned long) &lum->u,
f59ed768 1013 &args, sock_info);
46050b1a
MD
1014 else
1015 ret = -ENOSYS;
1016 break;
d9e99d10 1017 }
46050b1a 1018
46050b1a
MD
1019 lur.handle = lum->handle;
1020 lur.cmd = lum->cmd;
1021 lur.ret_val = ret;
1022 if (ret >= 0) {
7bc53e94 1023 lur.ret_code = LTTNG_UST_OK;
46050b1a 1024 } else {
7bc53e94
MD
1025 /*
1026 * Use -LTTNG_UST_ERR as wildcard for UST internal
1027 * error that are not caused by the transport, except if
1028 * we already have a more precise error message to
1029 * report.
1030 */
64b2564e
DG
1031 if (ret > -LTTNG_UST_ERR) {
1032 /* Translate code to UST error. */
1033 switch (ret) {
1034 case -EEXIST:
1035 lur.ret_code = -LTTNG_UST_ERR_EXIST;
1036 break;
1037 case -EINVAL:
1038 lur.ret_code = -LTTNG_UST_ERR_INVAL;
1039 break;
1040 case -ENOENT:
1041 lur.ret_code = -LTTNG_UST_ERR_NOENT;
1042 break;
1043 case -EPERM:
1044 lur.ret_code = -LTTNG_UST_ERR_PERM;
1045 break;
1046 case -ENOSYS:
1047 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
1048 break;
1049 default:
1050 lur.ret_code = -LTTNG_UST_ERR;
1051 break;
1052 }
1053 } else {
7bc53e94 1054 lur.ret_code = ret;
64b2564e 1055 }
46050b1a 1056 }
e6ea14c5
MD
1057 if (ret >= 0) {
1058 switch (lum->cmd) {
e6ea14c5
MD
1059 case LTTNG_UST_TRACER_VERSION:
1060 lur.u.version = lum->u.version;
1061 break;
1062 case LTTNG_UST_TRACEPOINT_LIST_GET:
1063 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1064 break;
1065 }
381c0f1e 1066 }
74d81a6c 1067 DBG("Return value: %d", lur.ret_val);
4c62d8d1
MD
1068
1069 ust_unlock();
1070
1071 /*
1072 * Performed delayed statedump operations outside of the UST
1073 * lock. We need to take the dynamic loader lock before we take
1074 * the UST lock internally within handle_pending_statedump().
1075 */
1076 handle_pending_statedump(sock_info);
1077
1078 if (ust_lock()) {
1079 ret = -LTTNG_UST_ERR_EXITING;
1080 goto error;
1081 }
1082
46050b1a 1083 ret = send_reply(sock, &lur);
193183fb 1084 if (ret < 0) {
7bc53e94 1085 DBG("error sending reply");
193183fb
MD
1086 goto error;
1087 }
46050b1a 1088
40003310
MD
1089 /*
1090 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1091 * after the reply.
1092 */
7bc53e94 1093 if (lur.ret_code == LTTNG_UST_OK) {
40003310
MD
1094 switch (lum->cmd) {
1095 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
1096 len = ustcomm_send_unix_sock(sock,
1097 &args.field_list.entry,
1098 sizeof(args.field_list.entry));
7bc53e94
MD
1099 if (len < 0) {
1100 ret = len;
1101 goto error;
1102 }
40003310 1103 if (len != sizeof(args.field_list.entry)) {
7bc53e94 1104 ret = -EINVAL;
40003310
MD
1105 goto error;
1106 }
1107 }
1108 }
ef9ff354 1109
381c0f1e 1110error:
17dfb34b 1111 ust_unlock();
d9e99d10 1112
37dddb65 1113 return ret;
246be17e
PW
1114}
1115
46050b1a 1116static
efe0de09 1117void cleanup_sock_info(struct sock_info *sock_info, int exiting)
46050b1a
MD
1118{
1119 int ret;
1120
5b14aab3
MD
1121 if (sock_info->root_handle != -1) {
1122 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1123 if (ret) {
1124 ERR("Error unref root handle");
1125 }
1126 sock_info->root_handle = -1;
1127 }
eb0e6022
GAPG
1128 sock_info->registration_done = 0;
1129 sock_info->initial_statedump_done = 0;
5b14aab3
MD
1130
1131 /*
1132 * wait_shm_mmap, socket and notify socket are used by listener
1133 * threads outside of the ust lock, so we cannot tear them down
1134 * ourselves, because we cannot join on these threads. Leave
1135 * responsibility of cleaning up these resources to the OS
1136 * process exit.
1137 */
1138 if (exiting)
1139 return;
1140
46050b1a 1141 if (sock_info->socket != -1) {
e6973a89 1142 ret = ustcomm_close_unix_sock(sock_info->socket);
46050b1a 1143 if (ret) {
32ce8569 1144 ERR("Error closing ust cmd socket");
46050b1a
MD
1145 }
1146 sock_info->socket = -1;
1147 }
32ce8569
MD
1148 if (sock_info->notify_socket != -1) {
1149 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1150 if (ret) {
1151 ERR("Error closing ust notify socket");
1152 }
1153 sock_info->notify_socket = -1;
1154 }
5b14aab3 1155 if (sock_info->wait_shm_mmap) {
172d6b68
MD
1156 long page_size;
1157
1158 page_size = sysconf(_SC_PAGE_SIZE);
2657d1ba
MD
1159 if (page_size <= 0) {
1160 if (!page_size) {
1161 errno = EINVAL;
1162 }
1163 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1164 } else {
172d6b68
MD
1165 ret = munmap(sock_info->wait_shm_mmap, page_size);
1166 if (ret) {
1167 ERR("Error unmapping wait shm");
1168 }
7fc90dca
MD
1169 }
1170 sock_info->wait_shm_mmap = NULL;
1171 }
1172}
1173
58d4b2a2 1174/*
33bbeb90
MD
1175 * Using fork to set umask in the child process (not multi-thread safe).
1176 * We deal with the shm_open vs ftruncate race (happening when the
1177 * sessiond owns the shm and does not let everybody modify it, to ensure
1178 * safety against shm_unlink) by simply letting the mmap fail and
1179 * retrying after a few seconds.
1180 * For global shm, everybody has rw access to it until the sessiond
1181 * starts.
58d4b2a2 1182 */
7fc90dca 1183static
58d4b2a2 1184int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
7fc90dca 1185{
7fc90dca 1186 int wait_shm_fd, ret;
58d4b2a2 1187 pid_t pid;
44e073f5 1188
58d4b2a2 1189 /*
33bbeb90 1190 * Try to open read-only.
58d4b2a2 1191 */
33bbeb90 1192 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
58d4b2a2 1193 if (wait_shm_fd >= 0) {
7aa76730
MD
1194 int32_t tmp_read;
1195 ssize_t len;
1196 size_t bytes_read = 0;
1197
1198 /*
1199 * Try to read the fd. If unable to do so, try opening
1200 * it in write mode.
1201 */
1202 do {
1203 len = read(wait_shm_fd,
1204 &((char *) &tmp_read)[bytes_read],
1205 sizeof(tmp_read) - bytes_read);
1206 if (len > 0) {
1207 bytes_read += len;
1208 }
1209 } while ((len < 0 && errno == EINTR)
1210 || (len > 0 && bytes_read < sizeof(tmp_read)));
1211 if (bytes_read != sizeof(tmp_read)) {
1212 ret = close(wait_shm_fd);
1213 if (ret) {
1214 ERR("close wait_shm_fd");
1215 }
1216 goto open_write;
1217 }
58d4b2a2
MD
1218 goto end;
1219 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1220 /*
33bbeb90
MD
1221 * Real-only open did not work, and it's not because the
1222 * entry was not present. It's a failure that prohibits
1223 * using shm.
58d4b2a2 1224 */
7fc90dca 1225 ERR("Error opening shm %s", sock_info->wait_shm_path);
58d4b2a2 1226 goto end;
7fc90dca 1227 }
7aa76730
MD
1228
1229open_write:
7fc90dca 1230 /*
7aa76730
MD
1231 * If the open failed because the file did not exist, or because
1232 * the file was not truncated yet, try creating it ourself.
7fc90dca 1233 */
8c90a710 1234 URCU_TLS(lttng_ust_nest_count)++;
58d4b2a2 1235 pid = fork();
8c90a710 1236 URCU_TLS(lttng_ust_nest_count)--;
58d4b2a2
MD
1237 if (pid > 0) {
1238 int status;
1239
1240 /*
1241 * Parent: wait for child to return, in which case the
1242 * shared memory map will have been created.
1243 */
1244 pid = wait(&status);
b7d3cb32 1245 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
58d4b2a2
MD
1246 wait_shm_fd = -1;
1247 goto end;
7fc90dca 1248 }
58d4b2a2
MD
1249 /*
1250 * Try to open read-only again after creation.
1251 */
33bbeb90 1252 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
58d4b2a2
MD
1253 if (wait_shm_fd < 0) {
1254 /*
1255 * Real-only open did not work. It's a failure
1256 * that prohibits using shm.
1257 */
1258 ERR("Error opening shm %s", sock_info->wait_shm_path);
1259 goto end;
1260 }
1261 goto end;
1262 } else if (pid == 0) {
1263 int create_mode;
1264
1265 /* Child */
33bbeb90 1266 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
58d4b2a2 1267 if (sock_info->global)
33bbeb90 1268 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
58d4b2a2
MD
1269 /*
1270 * We're alone in a child process, so we can modify the
1271 * process-wide umask.
1272 */
33bbeb90 1273 umask(~create_mode);
58d4b2a2 1274 /*
33bbeb90
MD
1275 * Try creating shm (or get rw access).
1276 * We don't do an exclusive open, because we allow other
1277 * processes to create+ftruncate it concurrently.
58d4b2a2
MD
1278 */
1279 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1280 O_RDWR | O_CREAT, create_mode);
1281 if (wait_shm_fd >= 0) {
1282 ret = ftruncate(wait_shm_fd, mmap_size);
1283 if (ret) {
1284 PERROR("ftruncate");
b0c1425d 1285 _exit(EXIT_FAILURE);
58d4b2a2 1286 }
b0c1425d 1287 _exit(EXIT_SUCCESS);
58d4b2a2 1288 }
33bbeb90
MD
1289 /*
1290 * For local shm, we need to have rw access to accept
1291 * opening it: this means the local sessiond will be
1292 * able to wake us up. For global shm, we open it even
1293 * if rw access is not granted, because the root.root
1294 * sessiond will be able to override all rights and wake
1295 * us up.
1296 */
1297 if (!sock_info->global && errno != EACCES) {
58d4b2a2 1298 ERR("Error opening shm %s", sock_info->wait_shm_path);
5d3bc5ed 1299 _exit(EXIT_FAILURE);
58d4b2a2
MD
1300 }
1301 /*
33bbeb90
MD
1302 * The shm exists, but we cannot open it RW. Report
1303 * success.
58d4b2a2 1304 */
5d3bc5ed 1305 _exit(EXIT_SUCCESS);
58d4b2a2
MD
1306 } else {
1307 return -1;
7fc90dca 1308 }
58d4b2a2 1309end:
33bbeb90
MD
1310 if (wait_shm_fd >= 0 && !sock_info->global) {
1311 struct stat statbuf;
1312
1313 /*
1314 * Ensure that our user is the owner of the shm file for
1315 * local shm. If we do not own the file, it means our
1316 * sessiond will not have access to wake us up (there is
1317 * probably a rogue process trying to fake our
1318 * sessiond). Fallback to polling method in this case.
1319 */
1320 ret = fstat(wait_shm_fd, &statbuf);
1321 if (ret) {
1322 PERROR("fstat");
1323 goto error_close;
1324 }
1325 if (statbuf.st_uid != getuid())
1326 goto error_close;
1327 }
58d4b2a2 1328 return wait_shm_fd;
33bbeb90
MD
1329
1330error_close:
1331 ret = close(wait_shm_fd);
1332 if (ret) {
1333 PERROR("Error closing fd");
1334 }
1335 return -1;
58d4b2a2
MD
1336}
1337
1338static
1339char *get_map_shm(struct sock_info *sock_info)
1340{
172d6b68 1341 long page_size;
58d4b2a2
MD
1342 int wait_shm_fd, ret;
1343 char *wait_shm_mmap;
1344
172d6b68 1345 page_size = sysconf(_SC_PAGE_SIZE);
2657d1ba
MD
1346 if (page_size <= 0) {
1347 if (!page_size) {
1348 errno = EINVAL;
1349 }
1350 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
172d6b68
MD
1351 goto error;
1352 }
1353
6548fca4 1354 lttng_ust_lock_fd_tracker();
172d6b68 1355 wait_shm_fd = get_wait_shm(sock_info, page_size);
58d4b2a2 1356 if (wait_shm_fd < 0) {
6548fca4 1357 lttng_ust_unlock_fd_tracker();
58d4b2a2 1358 goto error;
44e073f5 1359 }
f5c453e9
JR
1360
1361 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1362 if (ret < 0) {
1363 ret = close(wait_shm_fd);
1364 if (!ret) {
1365 PERROR("Error closing fd");
1366 }
1367 lttng_ust_unlock_fd_tracker();
1368 goto error;
1369 }
1370
1371 wait_shm_fd = ret;
6548fca4
MD
1372 lttng_ust_unlock_fd_tracker();
1373
172d6b68 1374 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
7fc90dca 1375 MAP_SHARED, wait_shm_fd, 0);
6548fca4 1376
7fc90dca 1377 /* close shm fd immediately after taking the mmap reference */
6548fca4 1378 lttng_ust_lock_fd_tracker();
7fc90dca 1379 ret = close(wait_shm_fd);
6548fca4
MD
1380 if (!ret) {
1381 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1382 } else {
33bbeb90
MD
1383 PERROR("Error closing fd");
1384 }
6548fca4
MD
1385 lttng_ust_unlock_fd_tracker();
1386
33bbeb90
MD
1387 if (wait_shm_mmap == MAP_FAILED) {
1388 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1389 goto error;
7fc90dca
MD
1390 }
1391 return wait_shm_mmap;
1392
1393error:
1394 return NULL;
1395}
1396
1397static
1398void wait_for_sessiond(struct sock_info *sock_info)
1399{
060577e3 1400 /* Use ust_lock to check if we should quit. */
3327ac33 1401 if (ust_lock()) {
7fc90dca
MD
1402 goto quit;
1403 }
37ed587a
MD
1404 if (wait_poll_fallback) {
1405 goto error;
1406 }
7fc90dca
MD
1407 ust_unlock();
1408
060577e3
JR
1409 assert(sock_info->wait_shm_mmap);
1410
7fc90dca 1411 DBG("Waiting for %s apps sessiond", sock_info->name);
80e2814b 1412 /* Wait for futex wakeup */
ee7fcec8
MD
1413 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1414 goto end_wait;
1415
1416 while (futex_async((int32_t *) sock_info->wait_shm_mmap,
1417 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1418 switch (errno) {
1419 case EWOULDBLOCK:
1420 /* Value already changed. */
1421 goto end_wait;
1422 case EINTR:
1423 /* Retry if interrupted by signal. */
1424 break; /* Get out of switch. */
1425 case EFAULT:
1426 wait_poll_fallback = 1;
1427 DBG(
37ed587a
MD
1428"Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1429"do not support FUTEX_WAKE on read-only memory mappings correctly. "
1430"Please upgrade your kernel "
1431"(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1432"mainline). LTTng-UST will use polling mode fallback.");
ee7fcec8
MD
1433 if (ust_debug())
1434 PERROR("futex");
1435 goto end_wait;
80e2814b
MD
1436 }
1437 }
ee7fcec8 1438end_wait:
7fc90dca
MD
1439 return;
1440
1441quit:
1442 ust_unlock();
1443 return;
1444
1445error:
1446 ust_unlock();
7fc90dca 1447 return;
46050b1a
MD
1448}
1449
1ea11eab
MD
1450/*
1451 * This thread does not allocate any resource, except within
1452 * handle_message, within mutex protection. This mutex protects against
1453 * fork and exit.
98bf993f 1454 * The other moment it allocates resources is at socket connection, which
1ea11eab
MD
1455 * is also protected by the mutex.
1456 */
d9e99d10
MD
1457static
1458void *ust_listener_thread(void *arg)
1459{
1ea11eab 1460 struct sock_info *sock_info = arg;
f5c453e9 1461 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
ff517991 1462 long timeout;
d9e99d10 1463
c362addf 1464 lttng_ust_fixup_tls();
01f0e40c
RB
1465 /*
1466 * If available, add '-ust' to the end of this thread's
1467 * process name
1468 */
1469 ret = lttng_ust_setustprocname();
1470 if (ret) {
1471 ERR("Unable to set UST process name");
1472 }
1473
9eb62b9c
MD
1474 /* Restart trying to connect to the session daemon */
1475restart:
c0eedf81
MD
1476 if (prev_connect_failed) {
1477 /* Wait for sessiond availability with pipe */
1478 wait_for_sessiond(sock_info);
1479 if (has_waited) {
1480 has_waited = 0;
1481 /*
1482 * Sleep for 5 seconds before retrying after a
1483 * sequence of failure / wait / failure. This
1484 * deals with a killed or broken session daemon.
1485 */
1486 sleep(5);
eacc4aa4
MD
1487 } else {
1488 has_waited = 1;
c0eedf81 1489 }
c0eedf81
MD
1490 prev_connect_failed = 0;
1491 }
9eb62b9c 1492
101dace0
JR
1493 if (ust_lock()) {
1494 goto quit;
1495 }
1496
1ea11eab 1497 if (sock_info->socket != -1) {
6548fca4 1498 /* FD tracker is updated by ustcomm_close_unix_sock() */
e6973a89 1499 ret = ustcomm_close_unix_sock(sock_info->socket);
1ea11eab 1500 if (ret) {
32ce8569
MD
1501 ERR("Error closing %s ust cmd socket",
1502 sock_info->name);
1ea11eab
MD
1503 }
1504 sock_info->socket = -1;
1505 }
32ce8569 1506 if (sock_info->notify_socket != -1) {
6548fca4 1507 /* FD tracker is updated by ustcomm_close_unix_sock() */
32ce8569
MD
1508 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1509 if (ret) {
1510 ERR("Error closing %s ust notify socket",
1511 sock_info->name);
1512 }
1513 sock_info->notify_socket = -1;
1514 }
46050b1a 1515
6548fca4 1516
321f2351
MD
1517 /*
1518 * Register. We need to perform both connect and sending
1519 * registration message before doing the next connect otherwise
1520 * we may reach unix socket connect queue max limits and block
1521 * on the 2nd connect while the session daemon is awaiting the
1522 * first connect registration message.
1523 */
1524 /* Connect cmd socket */
6548fca4 1525 lttng_ust_lock_fd_tracker();
451d66b2
MD
1526 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1527 get_connect_sock_timeout());
321f2351 1528 if (ret < 0) {
6548fca4 1529 lttng_ust_unlock_fd_tracker();
321f2351
MD
1530 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1531 prev_connect_failed = 1;
5b14aab3 1532
e3426ddc 1533 /*
321f2351
MD
1534 * If we cannot find the sessiond daemon, don't delay
1535 * constructor execution.
e3426ddc 1536 */
eb0e6022 1537 ret = handle_register_failed(sock_info);
321f2351
MD
1538 assert(!ret);
1539 ust_unlock();
1540 goto restart;
27fe9f21 1541 }
f5c453e9
JR
1542 fd = ret;
1543 ret = lttng_ust_add_fd_to_tracker(fd);
1544 if (ret < 0) {
1545 ret = close(fd);
1546 if (ret) {
1547 PERROR("close on sock_info->socket");
1548 }
1549 ret = -1;
1550 lttng_ust_unlock_fd_tracker();
1551 ust_unlock();
1552 goto quit;
1553 }
1554
321f2351 1555 sock_info->socket = ret;
f5c453e9 1556 lttng_ust_unlock_fd_tracker();
27fe9f21 1557
6548fca4
MD
1558 ust_unlock();
1559 /*
1560 * Unlock/relock ust lock because connect is blocking (with
1561 * timeout). Don't delay constructors on the ust lock for too
1562 * long.
1563 */
3327ac33 1564 if (ust_lock()) {
5b14aab3
MD
1565 goto quit;
1566 }
1567
46050b1a
MD
1568 /*
1569 * Create only one root handle per listener thread for the whole
f59ed768
MD
1570 * process lifetime, so we ensure we get ID which is statically
1571 * assigned to the root handle.
46050b1a
MD
1572 */
1573 if (sock_info->root_handle == -1) {
1574 ret = lttng_abi_create_root_handle();
a51070bb 1575 if (ret < 0) {
46050b1a 1576 ERR("Error creating root handle");
46050b1a
MD
1577 goto quit;
1578 }
1579 sock_info->root_handle = ret;
9eb62b9c 1580 }
1ea11eab 1581
32ce8569 1582 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
9eb62b9c 1583 if (ret < 0) {
32ce8569
MD
1584 ERR("Error registering to %s ust cmd socket",
1585 sock_info->name);
c0eedf81 1586 prev_connect_failed = 1;
11ff9c7d
MD
1587 /*
1588 * If we cannot register to the sessiond daemon, don't
1589 * delay constructor execution.
1590 */
eb0e6022 1591 ret = handle_register_failed(sock_info);
11ff9c7d 1592 assert(!ret);
17dfb34b 1593 ust_unlock();
9eb62b9c
MD
1594 goto restart;
1595 }
321f2351
MD
1596
1597 ust_unlock();
6548fca4
MD
1598 /*
1599 * Unlock/relock ust lock because connect is blocking (with
1600 * timeout). Don't delay constructors on the ust lock for too
1601 * long.
1602 */
1603 if (ust_lock()) {
1604 goto quit;
1605 }
321f2351
MD
1606
1607 /* Connect notify socket */
6548fca4 1608 lttng_ust_lock_fd_tracker();
451d66b2
MD
1609 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1610 get_connect_sock_timeout());
321f2351 1611 if (ret < 0) {
6548fca4 1612 lttng_ust_unlock_fd_tracker();
321f2351
MD
1613 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1614 prev_connect_failed = 1;
1615
321f2351
MD
1616 /*
1617 * If we cannot find the sessiond daemon, don't delay
1618 * constructor execution.
1619 */
eb0e6022 1620 ret = handle_register_failed(sock_info);
321f2351
MD
1621 assert(!ret);
1622 ust_unlock();
1623 goto restart;
1624 }
f5c453e9
JR
1625
1626 fd = ret;
1627 ret = lttng_ust_add_fd_to_tracker(fd);
1628 if (ret < 0) {
1629 ret = close(fd);
1630 if (ret) {
1631 PERROR("close on sock_info->notify_socket");
1632 }
1633 ret = -1;
1634 lttng_ust_unlock_fd_tracker();
1635 ust_unlock();
1636 goto quit;
1637 }
1638
321f2351 1639 sock_info->notify_socket = ret;
f5c453e9 1640 lttng_ust_unlock_fd_tracker();
321f2351 1641
6548fca4
MD
1642 ust_unlock();
1643 /*
1644 * Unlock/relock ust lock because connect is blocking (with
1645 * timeout). Don't delay constructors on the ust lock for too
1646 * long.
1647 */
1648 if (ust_lock()) {
1649 goto quit;
1650 }
1651
321f2351
MD
1652 timeout = get_notify_sock_timeout();
1653 if (timeout >= 0) {
1654 /*
1655 * Give at least 10ms to sessiond to reply to
1656 * notifications.
1657 */
1658 if (timeout < 10)
1659 timeout = 10;
1660 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1661 timeout);
1662 if (ret < 0) {
1663 WARN("Error setting socket receive timeout");
1664 }
1665 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1666 timeout);
1667 if (ret < 0) {
1668 WARN("Error setting socket send timeout");
1669 }
1670 } else if (timeout < -1) {
1671 WARN("Unsupported timeout value %ld", timeout);
1672 }
1673
32ce8569
MD
1674 ret = register_to_sessiond(sock_info->notify_socket,
1675 USTCTL_SOCKET_NOTIFY);
1676 if (ret < 0) {
1677 ERR("Error registering to %s ust notify socket",
1678 sock_info->name);
1679 prev_connect_failed = 1;
1680 /*
1681 * If we cannot register to the sessiond daemon, don't
1682 * delay constructor execution.
1683 */
eb0e6022 1684 ret = handle_register_failed(sock_info);
32ce8569
MD
1685 assert(!ret);
1686 ust_unlock();
1687 goto restart;
1688 }
1689 sock = sock_info->socket;
1690
17dfb34b 1691 ust_unlock();
46050b1a 1692
d9e99d10
MD
1693 for (;;) {
1694 ssize_t len;
57773204 1695 struct ustcomm_ust_msg lum;
d9e99d10 1696
57773204 1697 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
d9e99d10
MD
1698 switch (len) {
1699 case 0: /* orderly shutdown */
7dd08bec 1700 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
3327ac33 1701 if (ust_lock()) {
d5e1fea6
MD
1702 goto quit;
1703 }
8236ba10
MD
1704 /*
1705 * Either sessiond has shutdown or refused us by closing the socket.
1706 * In either case, we don't want to delay construction execution,
1707 * and we need to wait before retry.
1708 */
1709 prev_connect_failed = 1;
1710 /*
1711 * If we cannot register to the sessiond daemon, don't
1712 * delay constructor execution.
1713 */
eb0e6022 1714 ret = handle_register_failed(sock_info);
8236ba10
MD
1715 assert(!ret);
1716 ust_unlock();
d9e99d10 1717 goto end;
e7723462 1718 case sizeof(lum):
74d81a6c 1719 print_cmd(lum.cmd, lum.handle);
11ff9c7d 1720 ret = handle_message(sock_info, sock, &lum);
7bc53e94 1721 if (ret) {
0dafcd63
MD
1722 ERR("Error handling message for %s socket",
1723 sock_info->name);
1724 /*
1725 * Close socket if protocol error is
1726 * detected.
1727 */
1728 goto end;
d9e99d10
MD
1729 }
1730 continue;
7bc53e94
MD
1731 default:
1732 if (len < 0) {
1733 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1734 } else {
1735 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1736 }
1737 if (len == -ECONNRESET) {
1738 DBG("%s remote end closed connection", sock_info->name);
d9e99d10
MD
1739 goto end;
1740 }
1741 goto end;
d9e99d10
MD
1742 }
1743
1744 }
1745end:
3327ac33 1746 if (ust_lock()) {
d5e1fea6
MD
1747 goto quit;
1748 }
f59ed768
MD
1749 /* Cleanup socket handles before trying to reconnect */
1750 lttng_ust_objd_table_owner_cleanup(sock_info);
1751 ust_unlock();
9eb62b9c 1752 goto restart; /* try to reconnect */
e33f3265 1753
1ea11eab 1754quit:
e33f3265 1755 ust_unlock();
3327ac33
MD
1756
1757 pthread_mutex_lock(&ust_exit_mutex);
1758 sock_info->thread_active = 0;
1759 pthread_mutex_unlock(&ust_exit_mutex);
d9e99d10
MD
1760 return NULL;
1761}
1762
2594a5b4
MD
1763/*
1764 * Weak symbol to call when the ust malloc wrapper is not loaded.
1765 */
1766__attribute__((weak))
1767void lttng_ust_malloc_wrapper_init(void)
1768{
1769}
1770
2691221a
MD
1771/*
1772 * sessiond monitoring thread: monitor presence of global and per-user
1773 * sessiond by polling the application common named pipe.
1774 */
edaa1431 1775void __attribute__((constructor)) lttng_ust_init(void)
2691221a 1776{
11ff9c7d 1777 struct timespec constructor_timeout;
ae6a58bf 1778 sigset_t sig_all_blocked, orig_parent_mask;
1879f67f 1779 pthread_attr_t thread_attr;
cf12a773 1780 int timeout_mode;
2691221a 1781 int ret;
b2292d85 1782 void *handle;
2691221a 1783
edaa1431
MD
1784 if (uatomic_xchg(&initialized, 1) == 1)
1785 return;
1786
eddd8d5d
MD
1787 /*
1788 * Fixup interdependency between TLS fixup mutex (which happens
1789 * to be the dynamic linker mutex) and ust_lock, taken within
1790 * the ust lock.
1791 */
c362addf 1792 lttng_ust_fixup_tls();
eddd8d5d 1793
07b57e5e
MD
1794 lttng_ust_loaded = 1;
1795
b2292d85
FD
1796 /*
1797 * We need to ensure that the liblttng-ust library is not unloaded to avoid
1798 * the unloading of code used by the ust_listener_threads as we can not
1799 * reliably know when they exited. To do that, manually load
1800 * liblttng-ust.so to increment the dynamic loader's internal refcount for
1801 * this library so it never becomes zero, thus never gets unloaded from the
1802 * address space of the process. Since we are already running in the
1803 * constructor of the LTTNG_UST_LIB_SO_NAME library, calling dlopen will
1804 * simply increment the refcount and no additionnal work is needed by the
1805 * dynamic loader as the shared library is already loaded in the address
1806 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
1807 * unloading of the UST library if its refcount becomes zero (which should
1808 * never happen). Do the return value check but discard the handle at the
1809 * end of the function as it's not needed.
1810 */
1811 handle = dlopen(LTTNG_UST_LIB_SO_NAME, RTLD_LAZY | RTLD_NODELETE);
1812 if (!handle) {
1813 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SO_NAME);
1814 }
1815
edaa1431
MD
1816 /*
1817 * We want precise control over the order in which we construct
1818 * our sub-libraries vs starting to receive commands from
1819 * sessiond (otherwise leading to errors when trying to create
1820 * sessiond before the init functions are completed).
1821 */
2691221a 1822 init_usterr();
6f626d28 1823 lttng_ust_getenv_init(); /* Needs init_usterr() to be completed. */
edaa1431 1824 init_tracepoint();
6548fca4 1825 lttng_ust_init_fd_tracker();
f9364363 1826 lttng_ust_clock_init();
5e1b7b8b 1827 lttng_ust_getcpu_init();
cf73e0fe 1828 lttng_ust_statedump_init();
7dd08bec
MD
1829 lttng_ring_buffer_metadata_client_init();
1830 lttng_ring_buffer_client_overwrite_init();
34a91bdb 1831 lttng_ring_buffer_client_overwrite_rt_init();
7dd08bec 1832 lttng_ring_buffer_client_discard_init();
34a91bdb 1833 lttng_ring_buffer_client_discard_rt_init();
d58d1454 1834 lttng_perf_counter_init();
2594a5b4
MD
1835 /*
1836 * Invoke ust malloc wrapper init before starting other threads.
1837 */
1838 lttng_ust_malloc_wrapper_init();
2691221a 1839
ff517991 1840 timeout_mode = get_constructor_timeout(&constructor_timeout);
11ff9c7d 1841
b2c5f61a 1842 get_allow_blocking();
6f97f9c2 1843
95259bd0 1844 ret = sem_init(&constructor_wait, 0, 0);
8aadb54a
MD
1845 if (ret) {
1846 PERROR("sem_init");
1847 }
11ff9c7d 1848
060577e3
JR
1849 ret = setup_global_apps();
1850 if (ret) {
1851 assert(global_apps.allowed == 0);
1852 DBG("global apps setup returned %d", ret);
1853 }
1854
8d20bf54 1855 ret = setup_local_apps();
2691221a 1856 if (ret) {
060577e3 1857 assert(local_apps.allowed == 0);
9ec6895c 1858 DBG("local apps setup returned %d", ret);
2691221a 1859 }
ae6a58bf
WP
1860
1861 /* A new thread created by pthread_create inherits the signal mask
1862 * from the parent. To avoid any signal being received by the
1863 * listener thread, we block all signals temporarily in the parent,
1864 * while we create the listener thread.
1865 */
1866 sigfillset(&sig_all_blocked);
1867 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1868 if (ret) {
d94d802c 1869 ERR("pthread_sigmask: %s", strerror(ret));
ae6a58bf
WP
1870 }
1871
1879f67f
MG
1872 ret = pthread_attr_init(&thread_attr);
1873 if (ret) {
1874 ERR("pthread_attr_init: %s", strerror(ret));
1875 }
1876 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1877 if (ret) {
1878 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1879 }
1880
060577e3
JR
1881 if (global_apps.allowed) {
1882 pthread_mutex_lock(&ust_exit_mutex);
1883 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1884 ust_listener_thread, &global_apps);
1885 if (ret) {
1886 ERR("pthread_create global: %s", strerror(ret));
1887 }
1888 global_apps.thread_active = 1;
1889 pthread_mutex_unlock(&ust_exit_mutex);
1890 } else {
1891 handle_register_done(&global_apps);
d94d802c 1892 }
e33f3265 1893
8d20bf54 1894 if (local_apps.allowed) {
c0bbbd5a 1895 pthread_mutex_lock(&ust_exit_mutex);
1879f67f 1896 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
dde70ea0 1897 ust_listener_thread, &local_apps);
d94d802c
MD
1898 if (ret) {
1899 ERR("pthread_create local: %s", strerror(ret));
1900 }
e33f3265 1901 local_apps.thread_active = 1;
c0bbbd5a 1902 pthread_mutex_unlock(&ust_exit_mutex);
8d20bf54
MD
1903 } else {
1904 handle_register_done(&local_apps);
1905 }
1879f67f
MG
1906 ret = pthread_attr_destroy(&thread_attr);
1907 if (ret) {
1908 ERR("pthread_attr_destroy: %s", strerror(ret));
1909 }
8d20bf54 1910
ae6a58bf
WP
1911 /* Restore original signal mask in parent */
1912 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1913 if (ret) {
d94d802c 1914 ERR("pthread_sigmask: %s", strerror(ret));
ae6a58bf
WP
1915 }
1916
cf12a773
MD
1917 switch (timeout_mode) {
1918 case 1: /* timeout wait */
95259bd0
MD
1919 do {
1920 ret = sem_timedwait(&constructor_wait,
1921 &constructor_timeout);
1922 } while (ret < 0 && errno == EINTR);
8aadb54a
MD
1923 if (ret < 0) {
1924 switch (errno) {
1925 case ETIMEDOUT:
1926 ERR("Timed out waiting for lttng-sessiond");
1927 break;
1928 case EINVAL:
1929 PERROR("sem_timedwait");
1930 break;
1931 default:
1932 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1933 strerror(errno));
1934 }
cf12a773
MD
1935 }
1936 break;
7b766b16 1937 case -1:/* wait forever */
95259bd0
MD
1938 do {
1939 ret = sem_wait(&constructor_wait);
1940 } while (ret < 0 && errno == EINTR);
8aadb54a
MD
1941 if (ret < 0) {
1942 switch (errno) {
1943 case EINVAL:
1944 PERROR("sem_wait");
1945 break;
1946 default:
1947 ERR("Unexpected error \"%s\" returned by sem_wait",
1948 strerror(errno));
1949 }
1950 }
cf12a773 1951 break;
7b766b16 1952 case 0: /* no timeout */
cf12a773 1953 break;
11ff9c7d 1954 }
2691221a
MD
1955}
1956
17dfb34b
MD
1957static
1958void lttng_ust_cleanup(int exiting)
1959{
efe0de09 1960 cleanup_sock_info(&global_apps, exiting);
932cfadb 1961 cleanup_sock_info(&local_apps, exiting);
74f98bc9 1962 local_apps.allowed = 0;
060577e3 1963 global_apps.allowed = 0;
efe0de09
MD
1964 /*
1965 * The teardown in this function all affect data structures
1966 * accessed under the UST lock by the listener thread. This
1967 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1968 * that none of these threads are accessing this data at this
1969 * point.
1970 */
17dfb34b 1971 lttng_ust_abi_exit();
003fedf4 1972 lttng_ust_events_exit();
d58d1454 1973 lttng_perf_counter_exit();
34a91bdb 1974 lttng_ring_buffer_client_discard_rt_exit();
7dd08bec 1975 lttng_ring_buffer_client_discard_exit();
34a91bdb 1976 lttng_ring_buffer_client_overwrite_rt_exit();
7dd08bec
MD
1977 lttng_ring_buffer_client_overwrite_exit();
1978 lttng_ring_buffer_metadata_client_exit();
cf73e0fe 1979 lttng_ust_statedump_destroy();
17dfb34b
MD
1980 exit_tracepoint();
1981 if (!exiting) {
1982 /* Reinitialize values for fork */
eb0e6022 1983 sem_count = sem_count_initial_value;
17dfb34b
MD
1984 lttng_ust_comm_should_quit = 0;
1985 initialized = 0;
1986 }
1987}
1988
edaa1431 1989void __attribute__((destructor)) lttng_ust_exit(void)
2691221a
MD
1990{
1991 int ret;
1992
9eb62b9c
MD
1993 /*
1994 * Using pthread_cancel here because:
1995 * A) we don't want to hang application teardown.
1996 * B) the thread is not allocating any resource.
1997 */
1ea11eab
MD
1998
1999 /*
2000 * Require the communication thread to quit. Synchronize with
2001 * mutexes to ensure it is not in a mutex critical section when
2002 * pthread_cancel is later called.
2003 */
3327ac33 2004 ust_lock_nocheck();
1ea11eab 2005 lttng_ust_comm_should_quit = 1;
3327ac33 2006 ust_unlock();
1ea11eab 2007
3327ac33 2008 pthread_mutex_lock(&ust_exit_mutex);
f5f94532 2009 /* cancel threads */
e33f3265
MD
2010 if (global_apps.thread_active) {
2011 ret = pthread_cancel(global_apps.ust_listener);
2012 if (ret) {
2013 ERR("Error cancelling global ust listener thread: %s",
2014 strerror(ret));
2015 } else {
2016 global_apps.thread_active = 0;
2017 }
2691221a 2018 }
e33f3265 2019 if (local_apps.thread_active) {
8d20bf54
MD
2020 ret = pthread_cancel(local_apps.ust_listener);
2021 if (ret) {
d94d802c
MD
2022 ERR("Error cancelling local ust listener thread: %s",
2023 strerror(ret));
e33f3265
MD
2024 } else {
2025 local_apps.thread_active = 0;
8d20bf54 2026 }
8d20bf54 2027 }
3327ac33 2028 pthread_mutex_unlock(&ust_exit_mutex);
e33f3265 2029
efe0de09
MD
2030 /*
2031 * Do NOT join threads: use of sys_futex makes it impossible to
2032 * join the threads without using async-cancel, but async-cancel
2033 * is delivered by a signal, which could hit the target thread
2034 * anywhere in its code path, including while the ust_lock() is
2035 * held, causing a deadlock for the other thread. Let the OS
2036 * cleanup the threads if there are stalled in a syscall.
2037 */
17dfb34b 2038 lttng_ust_cleanup(1);
2691221a 2039}
e822f505 2040
735bef47
MJ
2041static
2042void ust_context_ns_reset(void)
2043{
2044 lttng_context_pid_ns_reset();
2045 lttng_context_cgroup_ns_reset();
2046 lttng_context_ipc_ns_reset();
2047 lttng_context_mnt_ns_reset();
2048 lttng_context_net_ns_reset();
2049 lttng_context_user_ns_reset();
2050 lttng_context_uts_ns_reset();
2051}
2052
e822f505
MD
2053/*
2054 * We exclude the worker threads across fork and clone (except
2055 * CLONE_VM), because these system calls only keep the forking thread
2056 * running in the child. Therefore, we don't want to call fork or clone
2057 * in the middle of an tracepoint or ust tracing state modification.
2058 * Holding this mutex protects these structures across fork and clone.
2059 */
b728d87e 2060void ust_before_fork(sigset_t *save_sigset)
e822f505
MD
2061{
2062 /*
2063 * Disable signals. This is to avoid that the child intervenes
2064 * before it is properly setup for tracing. It is safer to
2065 * disable all signals, because then we know we are not breaking
2066 * anything by restoring the original mask.
2067 */
2068 sigset_t all_sigs;
2069 int ret;
2070
c362addf
MD
2071 /* Fixup lttng-ust TLS. */
2072 lttng_ust_fixup_tls();
2073
8c90a710 2074 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2075 return;
e822f505
MD
2076 /* Disable signals */
2077 sigfillset(&all_sigs);
b728d87e 2078 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
e822f505
MD
2079 if (ret == -1) {
2080 PERROR("sigprocmask");
2081 }
458d678c
PW
2082
2083 pthread_mutex_lock(&ust_fork_mutex);
2084
3327ac33 2085 ust_lock_nocheck();
d6ddec3f 2086 urcu_bp_before_fork();
c1be081a 2087 lttng_ust_lock_fd_tracker();
20142124 2088 lttng_perf_lock();
e822f505
MD
2089}
2090
b728d87e 2091static void ust_after_fork_common(sigset_t *restore_sigset)
e822f505
MD
2092{
2093 int ret;
2094
17dfb34b 2095 DBG("process %d", getpid());
20142124 2096 lttng_perf_unlock();
c1be081a 2097 lttng_ust_unlock_fd_tracker();
17dfb34b 2098 ust_unlock();
458d678c
PW
2099
2100 pthread_mutex_unlock(&ust_fork_mutex);
2101
e822f505 2102 /* Restore signals */
23c8854a 2103 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
e822f505
MD
2104 if (ret == -1) {
2105 PERROR("sigprocmask");
2106 }
2107}
2108
b728d87e 2109void ust_after_fork_parent(sigset_t *restore_sigset)
e822f505 2110{
8c90a710 2111 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2112 return;
17dfb34b 2113 DBG("process %d", getpid());
d6ddec3f 2114 urcu_bp_after_fork_parent();
e822f505 2115 /* Release mutexes and reenable signals */
b728d87e 2116 ust_after_fork_common(restore_sigset);
e822f505
MD
2117}
2118
17dfb34b
MD
2119/*
2120 * After fork, in the child, we need to cleanup all the leftover state,
2121 * except the worker thread which already magically disappeared thanks
2122 * to the weird Linux fork semantics. After tyding up, we call
2123 * lttng_ust_init() again to start over as a new PID.
2124 *
2125 * This is meant for forks() that have tracing in the child between the
2126 * fork and following exec call (if there is any).
2127 */
b728d87e 2128void ust_after_fork_child(sigset_t *restore_sigset)
e822f505 2129{
8c90a710 2130 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2131 return;
06b16a0b 2132 lttng_context_vpid_reset();
8478887d 2133 lttng_context_vtid_reset();
46228a6f 2134 lttng_context_procname_reset();
735bef47 2135 ust_context_ns_reset();
17dfb34b 2136 DBG("process %d", getpid());
e822f505 2137 /* Release urcu mutexes */
d6ddec3f 2138 urcu_bp_after_fork_child();
17dfb34b 2139 lttng_ust_cleanup(0);
e822f505 2140 /* Release mutexes and reenable signals */
b728d87e 2141 ust_after_fork_common(restore_sigset);
318dfea9 2142 lttng_ust_init();
e822f505 2143}
95c25348 2144
735bef47
MJ
2145void ust_after_setns(void)
2146{
2147 ust_context_ns_reset();
2148}
2149
2150void ust_after_unshare(void)
2151{
2152 ust_context_ns_reset();
2153}
2154
246be17e 2155void lttng_ust_sockinfo_session_enabled(void *owner)
95c25348
PW
2156{
2157 struct sock_info *sock_info = owner;
37dddb65 2158 sock_info->statedump_pending = 1;
95c25348 2159}
This page took 0.153229 seconds and 4 git commands to generate.