Fix: remove unused align.h header
[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 {
9369ec32
MD
941 int close_ret;
942
74d81a6c
MD
943 /* Receive shm_fd, wakeup_fd */
944 ret = ustcomm_recv_stream_from_sessiond(sock,
694f63ca 945 NULL,
74d81a6c
MD
946 &args.stream.shm_fd,
947 &args.stream.wakeup_fd);
948 if (ret) {
0dafcd63 949 goto error;
74d81a6c 950 }
d292c6e0 951
74d81a6c
MD
952 if (ops->cmd)
953 ret = ops->cmd(lum->handle, lum->cmd,
954 (unsigned long) &lum->u,
955 &args, sock_info);
956 else
957 ret = -ENOSYS;
9369ec32
MD
958 if (args.stream.shm_fd >= 0) {
959 lttng_ust_lock_fd_tracker();
960 close_ret = close(args.stream.shm_fd);
961 lttng_ust_unlock_fd_tracker();
962 args.stream.shm_fd = -1;
963 if (close_ret)
964 PERROR("close");
965 }
966 if (args.stream.wakeup_fd >= 0) {
967 lttng_ust_lock_fd_tracker();
968 close_ret = close(args.stream.wakeup_fd);
969 lttng_ust_unlock_fd_tracker();
970 args.stream.wakeup_fd = -1;
971 if (close_ret)
972 PERROR("close");
973 }
74d81a6c
MD
974 break;
975 }
8e696cfa
MD
976 case LTTNG_UST_CONTEXT:
977 switch (lum->u.context.ctx) {
978 case LTTNG_UST_CONTEXT_APP_CONTEXT:
979 {
980 char *p;
981 size_t ctxlen, recvlen;
982
983 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
984 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
985 if (ctxlen >= LTTNG_UST_SYM_NAME_LEN) {
986 ERR("Application context string length size is too large: %zu bytes",
987 ctxlen);
988 ret = -EINVAL;
989 goto error;
990 }
991 strcpy(ctxstr, "$app.");
992 p = &ctxstr[strlen("$app.")];
993 recvlen = ctxlen - strlen("$app.");
994 len = ustcomm_recv_unix_sock(sock, p, recvlen);
995 switch (len) {
996 case 0: /* orderly shutdown */
997 ret = 0;
998 goto error;
999 default:
1000 if (len == recvlen) {
1001 DBG("app context data received");
1002 break;
1003 } else if (len < 0) {
1004 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1005 if (len == -ECONNRESET) {
1006 ERR("%s remote end closed connection", sock_info->name);
1007 ret = len;
1008 goto error;
1009 }
1010 ret = len;
1011 goto error;
1012 } else {
1013 DBG("incorrect app context data message size: %zd", len);
1014 ret = -EINVAL;
1015 goto error;
1016 }
1017 }
1018 /* Put : between provider and ctxname. */
1019 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
1020 args.app_context.ctxname = ctxstr;
1021 break;
1022 }
1023 default:
1024 break;
1025 }
1026 if (ops->cmd) {
1027 ret = ops->cmd(lum->handle, lum->cmd,
1028 (unsigned long) &lum->u,
1029 &args, sock_info);
1030 } else {
1031 ret = -ENOSYS;
1032 }
1033 break;
d9e99d10 1034 default:
46050b1a
MD
1035 if (ops->cmd)
1036 ret = ops->cmd(lum->handle, lum->cmd,
ef9ff354 1037 (unsigned long) &lum->u,
f59ed768 1038 &args, sock_info);
46050b1a
MD
1039 else
1040 ret = -ENOSYS;
1041 break;
d9e99d10 1042 }
46050b1a 1043
46050b1a
MD
1044 lur.handle = lum->handle;
1045 lur.cmd = lum->cmd;
1046 lur.ret_val = ret;
1047 if (ret >= 0) {
7bc53e94 1048 lur.ret_code = LTTNG_UST_OK;
46050b1a 1049 } else {
7bc53e94
MD
1050 /*
1051 * Use -LTTNG_UST_ERR as wildcard for UST internal
1052 * error that are not caused by the transport, except if
1053 * we already have a more precise error message to
1054 * report.
1055 */
64b2564e
DG
1056 if (ret > -LTTNG_UST_ERR) {
1057 /* Translate code to UST error. */
1058 switch (ret) {
1059 case -EEXIST:
1060 lur.ret_code = -LTTNG_UST_ERR_EXIST;
1061 break;
1062 case -EINVAL:
1063 lur.ret_code = -LTTNG_UST_ERR_INVAL;
1064 break;
1065 case -ENOENT:
1066 lur.ret_code = -LTTNG_UST_ERR_NOENT;
1067 break;
1068 case -EPERM:
1069 lur.ret_code = -LTTNG_UST_ERR_PERM;
1070 break;
1071 case -ENOSYS:
1072 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
1073 break;
1074 default:
1075 lur.ret_code = -LTTNG_UST_ERR;
1076 break;
1077 }
1078 } else {
7bc53e94 1079 lur.ret_code = ret;
64b2564e 1080 }
46050b1a 1081 }
e6ea14c5
MD
1082 if (ret >= 0) {
1083 switch (lum->cmd) {
e6ea14c5
MD
1084 case LTTNG_UST_TRACER_VERSION:
1085 lur.u.version = lum->u.version;
1086 break;
1087 case LTTNG_UST_TRACEPOINT_LIST_GET:
1088 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1089 break;
1090 }
381c0f1e 1091 }
74d81a6c 1092 DBG("Return value: %d", lur.ret_val);
4c62d8d1
MD
1093
1094 ust_unlock();
1095
1096 /*
1097 * Performed delayed statedump operations outside of the UST
1098 * lock. We need to take the dynamic loader lock before we take
1099 * the UST lock internally within handle_pending_statedump().
1100 */
1101 handle_pending_statedump(sock_info);
1102
1103 if (ust_lock()) {
1104 ret = -LTTNG_UST_ERR_EXITING;
1105 goto error;
1106 }
1107
46050b1a 1108 ret = send_reply(sock, &lur);
193183fb 1109 if (ret < 0) {
7bc53e94 1110 DBG("error sending reply");
193183fb
MD
1111 goto error;
1112 }
46050b1a 1113
40003310
MD
1114 /*
1115 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1116 * after the reply.
1117 */
7bc53e94 1118 if (lur.ret_code == LTTNG_UST_OK) {
40003310
MD
1119 switch (lum->cmd) {
1120 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
1121 len = ustcomm_send_unix_sock(sock,
1122 &args.field_list.entry,
1123 sizeof(args.field_list.entry));
7bc53e94
MD
1124 if (len < 0) {
1125 ret = len;
1126 goto error;
1127 }
40003310 1128 if (len != sizeof(args.field_list.entry)) {
7bc53e94 1129 ret = -EINVAL;
40003310
MD
1130 goto error;
1131 }
1132 }
1133 }
ef9ff354 1134
381c0f1e 1135error:
17dfb34b 1136 ust_unlock();
d9e99d10 1137
37dddb65 1138 return ret;
246be17e
PW
1139}
1140
46050b1a 1141static
efe0de09 1142void cleanup_sock_info(struct sock_info *sock_info, int exiting)
46050b1a
MD
1143{
1144 int ret;
1145
5b14aab3
MD
1146 if (sock_info->root_handle != -1) {
1147 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1148 if (ret) {
1149 ERR("Error unref root handle");
1150 }
1151 sock_info->root_handle = -1;
1152 }
e85887ff
GAPG
1153 sock_info->registration_done = 0;
1154 sock_info->initial_statedump_done = 0;
5b14aab3
MD
1155
1156 /*
1157 * wait_shm_mmap, socket and notify socket are used by listener
1158 * threads outside of the ust lock, so we cannot tear them down
1159 * ourselves, because we cannot join on these threads. Leave
1160 * responsibility of cleaning up these resources to the OS
1161 * process exit.
1162 */
1163 if (exiting)
1164 return;
1165
46050b1a 1166 if (sock_info->socket != -1) {
e6973a89 1167 ret = ustcomm_close_unix_sock(sock_info->socket);
46050b1a 1168 if (ret) {
32ce8569 1169 ERR("Error closing ust cmd socket");
46050b1a
MD
1170 }
1171 sock_info->socket = -1;
1172 }
32ce8569
MD
1173 if (sock_info->notify_socket != -1) {
1174 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1175 if (ret) {
1176 ERR("Error closing ust notify socket");
1177 }
1178 sock_info->notify_socket = -1;
1179 }
5b14aab3 1180 if (sock_info->wait_shm_mmap) {
172d6b68
MD
1181 long page_size;
1182
1183 page_size = sysconf(_SC_PAGE_SIZE);
2657d1ba
MD
1184 if (page_size <= 0) {
1185 if (!page_size) {
1186 errno = EINVAL;
1187 }
1188 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1189 } else {
172d6b68
MD
1190 ret = munmap(sock_info->wait_shm_mmap, page_size);
1191 if (ret) {
1192 ERR("Error unmapping wait shm");
1193 }
7fc90dca
MD
1194 }
1195 sock_info->wait_shm_mmap = NULL;
1196 }
1197}
1198
58d4b2a2 1199/*
33bbeb90
MD
1200 * Using fork to set umask in the child process (not multi-thread safe).
1201 * We deal with the shm_open vs ftruncate race (happening when the
1202 * sessiond owns the shm and does not let everybody modify it, to ensure
1203 * safety against shm_unlink) by simply letting the mmap fail and
1204 * retrying after a few seconds.
1205 * For global shm, everybody has rw access to it until the sessiond
1206 * starts.
58d4b2a2 1207 */
7fc90dca 1208static
58d4b2a2 1209int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
7fc90dca 1210{
7fc90dca 1211 int wait_shm_fd, ret;
58d4b2a2 1212 pid_t pid;
44e073f5 1213
58d4b2a2 1214 /*
33bbeb90 1215 * Try to open read-only.
58d4b2a2 1216 */
33bbeb90 1217 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
58d4b2a2 1218 if (wait_shm_fd >= 0) {
7aa76730
MD
1219 int32_t tmp_read;
1220 ssize_t len;
1221 size_t bytes_read = 0;
1222
1223 /*
1224 * Try to read the fd. If unable to do so, try opening
1225 * it in write mode.
1226 */
1227 do {
1228 len = read(wait_shm_fd,
1229 &((char *) &tmp_read)[bytes_read],
1230 sizeof(tmp_read) - bytes_read);
1231 if (len > 0) {
1232 bytes_read += len;
1233 }
1234 } while ((len < 0 && errno == EINTR)
1235 || (len > 0 && bytes_read < sizeof(tmp_read)));
1236 if (bytes_read != sizeof(tmp_read)) {
1237 ret = close(wait_shm_fd);
1238 if (ret) {
1239 ERR("close wait_shm_fd");
1240 }
1241 goto open_write;
1242 }
58d4b2a2
MD
1243 goto end;
1244 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1245 /*
33bbeb90
MD
1246 * Real-only open did not work, and it's not because the
1247 * entry was not present. It's a failure that prohibits
1248 * using shm.
58d4b2a2 1249 */
7fc90dca 1250 ERR("Error opening shm %s", sock_info->wait_shm_path);
58d4b2a2 1251 goto end;
7fc90dca 1252 }
7aa76730
MD
1253
1254open_write:
7fc90dca 1255 /*
7aa76730
MD
1256 * If the open failed because the file did not exist, or because
1257 * the file was not truncated yet, try creating it ourself.
7fc90dca 1258 */
8c90a710 1259 URCU_TLS(lttng_ust_nest_count)++;
58d4b2a2 1260 pid = fork();
8c90a710 1261 URCU_TLS(lttng_ust_nest_count)--;
58d4b2a2
MD
1262 if (pid > 0) {
1263 int status;
1264
1265 /*
1266 * Parent: wait for child to return, in which case the
1267 * shared memory map will have been created.
1268 */
1269 pid = wait(&status);
b7d3cb32 1270 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
58d4b2a2
MD
1271 wait_shm_fd = -1;
1272 goto end;
7fc90dca 1273 }
58d4b2a2
MD
1274 /*
1275 * Try to open read-only again after creation.
1276 */
33bbeb90 1277 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
58d4b2a2
MD
1278 if (wait_shm_fd < 0) {
1279 /*
1280 * Real-only open did not work. It's a failure
1281 * that prohibits using shm.
1282 */
1283 ERR("Error opening shm %s", sock_info->wait_shm_path);
1284 goto end;
1285 }
1286 goto end;
1287 } else if (pid == 0) {
1288 int create_mode;
1289
1290 /* Child */
33bbeb90 1291 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
58d4b2a2 1292 if (sock_info->global)
33bbeb90 1293 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
58d4b2a2
MD
1294 /*
1295 * We're alone in a child process, so we can modify the
1296 * process-wide umask.
1297 */
33bbeb90 1298 umask(~create_mode);
58d4b2a2 1299 /*
33bbeb90
MD
1300 * Try creating shm (or get rw access).
1301 * We don't do an exclusive open, because we allow other
1302 * processes to create+ftruncate it concurrently.
58d4b2a2
MD
1303 */
1304 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1305 O_RDWR | O_CREAT, create_mode);
1306 if (wait_shm_fd >= 0) {
1307 ret = ftruncate(wait_shm_fd, mmap_size);
1308 if (ret) {
1309 PERROR("ftruncate");
b0c1425d 1310 _exit(EXIT_FAILURE);
58d4b2a2 1311 }
b0c1425d 1312 _exit(EXIT_SUCCESS);
58d4b2a2 1313 }
33bbeb90
MD
1314 /*
1315 * For local shm, we need to have rw access to accept
1316 * opening it: this means the local sessiond will be
1317 * able to wake us up. For global shm, we open it even
1318 * if rw access is not granted, because the root.root
1319 * sessiond will be able to override all rights and wake
1320 * us up.
1321 */
1322 if (!sock_info->global && errno != EACCES) {
58d4b2a2 1323 ERR("Error opening shm %s", sock_info->wait_shm_path);
5d3bc5ed 1324 _exit(EXIT_FAILURE);
58d4b2a2
MD
1325 }
1326 /*
33bbeb90
MD
1327 * The shm exists, but we cannot open it RW. Report
1328 * success.
58d4b2a2 1329 */
5d3bc5ed 1330 _exit(EXIT_SUCCESS);
58d4b2a2
MD
1331 } else {
1332 return -1;
7fc90dca 1333 }
58d4b2a2 1334end:
33bbeb90
MD
1335 if (wait_shm_fd >= 0 && !sock_info->global) {
1336 struct stat statbuf;
1337
1338 /*
1339 * Ensure that our user is the owner of the shm file for
1340 * local shm. If we do not own the file, it means our
1341 * sessiond will not have access to wake us up (there is
1342 * probably a rogue process trying to fake our
1343 * sessiond). Fallback to polling method in this case.
1344 */
1345 ret = fstat(wait_shm_fd, &statbuf);
1346 if (ret) {
1347 PERROR("fstat");
1348 goto error_close;
1349 }
1350 if (statbuf.st_uid != getuid())
1351 goto error_close;
1352 }
58d4b2a2 1353 return wait_shm_fd;
33bbeb90
MD
1354
1355error_close:
1356 ret = close(wait_shm_fd);
1357 if (ret) {
1358 PERROR("Error closing fd");
1359 }
1360 return -1;
58d4b2a2
MD
1361}
1362
1363static
1364char *get_map_shm(struct sock_info *sock_info)
1365{
172d6b68 1366 long page_size;
58d4b2a2
MD
1367 int wait_shm_fd, ret;
1368 char *wait_shm_mmap;
1369
172d6b68 1370 page_size = sysconf(_SC_PAGE_SIZE);
2657d1ba
MD
1371 if (page_size <= 0) {
1372 if (!page_size) {
1373 errno = EINVAL;
1374 }
1375 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
172d6b68
MD
1376 goto error;
1377 }
1378
6548fca4 1379 lttng_ust_lock_fd_tracker();
172d6b68 1380 wait_shm_fd = get_wait_shm(sock_info, page_size);
58d4b2a2 1381 if (wait_shm_fd < 0) {
6548fca4 1382 lttng_ust_unlock_fd_tracker();
58d4b2a2 1383 goto error;
44e073f5 1384 }
f5c453e9
JR
1385
1386 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1387 if (ret < 0) {
1388 ret = close(wait_shm_fd);
1389 if (!ret) {
1390 PERROR("Error closing fd");
1391 }
1392 lttng_ust_unlock_fd_tracker();
1393 goto error;
1394 }
1395
1396 wait_shm_fd = ret;
6548fca4
MD
1397 lttng_ust_unlock_fd_tracker();
1398
172d6b68 1399 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
7fc90dca 1400 MAP_SHARED, wait_shm_fd, 0);
6548fca4 1401
7fc90dca 1402 /* close shm fd immediately after taking the mmap reference */
6548fca4 1403 lttng_ust_lock_fd_tracker();
7fc90dca 1404 ret = close(wait_shm_fd);
6548fca4
MD
1405 if (!ret) {
1406 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1407 } else {
33bbeb90
MD
1408 PERROR("Error closing fd");
1409 }
6548fca4
MD
1410 lttng_ust_unlock_fd_tracker();
1411
33bbeb90
MD
1412 if (wait_shm_mmap == MAP_FAILED) {
1413 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1414 goto error;
7fc90dca
MD
1415 }
1416 return wait_shm_mmap;
1417
1418error:
1419 return NULL;
1420}
1421
1422static
1423void wait_for_sessiond(struct sock_info *sock_info)
1424{
9d2dfb47 1425 /* Use ust_lock to check if we should quit. */
3327ac33 1426 if (ust_lock()) {
7fc90dca
MD
1427 goto quit;
1428 }
37ed587a
MD
1429 if (wait_poll_fallback) {
1430 goto error;
1431 }
7fc90dca
MD
1432 ust_unlock();
1433
9d2dfb47
JR
1434 assert(sock_info->wait_shm_mmap);
1435
7fc90dca 1436 DBG("Waiting for %s apps sessiond", sock_info->name);
80e2814b 1437 /* Wait for futex wakeup */
ee7fcec8
MD
1438 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1439 goto end_wait;
1440
1441 while (futex_async((int32_t *) sock_info->wait_shm_mmap,
1442 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1443 switch (errno) {
1444 case EWOULDBLOCK:
1445 /* Value already changed. */
1446 goto end_wait;
1447 case EINTR:
1448 /* Retry if interrupted by signal. */
1449 break; /* Get out of switch. */
1450 case EFAULT:
1451 wait_poll_fallback = 1;
1452 DBG(
37ed587a
MD
1453"Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1454"do not support FUTEX_WAKE on read-only memory mappings correctly. "
1455"Please upgrade your kernel "
1456"(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1457"mainline). LTTng-UST will use polling mode fallback.");
ee7fcec8
MD
1458 if (ust_debug())
1459 PERROR("futex");
1460 goto end_wait;
80e2814b
MD
1461 }
1462 }
ee7fcec8 1463end_wait:
7fc90dca
MD
1464 return;
1465
1466quit:
1467 ust_unlock();
1468 return;
1469
1470error:
1471 ust_unlock();
7fc90dca 1472 return;
46050b1a
MD
1473}
1474
1ea11eab
MD
1475/*
1476 * This thread does not allocate any resource, except within
1477 * handle_message, within mutex protection. This mutex protects against
1478 * fork and exit.
98bf993f 1479 * The other moment it allocates resources is at socket connection, which
1ea11eab
MD
1480 * is also protected by the mutex.
1481 */
d9e99d10
MD
1482static
1483void *ust_listener_thread(void *arg)
1484{
1ea11eab 1485 struct sock_info *sock_info = arg;
f5c453e9 1486 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
ff517991 1487 long timeout;
d9e99d10 1488
c362addf 1489 lttng_ust_fixup_tls();
01f0e40c
RB
1490 /*
1491 * If available, add '-ust' to the end of this thread's
1492 * process name
1493 */
1494 ret = lttng_ust_setustprocname();
1495 if (ret) {
1496 ERR("Unable to set UST process name");
1497 }
1498
9eb62b9c
MD
1499 /* Restart trying to connect to the session daemon */
1500restart:
c0eedf81
MD
1501 if (prev_connect_failed) {
1502 /* Wait for sessiond availability with pipe */
1503 wait_for_sessiond(sock_info);
1504 if (has_waited) {
1505 has_waited = 0;
1506 /*
1507 * Sleep for 5 seconds before retrying after a
1508 * sequence of failure / wait / failure. This
1509 * deals with a killed or broken session daemon.
1510 */
1511 sleep(5);
eacc4aa4
MD
1512 } else {
1513 has_waited = 1;
c0eedf81 1514 }
c0eedf81
MD
1515 prev_connect_failed = 0;
1516 }
9eb62b9c 1517
101dace0
JR
1518 if (ust_lock()) {
1519 goto quit;
1520 }
1521
1ea11eab 1522 if (sock_info->socket != -1) {
6548fca4 1523 /* FD tracker is updated by ustcomm_close_unix_sock() */
e6973a89 1524 ret = ustcomm_close_unix_sock(sock_info->socket);
1ea11eab 1525 if (ret) {
32ce8569
MD
1526 ERR("Error closing %s ust cmd socket",
1527 sock_info->name);
1ea11eab
MD
1528 }
1529 sock_info->socket = -1;
1530 }
32ce8569 1531 if (sock_info->notify_socket != -1) {
6548fca4 1532 /* FD tracker is updated by ustcomm_close_unix_sock() */
32ce8569
MD
1533 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1534 if (ret) {
1535 ERR("Error closing %s ust notify socket",
1536 sock_info->name);
1537 }
1538 sock_info->notify_socket = -1;
1539 }
46050b1a 1540
6548fca4 1541
321f2351
MD
1542 /*
1543 * Register. We need to perform both connect and sending
1544 * registration message before doing the next connect otherwise
1545 * we may reach unix socket connect queue max limits and block
1546 * on the 2nd connect while the session daemon is awaiting the
1547 * first connect registration message.
1548 */
1549 /* Connect cmd socket */
6548fca4 1550 lttng_ust_lock_fd_tracker();
451d66b2
MD
1551 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1552 get_connect_sock_timeout());
321f2351 1553 if (ret < 0) {
6548fca4 1554 lttng_ust_unlock_fd_tracker();
321f2351
MD
1555 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1556 prev_connect_failed = 1;
5b14aab3 1557
e3426ddc 1558 /*
321f2351
MD
1559 * If we cannot find the sessiond daemon, don't delay
1560 * constructor execution.
e3426ddc 1561 */
e85887ff 1562 ret = handle_register_failed(sock_info);
321f2351
MD
1563 assert(!ret);
1564 ust_unlock();
1565 goto restart;
27fe9f21 1566 }
f5c453e9
JR
1567 fd = ret;
1568 ret = lttng_ust_add_fd_to_tracker(fd);
1569 if (ret < 0) {
1570 ret = close(fd);
1571 if (ret) {
1572 PERROR("close on sock_info->socket");
1573 }
1574 ret = -1;
1575 lttng_ust_unlock_fd_tracker();
1576 ust_unlock();
1577 goto quit;
1578 }
1579
321f2351 1580 sock_info->socket = ret;
f5c453e9 1581 lttng_ust_unlock_fd_tracker();
27fe9f21 1582
6548fca4
MD
1583 ust_unlock();
1584 /*
1585 * Unlock/relock ust lock because connect is blocking (with
1586 * timeout). Don't delay constructors on the ust lock for too
1587 * long.
1588 */
3327ac33 1589 if (ust_lock()) {
5b14aab3
MD
1590 goto quit;
1591 }
1592
46050b1a
MD
1593 /*
1594 * Create only one root handle per listener thread for the whole
f59ed768
MD
1595 * process lifetime, so we ensure we get ID which is statically
1596 * assigned to the root handle.
46050b1a
MD
1597 */
1598 if (sock_info->root_handle == -1) {
1599 ret = lttng_abi_create_root_handle();
a51070bb 1600 if (ret < 0) {
46050b1a 1601 ERR("Error creating root handle");
46050b1a
MD
1602 goto quit;
1603 }
1604 sock_info->root_handle = ret;
9eb62b9c 1605 }
1ea11eab 1606
32ce8569 1607 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
9eb62b9c 1608 if (ret < 0) {
32ce8569
MD
1609 ERR("Error registering to %s ust cmd socket",
1610 sock_info->name);
c0eedf81 1611 prev_connect_failed = 1;
11ff9c7d
MD
1612 /*
1613 * If we cannot register to the sessiond daemon, don't
1614 * delay constructor execution.
1615 */
e85887ff 1616 ret = handle_register_failed(sock_info);
11ff9c7d 1617 assert(!ret);
17dfb34b 1618 ust_unlock();
9eb62b9c
MD
1619 goto restart;
1620 }
321f2351
MD
1621
1622 ust_unlock();
6548fca4
MD
1623 /*
1624 * Unlock/relock ust lock because connect is blocking (with
1625 * timeout). Don't delay constructors on the ust lock for too
1626 * long.
1627 */
1628 if (ust_lock()) {
1629 goto quit;
1630 }
321f2351
MD
1631
1632 /* Connect notify socket */
6548fca4 1633 lttng_ust_lock_fd_tracker();
451d66b2
MD
1634 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1635 get_connect_sock_timeout());
321f2351 1636 if (ret < 0) {
6548fca4 1637 lttng_ust_unlock_fd_tracker();
321f2351
MD
1638 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1639 prev_connect_failed = 1;
1640
321f2351
MD
1641 /*
1642 * If we cannot find the sessiond daemon, don't delay
1643 * constructor execution.
1644 */
e85887ff 1645 ret = handle_register_failed(sock_info);
321f2351
MD
1646 assert(!ret);
1647 ust_unlock();
1648 goto restart;
1649 }
f5c453e9
JR
1650
1651 fd = ret;
1652 ret = lttng_ust_add_fd_to_tracker(fd);
1653 if (ret < 0) {
1654 ret = close(fd);
1655 if (ret) {
1656 PERROR("close on sock_info->notify_socket");
1657 }
1658 ret = -1;
1659 lttng_ust_unlock_fd_tracker();
1660 ust_unlock();
1661 goto quit;
1662 }
1663
321f2351 1664 sock_info->notify_socket = ret;
f5c453e9 1665 lttng_ust_unlock_fd_tracker();
321f2351 1666
6548fca4
MD
1667 ust_unlock();
1668 /*
1669 * Unlock/relock ust lock because connect is blocking (with
1670 * timeout). Don't delay constructors on the ust lock for too
1671 * long.
1672 */
1673 if (ust_lock()) {
1674 goto quit;
1675 }
1676
321f2351
MD
1677 timeout = get_notify_sock_timeout();
1678 if (timeout >= 0) {
1679 /*
1680 * Give at least 10ms to sessiond to reply to
1681 * notifications.
1682 */
1683 if (timeout < 10)
1684 timeout = 10;
1685 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1686 timeout);
1687 if (ret < 0) {
1688 WARN("Error setting socket receive timeout");
1689 }
1690 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1691 timeout);
1692 if (ret < 0) {
1693 WARN("Error setting socket send timeout");
1694 }
1695 } else if (timeout < -1) {
1696 WARN("Unsupported timeout value %ld", timeout);
1697 }
1698
32ce8569
MD
1699 ret = register_to_sessiond(sock_info->notify_socket,
1700 USTCTL_SOCKET_NOTIFY);
1701 if (ret < 0) {
1702 ERR("Error registering to %s ust notify socket",
1703 sock_info->name);
1704 prev_connect_failed = 1;
1705 /*
1706 * If we cannot register to the sessiond daemon, don't
1707 * delay constructor execution.
1708 */
e85887ff 1709 ret = handle_register_failed(sock_info);
32ce8569
MD
1710 assert(!ret);
1711 ust_unlock();
1712 goto restart;
1713 }
1714 sock = sock_info->socket;
1715
17dfb34b 1716 ust_unlock();
46050b1a 1717
d9e99d10
MD
1718 for (;;) {
1719 ssize_t len;
57773204 1720 struct ustcomm_ust_msg lum;
d9e99d10 1721
57773204 1722 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
d9e99d10
MD
1723 switch (len) {
1724 case 0: /* orderly shutdown */
7dd08bec 1725 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
3327ac33 1726 if (ust_lock()) {
d5e1fea6
MD
1727 goto quit;
1728 }
8236ba10
MD
1729 /*
1730 * Either sessiond has shutdown or refused us by closing the socket.
1731 * In either case, we don't want to delay construction execution,
1732 * and we need to wait before retry.
1733 */
1734 prev_connect_failed = 1;
1735 /*
1736 * If we cannot register to the sessiond daemon, don't
1737 * delay constructor execution.
1738 */
e85887ff 1739 ret = handle_register_failed(sock_info);
8236ba10
MD
1740 assert(!ret);
1741 ust_unlock();
d9e99d10 1742 goto end;
e7723462 1743 case sizeof(lum):
74d81a6c 1744 print_cmd(lum.cmd, lum.handle);
11ff9c7d 1745 ret = handle_message(sock_info, sock, &lum);
7bc53e94 1746 if (ret) {
0dafcd63
MD
1747 ERR("Error handling message for %s socket",
1748 sock_info->name);
1749 /*
1750 * Close socket if protocol error is
1751 * detected.
1752 */
1753 goto end;
d9e99d10
MD
1754 }
1755 continue;
7bc53e94
MD
1756 default:
1757 if (len < 0) {
1758 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1759 } else {
1760 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1761 }
1762 if (len == -ECONNRESET) {
1763 DBG("%s remote end closed connection", sock_info->name);
d9e99d10
MD
1764 goto end;
1765 }
1766 goto end;
d9e99d10
MD
1767 }
1768
1769 }
1770end:
3327ac33 1771 if (ust_lock()) {
d5e1fea6
MD
1772 goto quit;
1773 }
f59ed768
MD
1774 /* Cleanup socket handles before trying to reconnect */
1775 lttng_ust_objd_table_owner_cleanup(sock_info);
1776 ust_unlock();
9eb62b9c 1777 goto restart; /* try to reconnect */
e33f3265 1778
1ea11eab 1779quit:
e33f3265 1780 ust_unlock();
3327ac33
MD
1781
1782 pthread_mutex_lock(&ust_exit_mutex);
1783 sock_info->thread_active = 0;
1784 pthread_mutex_unlock(&ust_exit_mutex);
d9e99d10
MD
1785 return NULL;
1786}
1787
2594a5b4
MD
1788/*
1789 * Weak symbol to call when the ust malloc wrapper is not loaded.
1790 */
1791__attribute__((weak))
1792void lttng_ust_malloc_wrapper_init(void)
1793{
1794}
1795
2691221a
MD
1796/*
1797 * sessiond monitoring thread: monitor presence of global and per-user
1798 * sessiond by polling the application common named pipe.
1799 */
edaa1431 1800void __attribute__((constructor)) lttng_ust_init(void)
2691221a 1801{
11ff9c7d 1802 struct timespec constructor_timeout;
ae6a58bf 1803 sigset_t sig_all_blocked, orig_parent_mask;
1879f67f 1804 pthread_attr_t thread_attr;
cf12a773 1805 int timeout_mode;
2691221a 1806 int ret;
b2292d85 1807 void *handle;
2691221a 1808
edaa1431
MD
1809 if (uatomic_xchg(&initialized, 1) == 1)
1810 return;
1811
eddd8d5d
MD
1812 /*
1813 * Fixup interdependency between TLS fixup mutex (which happens
1814 * to be the dynamic linker mutex) and ust_lock, taken within
1815 * the ust lock.
1816 */
c362addf 1817 lttng_ust_fixup_tls();
eddd8d5d 1818
07b57e5e
MD
1819 lttng_ust_loaded = 1;
1820
b2292d85
FD
1821 /*
1822 * We need to ensure that the liblttng-ust library is not unloaded to avoid
1823 * the unloading of code used by the ust_listener_threads as we can not
1824 * reliably know when they exited. To do that, manually load
1825 * liblttng-ust.so to increment the dynamic loader's internal refcount for
1826 * this library so it never becomes zero, thus never gets unloaded from the
1827 * address space of the process. Since we are already running in the
1828 * constructor of the LTTNG_UST_LIB_SO_NAME library, calling dlopen will
1829 * simply increment the refcount and no additionnal work is needed by the
1830 * dynamic loader as the shared library is already loaded in the address
1831 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
1832 * unloading of the UST library if its refcount becomes zero (which should
1833 * never happen). Do the return value check but discard the handle at the
1834 * end of the function as it's not needed.
1835 */
1836 handle = dlopen(LTTNG_UST_LIB_SO_NAME, RTLD_LAZY | RTLD_NODELETE);
1837 if (!handle) {
1838 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SO_NAME);
1839 }
1840
edaa1431
MD
1841 /*
1842 * We want precise control over the order in which we construct
1843 * our sub-libraries vs starting to receive commands from
1844 * sessiond (otherwise leading to errors when trying to create
1845 * sessiond before the init functions are completed).
1846 */
2691221a 1847 init_usterr();
6f626d28 1848 lttng_ust_getenv_init(); /* Needs init_usterr() to be completed. */
edaa1431 1849 init_tracepoint();
6548fca4 1850 lttng_ust_init_fd_tracker();
f9364363 1851 lttng_ust_clock_init();
5e1b7b8b 1852 lttng_ust_getcpu_init();
cf73e0fe 1853 lttng_ust_statedump_init();
7dd08bec
MD
1854 lttng_ring_buffer_metadata_client_init();
1855 lttng_ring_buffer_client_overwrite_init();
34a91bdb 1856 lttng_ring_buffer_client_overwrite_rt_init();
7dd08bec 1857 lttng_ring_buffer_client_discard_init();
34a91bdb 1858 lttng_ring_buffer_client_discard_rt_init();
d58d1454 1859 lttng_perf_counter_init();
2594a5b4
MD
1860 /*
1861 * Invoke ust malloc wrapper init before starting other threads.
1862 */
1863 lttng_ust_malloc_wrapper_init();
2691221a 1864
ff517991 1865 timeout_mode = get_constructor_timeout(&constructor_timeout);
11ff9c7d 1866
b2c5f61a 1867 get_allow_blocking();
6f97f9c2 1868
95259bd0 1869 ret = sem_init(&constructor_wait, 0, 0);
8aadb54a
MD
1870 if (ret) {
1871 PERROR("sem_init");
1872 }
11ff9c7d 1873
9d2dfb47
JR
1874 ret = setup_global_apps();
1875 if (ret) {
1876 assert(global_apps.allowed == 0);
1877 DBG("global apps setup returned %d", ret);
1878 }
1879
8d20bf54 1880 ret = setup_local_apps();
2691221a 1881 if (ret) {
9d2dfb47 1882 assert(local_apps.allowed == 0);
9ec6895c 1883 DBG("local apps setup returned %d", ret);
2691221a 1884 }
ae6a58bf
WP
1885
1886 /* A new thread created by pthread_create inherits the signal mask
1887 * from the parent. To avoid any signal being received by the
1888 * listener thread, we block all signals temporarily in the parent,
1889 * while we create the listener thread.
1890 */
1891 sigfillset(&sig_all_blocked);
1892 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1893 if (ret) {
d94d802c 1894 ERR("pthread_sigmask: %s", strerror(ret));
ae6a58bf
WP
1895 }
1896
1879f67f
MG
1897 ret = pthread_attr_init(&thread_attr);
1898 if (ret) {
1899 ERR("pthread_attr_init: %s", strerror(ret));
1900 }
1901 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1902 if (ret) {
1903 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1904 }
1905
9d2dfb47
JR
1906 if (global_apps.allowed) {
1907 pthread_mutex_lock(&ust_exit_mutex);
1908 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1909 ust_listener_thread, &global_apps);
1910 if (ret) {
1911 ERR("pthread_create global: %s", strerror(ret));
1912 }
1913 global_apps.thread_active = 1;
1914 pthread_mutex_unlock(&ust_exit_mutex);
1915 } else {
1916 handle_register_done(&global_apps);
d94d802c 1917 }
e33f3265 1918
8d20bf54 1919 if (local_apps.allowed) {
c0bbbd5a 1920 pthread_mutex_lock(&ust_exit_mutex);
1879f67f 1921 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
dde70ea0 1922 ust_listener_thread, &local_apps);
d94d802c
MD
1923 if (ret) {
1924 ERR("pthread_create local: %s", strerror(ret));
1925 }
e33f3265 1926 local_apps.thread_active = 1;
c0bbbd5a 1927 pthread_mutex_unlock(&ust_exit_mutex);
8d20bf54
MD
1928 } else {
1929 handle_register_done(&local_apps);
1930 }
1879f67f
MG
1931 ret = pthread_attr_destroy(&thread_attr);
1932 if (ret) {
1933 ERR("pthread_attr_destroy: %s", strerror(ret));
1934 }
8d20bf54 1935
ae6a58bf
WP
1936 /* Restore original signal mask in parent */
1937 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1938 if (ret) {
d94d802c 1939 ERR("pthread_sigmask: %s", strerror(ret));
ae6a58bf
WP
1940 }
1941
cf12a773
MD
1942 switch (timeout_mode) {
1943 case 1: /* timeout wait */
95259bd0
MD
1944 do {
1945 ret = sem_timedwait(&constructor_wait,
1946 &constructor_timeout);
1947 } while (ret < 0 && errno == EINTR);
8aadb54a
MD
1948 if (ret < 0) {
1949 switch (errno) {
1950 case ETIMEDOUT:
1951 ERR("Timed out waiting for lttng-sessiond");
1952 break;
1953 case EINVAL:
1954 PERROR("sem_timedwait");
1955 break;
1956 default:
1957 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1958 strerror(errno));
1959 }
cf12a773
MD
1960 }
1961 break;
7b766b16 1962 case -1:/* wait forever */
95259bd0
MD
1963 do {
1964 ret = sem_wait(&constructor_wait);
1965 } while (ret < 0 && errno == EINTR);
8aadb54a
MD
1966 if (ret < 0) {
1967 switch (errno) {
1968 case EINVAL:
1969 PERROR("sem_wait");
1970 break;
1971 default:
1972 ERR("Unexpected error \"%s\" returned by sem_wait",
1973 strerror(errno));
1974 }
1975 }
cf12a773 1976 break;
7b766b16 1977 case 0: /* no timeout */
cf12a773 1978 break;
11ff9c7d 1979 }
2691221a
MD
1980}
1981
17dfb34b
MD
1982static
1983void lttng_ust_cleanup(int exiting)
1984{
efe0de09 1985 cleanup_sock_info(&global_apps, exiting);
932cfadb 1986 cleanup_sock_info(&local_apps, exiting);
74f98bc9 1987 local_apps.allowed = 0;
9d2dfb47 1988 global_apps.allowed = 0;
efe0de09
MD
1989 /*
1990 * The teardown in this function all affect data structures
1991 * accessed under the UST lock by the listener thread. This
1992 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1993 * that none of these threads are accessing this data at this
1994 * point.
1995 */
17dfb34b 1996 lttng_ust_abi_exit();
003fedf4 1997 lttng_ust_events_exit();
d58d1454 1998 lttng_perf_counter_exit();
34a91bdb 1999 lttng_ring_buffer_client_discard_rt_exit();
7dd08bec 2000 lttng_ring_buffer_client_discard_exit();
34a91bdb 2001 lttng_ring_buffer_client_overwrite_rt_exit();
7dd08bec
MD
2002 lttng_ring_buffer_client_overwrite_exit();
2003 lttng_ring_buffer_metadata_client_exit();
cf73e0fe 2004 lttng_ust_statedump_destroy();
17dfb34b
MD
2005 exit_tracepoint();
2006 if (!exiting) {
2007 /* Reinitialize values for fork */
e85887ff 2008 sem_count = sem_count_initial_value;
17dfb34b
MD
2009 lttng_ust_comm_should_quit = 0;
2010 initialized = 0;
2011 }
2012}
2013
edaa1431 2014void __attribute__((destructor)) lttng_ust_exit(void)
2691221a
MD
2015{
2016 int ret;
2017
9eb62b9c
MD
2018 /*
2019 * Using pthread_cancel here because:
2020 * A) we don't want to hang application teardown.
2021 * B) the thread is not allocating any resource.
2022 */
1ea11eab
MD
2023
2024 /*
2025 * Require the communication thread to quit. Synchronize with
2026 * mutexes to ensure it is not in a mutex critical section when
2027 * pthread_cancel is later called.
2028 */
3327ac33 2029 ust_lock_nocheck();
1ea11eab 2030 lttng_ust_comm_should_quit = 1;
3327ac33 2031 ust_unlock();
1ea11eab 2032
3327ac33 2033 pthread_mutex_lock(&ust_exit_mutex);
f5f94532 2034 /* cancel threads */
e33f3265
MD
2035 if (global_apps.thread_active) {
2036 ret = pthread_cancel(global_apps.ust_listener);
2037 if (ret) {
2038 ERR("Error cancelling global ust listener thread: %s",
2039 strerror(ret));
2040 } else {
2041 global_apps.thread_active = 0;
2042 }
2691221a 2043 }
e33f3265 2044 if (local_apps.thread_active) {
8d20bf54
MD
2045 ret = pthread_cancel(local_apps.ust_listener);
2046 if (ret) {
d94d802c
MD
2047 ERR("Error cancelling local ust listener thread: %s",
2048 strerror(ret));
e33f3265
MD
2049 } else {
2050 local_apps.thread_active = 0;
8d20bf54 2051 }
8d20bf54 2052 }
3327ac33 2053 pthread_mutex_unlock(&ust_exit_mutex);
e33f3265 2054
efe0de09
MD
2055 /*
2056 * Do NOT join threads: use of sys_futex makes it impossible to
2057 * join the threads without using async-cancel, but async-cancel
2058 * is delivered by a signal, which could hit the target thread
2059 * anywhere in its code path, including while the ust_lock() is
2060 * held, causing a deadlock for the other thread. Let the OS
2061 * cleanup the threads if there are stalled in a syscall.
2062 */
17dfb34b 2063 lttng_ust_cleanup(1);
2691221a 2064}
e822f505
MD
2065
2066/*
2067 * We exclude the worker threads across fork and clone (except
2068 * CLONE_VM), because these system calls only keep the forking thread
2069 * running in the child. Therefore, we don't want to call fork or clone
2070 * in the middle of an tracepoint or ust tracing state modification.
2071 * Holding this mutex protects these structures across fork and clone.
2072 */
b728d87e 2073void ust_before_fork(sigset_t *save_sigset)
e822f505
MD
2074{
2075 /*
2076 * Disable signals. This is to avoid that the child intervenes
2077 * before it is properly setup for tracing. It is safer to
2078 * disable all signals, because then we know we are not breaking
2079 * anything by restoring the original mask.
2080 */
2081 sigset_t all_sigs;
2082 int ret;
2083
c362addf
MD
2084 /* Fixup lttng-ust TLS. */
2085 lttng_ust_fixup_tls();
2086
8c90a710 2087 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2088 return;
e822f505
MD
2089 /* Disable signals */
2090 sigfillset(&all_sigs);
b728d87e 2091 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
e822f505
MD
2092 if (ret == -1) {
2093 PERROR("sigprocmask");
2094 }
458d678c
PW
2095
2096 pthread_mutex_lock(&ust_fork_mutex);
2097
3327ac33 2098 ust_lock_nocheck();
e822f505 2099 rcu_bp_before_fork();
48a80fd7 2100 lttng_ust_lock_fd_tracker();
4ed26293 2101 lttng_perf_lock();
e822f505
MD
2102}
2103
b728d87e 2104static void ust_after_fork_common(sigset_t *restore_sigset)
e822f505
MD
2105{
2106 int ret;
2107
17dfb34b 2108 DBG("process %d", getpid());
4ed26293 2109 lttng_perf_unlock();
48a80fd7 2110 lttng_ust_unlock_fd_tracker();
17dfb34b 2111 ust_unlock();
458d678c
PW
2112
2113 pthread_mutex_unlock(&ust_fork_mutex);
2114
e822f505 2115 /* Restore signals */
23c8854a 2116 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
e822f505
MD
2117 if (ret == -1) {
2118 PERROR("sigprocmask");
2119 }
2120}
2121
b728d87e 2122void ust_after_fork_parent(sigset_t *restore_sigset)
e822f505 2123{
8c90a710 2124 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2125 return;
17dfb34b 2126 DBG("process %d", getpid());
e822f505
MD
2127 rcu_bp_after_fork_parent();
2128 /* Release mutexes and reenable signals */
b728d87e 2129 ust_after_fork_common(restore_sigset);
e822f505
MD
2130}
2131
17dfb34b
MD
2132/*
2133 * After fork, in the child, we need to cleanup all the leftover state,
2134 * except the worker thread which already magically disappeared thanks
2135 * to the weird Linux fork semantics. After tyding up, we call
2136 * lttng_ust_init() again to start over as a new PID.
2137 *
2138 * This is meant for forks() that have tracing in the child between the
2139 * fork and following exec call (if there is any).
2140 */
b728d87e 2141void ust_after_fork_child(sigset_t *restore_sigset)
e822f505 2142{
8c90a710 2143 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2144 return;
06b16a0b 2145 lttng_context_vpid_reset();
8478887d 2146 lttng_context_vtid_reset();
3e3a077a 2147 lttng_context_procname_reset();
17dfb34b 2148 DBG("process %d", getpid());
e822f505
MD
2149 /* Release urcu mutexes */
2150 rcu_bp_after_fork_child();
17dfb34b 2151 lttng_ust_cleanup(0);
e822f505 2152 /* Release mutexes and reenable signals */
b728d87e 2153 ust_after_fork_common(restore_sigset);
318dfea9 2154 lttng_ust_init();
e822f505 2155}
95c25348 2156
246be17e 2157void lttng_ust_sockinfo_session_enabled(void *owner)
95c25348
PW
2158{
2159 struct sock_info *sock_info = owner;
37dddb65 2160 sock_info->statedump_pending = 1;
95c25348 2161}
This page took 0.160111 seconds and 4 git commands to generate.