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