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