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