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