4 * Copyright (C) 2011 David Goulet <david.goulet@polymtl.ca>
5 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
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.
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.
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
23 #include <sys/types.h>
24 #include <sys/socket.h>
27 #include <sys/types.h>
33 #include <semaphore.h>
37 #include <urcu/uatomic.h>
38 #include <urcu/futex.h>
39 #include <urcu/compiler.h>
41 #include <lttng/ust-events.h>
42 #include <lttng/ust-abi.h>
43 #include <lttng/ust.h>
44 #include <lttng/ust-error.h>
45 #include <lttng/ust-ctl.h>
46 #include <urcu/tls-compat.h>
48 #include <usterr-signal-safe.h>
50 #include "tracepoint-internal.h"
51 #include "lttng-tracer-core.h"
53 #include "../libringbuffer/tlsfixup.h"
54 #include "lttng-ust-baddr.h"
57 * Has lttng ust comm constructor been called ?
59 static int initialized
;
62 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
63 * Held when handling a command, also held by fork() to deal with
64 * removal of threads, and by exit path.
66 * The UST lock is the centralized mutex across UST tracing control and
69 * ust_exit_mutex must never nest in ust_mutex.
71 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
72 * counter lazy initialization called by events within the statedump,
73 * which traces while the ust_mutex is held.
75 static pthread_mutex_t ust_mutex
= PTHREAD_MUTEX_INITIALIZER
;
77 /* Allow nesting the ust_mutex within the same thread. */
78 static DEFINE_URCU_TLS(int, ust_mutex_nest
);
81 * ust_exit_mutex protects thread_active variable wrt thread exit. It
82 * cannot be done by ust_mutex because pthread_cancel(), which takes an
83 * internal libc lock, cannot nest within ust_mutex.
85 * It never nests within a ust_mutex.
87 static pthread_mutex_t ust_exit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
89 /* Should the ust comm thread quit ? */
90 static int lttng_ust_comm_should_quit
;
93 * Return 0 on success, -1 if should quit.
94 * The lock is taken in both cases.
99 sigset_t sig_all_blocked
, orig_mask
;
102 sigfillset(&sig_all_blocked
);
103 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
105 ERR("pthread_sigmask: %s", strerror(ret
));
107 if (!URCU_TLS(ust_mutex_nest
)++)
108 pthread_mutex_lock(&ust_mutex
);
109 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
111 ERR("pthread_sigmask: %s", strerror(ret
));
113 if (lttng_ust_comm_should_quit
) {
121 * ust_lock_nocheck() can be used in constructors/destructors, because
122 * they are already nested within the dynamic loader lock, and therefore
123 * have exclusive access against execution of liblttng-ust destructor.
126 void ust_lock_nocheck(void)
128 sigset_t sig_all_blocked
, orig_mask
;
131 sigfillset(&sig_all_blocked
);
132 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
134 ERR("pthread_sigmask: %s", strerror(ret
));
136 if (!URCU_TLS(ust_mutex_nest
)++)
137 pthread_mutex_lock(&ust_mutex
);
138 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
140 ERR("pthread_sigmask: %s", strerror(ret
));
147 void ust_unlock(void)
149 sigset_t sig_all_blocked
, orig_mask
;
152 sigfillset(&sig_all_blocked
);
153 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
155 ERR("pthread_sigmask: %s", strerror(ret
));
157 if (!--URCU_TLS(ust_mutex_nest
))
158 pthread_mutex_unlock(&ust_mutex
);
159 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
161 ERR("pthread_sigmask: %s", strerror(ret
));
166 * Wait for either of these before continuing to the main
168 * - the register_done message from sessiond daemon
169 * (will let the sessiond daemon enable sessions before main
171 * - sessiond daemon is not reachable.
172 * - timeout (ensuring applications are resilient to session
175 static sem_t constructor_wait
;
177 * Doing this for both the global and local sessiond.
179 static int sem_count
= { 2 };
182 * Counting nesting within lttng-ust. Used to ensure that calling fork()
183 * from liblttng-ust does not execute the pre/post fork handlers.
185 static DEFINE_URCU_TLS(int, lttng_ust_nest_count
);
188 * Info about socket and associated listener thread.
192 pthread_t ust_listener
; /* listener thread */
194 int constructor_sem_posted
;
199 char sock_path
[PATH_MAX
];
203 char wait_shm_path
[PATH_MAX
];
205 /* Keep track of lazy state dump not performed yet. */
206 int statedump_pending
;
209 /* Socket from app (connect) to session daemon (listen) for communication */
210 struct sock_info global_apps
= {
218 .sock_path
= LTTNG_DEFAULT_RUNDIR
"/" LTTNG_UST_SOCK_FILENAME
,
222 .wait_shm_path
= "/" LTTNG_UST_WAIT_FILENAME
,
224 .statedump_pending
= 0,
227 /* TODO: allow global_apps_sock_path override */
229 struct sock_info local_apps
= {
233 .allowed
= 0, /* Check setuid bit first */
239 .statedump_pending
= 0,
242 static int wait_poll_fallback
;
244 static const char *cmd_name_mapping
[] = {
245 [ LTTNG_UST_RELEASE
] = "Release",
246 [ LTTNG_UST_SESSION
] = "Create Session",
247 [ LTTNG_UST_TRACER_VERSION
] = "Get Tracer Version",
249 [ LTTNG_UST_TRACEPOINT_LIST
] = "Create Tracepoint List",
250 [ LTTNG_UST_WAIT_QUIESCENT
] = "Wait for Quiescent State",
251 [ LTTNG_UST_REGISTER_DONE
] = "Registration Done",
252 [ LTTNG_UST_TRACEPOINT_FIELD_LIST
] = "Create Tracepoint Field List",
254 /* Session FD commands */
255 [ LTTNG_UST_CHANNEL
] = "Create Channel",
256 [ LTTNG_UST_SESSION_START
] = "Start Session",
257 [ LTTNG_UST_SESSION_STOP
] = "Stop Session",
259 /* Channel FD commands */
260 [ LTTNG_UST_STREAM
] = "Create Stream",
261 [ LTTNG_UST_EVENT
] = "Create Event",
263 /* Event and Channel FD commands */
264 [ LTTNG_UST_CONTEXT
] = "Create Context",
265 [ LTTNG_UST_FLUSH_BUFFER
] = "Flush Buffer",
267 /* Event, Channel and Session commands */
268 [ LTTNG_UST_ENABLE
] = "Enable",
269 [ LTTNG_UST_DISABLE
] = "Disable",
271 /* Tracepoint list commands */
272 [ LTTNG_UST_TRACEPOINT_LIST_GET
] = "List Next Tracepoint",
273 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
] = "List Next Tracepoint Field",
275 /* Event FD commands */
276 [ LTTNG_UST_FILTER
] = "Create Filter",
277 [ LTTNG_UST_EXCLUSION
] = "Add exclusions to event",
280 static const char *str_timeout
;
281 static int got_timeout_env
;
283 extern void lttng_ring_buffer_client_overwrite_init(void);
284 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
285 extern void lttng_ring_buffer_client_discard_init(void);
286 extern void lttng_ring_buffer_client_discard_rt_init(void);
287 extern void lttng_ring_buffer_metadata_client_init(void);
288 extern void lttng_ring_buffer_client_overwrite_exit(void);
289 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
290 extern void lttng_ring_buffer_client_discard_exit(void);
291 extern void lttng_ring_buffer_client_discard_rt_exit(void);
292 extern void lttng_ring_buffer_metadata_client_exit(void);
295 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
299 const char *get_lttng_home_dir(void)
303 val
= (const char *) getenv("LTTNG_HOME");
307 return (const char *) getenv("HOME");
311 * Force a read (imply TLS fixup for dlopen) of TLS variables.
314 void lttng_fixup_nest_count_tls(void)
316 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count
)));
320 void lttng_fixup_ust_mutex_nest_tls(void)
322 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest
)));
325 int lttng_get_notify_socket(void *owner
)
327 struct sock_info
*info
= owner
;
329 return info
->notify_socket
;
333 void print_cmd(int cmd
, int handle
)
335 const char *cmd_name
= "Unknown";
337 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
338 && cmd_name_mapping
[cmd
]) {
339 cmd_name
= cmd_name_mapping
[cmd
];
341 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
343 lttng_ust_obj_get_name(handle
), handle
);
347 int setup_local_apps(void)
349 const char *home_dir
;
354 * Disallow per-user tracing for setuid binaries.
356 if (uid
!= geteuid()) {
357 assert(local_apps
.allowed
== 0);
360 home_dir
= get_lttng_home_dir();
362 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
363 assert(local_apps
.allowed
== 0);
366 local_apps
.allowed
= 1;
367 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
369 LTTNG_DEFAULT_HOME_RUNDIR
,
370 LTTNG_UST_SOCK_FILENAME
);
371 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
372 LTTNG_UST_WAIT_FILENAME
,
378 * Get notify_sock timeout, in ms.
379 * -1: don't wait. 0: wait forever. >0: timeout, in ms.
382 long get_timeout(void)
384 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
386 if (!got_timeout_env
) {
387 str_timeout
= getenv("LTTNG_UST_REGISTER_TIMEOUT");
391 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
392 return constructor_delay_ms
;
396 long get_notify_sock_timeout(void)
398 return get_timeout();
402 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
405 int get_constructor_timeout(struct timespec
*constructor_timeout
)
407 long constructor_delay_ms
;
410 constructor_delay_ms
= get_timeout();
412 switch (constructor_delay_ms
) {
413 case -1:/* fall-through */
415 return constructor_delay_ms
;
421 * If we are unable to find the current time, don't wait.
423 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
427 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
428 constructor_timeout
->tv_nsec
+=
429 (constructor_delay_ms
% 1000UL) * 1000000UL;
430 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
431 constructor_timeout
->tv_sec
++;
432 constructor_timeout
->tv_nsec
-= 1000000000UL;
438 int register_to_sessiond(int socket
, enum ustctl_socket_type type
)
440 return ustcomm_send_reg_msg(socket
,
443 lttng_alignof(uint8_t) * CHAR_BIT
,
444 lttng_alignof(uint16_t) * CHAR_BIT
,
445 lttng_alignof(uint32_t) * CHAR_BIT
,
446 lttng_alignof(uint64_t) * CHAR_BIT
,
447 lttng_alignof(unsigned long) * CHAR_BIT
);
451 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
455 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
458 DBG("message successfully sent");
461 if (len
== -ECONNRESET
) {
462 DBG("remote end closed connection");
467 DBG("incorrect message size: %zd", len
);
473 int handle_register_done(struct sock_info
*sock_info
)
477 if (sock_info
->constructor_sem_posted
)
479 sock_info
->constructor_sem_posted
= 1;
480 if (uatomic_read(&sem_count
) <= 0) {
483 ret
= uatomic_add_return(&sem_count
, -1);
485 ret
= sem_post(&constructor_wait
);
492 * Only execute pending statedump after the constructor semaphore has
493 * been posted by each listener thread. This means statedump will only
494 * be performed after the "registration done" command is received from
495 * each session daemon the application is connected to.
497 * This ensures we don't run into deadlock issues with the dynamic
498 * loader mutex, which is held while the constructor is called and
499 * waiting on the constructor semaphore. All operations requiring this
500 * dynamic loader lock need to be postponed using this mechanism.
503 void handle_pending_statedump(struct sock_info
*sock_info
)
505 int ctor_passed
= sock_info
->constructor_sem_posted
;
507 if (ctor_passed
&& sock_info
->statedump_pending
) {
508 sock_info
->statedump_pending
= 0;
509 lttng_handle_pending_statedump(sock_info
);
514 int handle_message(struct sock_info
*sock_info
,
515 int sock
, struct ustcomm_ust_msg
*lum
)
518 const struct lttng_ust_objd_ops
*ops
;
519 struct ustcomm_ust_reply lur
;
523 memset(&lur
, 0, sizeof(lur
));
526 ret
= -LTTNG_UST_ERR_EXITING
;
530 ops
= objd_ops(lum
->handle
);
537 case LTTNG_UST_REGISTER_DONE
:
538 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
539 ret
= handle_register_done(sock_info
);
543 case LTTNG_UST_RELEASE
:
544 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
547 ret
= lttng_ust_objd_unref(lum
->handle
, 1);
549 case LTTNG_UST_FILTER
:
551 /* Receive filter data */
552 struct lttng_ust_filter_bytecode_node
*bytecode
;
554 if (lum
->u
.filter
.data_size
> FILTER_BYTECODE_MAX_LEN
) {
555 ERR("Filter data size is too large: %u bytes",
556 lum
->u
.filter
.data_size
);
561 if (lum
->u
.filter
.reloc_offset
> lum
->u
.filter
.data_size
) {
562 ERR("Filter reloc offset %u is not within data",
563 lum
->u
.filter
.reloc_offset
);
568 bytecode
= zmalloc(sizeof(*bytecode
) + lum
->u
.filter
.data_size
);
573 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
,
574 lum
->u
.filter
.data_size
);
576 case 0: /* orderly shutdown */
581 if (len
== lum
->u
.filter
.data_size
) {
582 DBG("filter data received");
584 } else if (len
< 0) {
585 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
586 if (len
== -ECONNRESET
) {
587 ERR("%s remote end closed connection", sock_info
->name
);
596 DBG("incorrect filter data message size: %zd", len
);
602 bytecode
->bc
.len
= lum
->u
.filter
.data_size
;
603 bytecode
->bc
.reloc_offset
= lum
->u
.filter
.reloc_offset
;
604 bytecode
->bc
.seqnum
= lum
->u
.filter
.seqnum
;
606 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
607 (unsigned long) bytecode
,
612 /* don't free bytecode if everything went fine. */
619 case LTTNG_UST_EXCLUSION
:
621 /* Receive exclusion names */
622 struct lttng_ust_excluder_node
*node
;
625 count
= lum
->u
.exclusion
.count
;
627 /* There are no names to read */
631 node
= zmalloc(sizeof(*node
) +
632 count
* LTTNG_UST_SYM_NAME_LEN
);
637 node
->excluder
.count
= count
;
638 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
639 count
* LTTNG_UST_SYM_NAME_LEN
);
641 case 0: /* orderly shutdown */
646 if (len
== count
* LTTNG_UST_SYM_NAME_LEN
) {
647 DBG("Exclusion data received");
649 } else if (len
< 0) {
650 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
651 if (len
== -ECONNRESET
) {
652 ERR("%s remote end closed connection", sock_info
->name
);
661 DBG("Incorrect exclusion data message size: %zd", len
);
668 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
669 (unsigned long) node
,
674 /* Don't free exclusion data if everything went fine. */
681 case LTTNG_UST_CHANNEL
:
686 len
= ustcomm_recv_channel_from_sessiond(sock
,
687 &chan_data
, lum
->u
.channel
.len
,
690 case 0: /* orderly shutdown */
694 if (len
== lum
->u
.channel
.len
) {
695 DBG("channel data received");
697 } else if (len
< 0) {
698 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
699 if (len
== -ECONNRESET
) {
700 ERR("%s remote end closed connection", sock_info
->name
);
707 DBG("incorrect channel data message size: %zd", len
);
712 args
.channel
.chan_data
= chan_data
;
713 args
.channel
.wakeup_fd
= wakeup_fd
;
715 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
716 (unsigned long) &lum
->u
,
722 case LTTNG_UST_STREAM
:
724 /* Receive shm_fd, wakeup_fd */
725 ret
= ustcomm_recv_stream_from_sessiond(sock
,
728 &args
.stream
.wakeup_fd
);
733 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
734 (unsigned long) &lum
->u
,
742 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
743 (unsigned long) &lum
->u
,
751 lur
.handle
= lum
->handle
;
755 lur
.ret_code
= LTTNG_UST_OK
;
758 * Use -LTTNG_UST_ERR as wildcard for UST internal
759 * error that are not caused by the transport, except if
760 * we already have a more precise error message to
763 if (ret
> -LTTNG_UST_ERR
) {
764 /* Translate code to UST error. */
767 lur
.ret_code
= -LTTNG_UST_ERR_EXIST
;
770 lur
.ret_code
= -LTTNG_UST_ERR_INVAL
;
773 lur
.ret_code
= -LTTNG_UST_ERR_NOENT
;
776 lur
.ret_code
= -LTTNG_UST_ERR_PERM
;
779 lur
.ret_code
= -LTTNG_UST_ERR_NOSYS
;
782 lur
.ret_code
= -LTTNG_UST_ERR
;
791 case LTTNG_UST_TRACER_VERSION
:
792 lur
.u
.version
= lum
->u
.version
;
794 case LTTNG_UST_TRACEPOINT_LIST_GET
:
795 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
799 DBG("Return value: %d", lur
.ret_val
);
800 ret
= send_reply(sock
, &lur
);
802 DBG("error sending reply");
807 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
810 if (lur
.ret_code
== LTTNG_UST_OK
) {
812 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
:
813 len
= ustcomm_send_unix_sock(sock
,
814 &args
.field_list
.entry
,
815 sizeof(args
.field_list
.entry
));
820 if (len
!= sizeof(args
.field_list
.entry
)) {
831 * Performed delayed statedump operations outside of the UST
832 * lock. We need to take the dynamic loader lock before we take
833 * the UST lock internally within handle_pending_statedump().
835 handle_pending_statedump(sock_info
);
841 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
845 if (sock_info
->root_handle
!= -1) {
846 ret
= lttng_ust_objd_unref(sock_info
->root_handle
, 1);
848 ERR("Error unref root handle");
850 sock_info
->root_handle
= -1;
852 sock_info
->constructor_sem_posted
= 0;
855 * wait_shm_mmap, socket and notify socket are used by listener
856 * threads outside of the ust lock, so we cannot tear them down
857 * ourselves, because we cannot join on these threads. Leave
858 * responsibility of cleaning up these resources to the OS
864 if (sock_info
->socket
!= -1) {
865 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
867 ERR("Error closing ust cmd socket");
869 sock_info
->socket
= -1;
871 if (sock_info
->notify_socket
!= -1) {
872 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
874 ERR("Error closing ust notify socket");
876 sock_info
->notify_socket
= -1;
878 if (sock_info
->wait_shm_mmap
) {
881 page_size
= sysconf(_SC_PAGE_SIZE
);
883 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
885 ERR("Error unmapping wait shm");
888 sock_info
->wait_shm_mmap
= NULL
;
893 * Using fork to set umask in the child process (not multi-thread safe).
894 * We deal with the shm_open vs ftruncate race (happening when the
895 * sessiond owns the shm and does not let everybody modify it, to ensure
896 * safety against shm_unlink) by simply letting the mmap fail and
897 * retrying after a few seconds.
898 * For global shm, everybody has rw access to it until the sessiond
902 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
904 int wait_shm_fd
, ret
;
908 * Try to open read-only.
910 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
911 if (wait_shm_fd
>= 0) {
914 size_t bytes_read
= 0;
917 * Try to read the fd. If unable to do so, try opening
921 len
= read(wait_shm_fd
,
922 &((char *) &tmp_read
)[bytes_read
],
923 sizeof(tmp_read
) - bytes_read
);
927 } while ((len
< 0 && errno
== EINTR
)
928 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
929 if (bytes_read
!= sizeof(tmp_read
)) {
930 ret
= close(wait_shm_fd
);
932 ERR("close wait_shm_fd");
937 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
939 * Real-only open did not work, and it's not because the
940 * entry was not present. It's a failure that prohibits
943 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
949 * If the open failed because the file did not exist, or because
950 * the file was not truncated yet, try creating it ourself.
952 URCU_TLS(lttng_ust_nest_count
)++;
954 URCU_TLS(lttng_ust_nest_count
)--;
959 * Parent: wait for child to return, in which case the
960 * shared memory map will have been created.
963 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
968 * Try to open read-only again after creation.
970 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
971 if (wait_shm_fd
< 0) {
973 * Real-only open did not work. It's a failure
974 * that prohibits using shm.
976 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
980 } else if (pid
== 0) {
984 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
985 if (sock_info
->global
)
986 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
988 * We're alone in a child process, so we can modify the
989 * process-wide umask.
993 * Try creating shm (or get rw access).
994 * We don't do an exclusive open, because we allow other
995 * processes to create+ftruncate it concurrently.
997 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
998 O_RDWR
| O_CREAT
, create_mode
);
999 if (wait_shm_fd
>= 0) {
1000 ret
= ftruncate(wait_shm_fd
, mmap_size
);
1002 PERROR("ftruncate");
1003 _exit(EXIT_FAILURE
);
1005 _exit(EXIT_SUCCESS
);
1008 * For local shm, we need to have rw access to accept
1009 * opening it: this means the local sessiond will be
1010 * able to wake us up. For global shm, we open it even
1011 * if rw access is not granted, because the root.root
1012 * sessiond will be able to override all rights and wake
1015 if (!sock_info
->global
&& errno
!= EACCES
) {
1016 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1017 _exit(EXIT_FAILURE
);
1020 * The shm exists, but we cannot open it RW. Report
1023 _exit(EXIT_SUCCESS
);
1028 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
1029 struct stat statbuf
;
1032 * Ensure that our user is the owner of the shm file for
1033 * local shm. If we do not own the file, it means our
1034 * sessiond will not have access to wake us up (there is
1035 * probably a rogue process trying to fake our
1036 * sessiond). Fallback to polling method in this case.
1038 ret
= fstat(wait_shm_fd
, &statbuf
);
1043 if (statbuf
.st_uid
!= getuid())
1049 ret
= close(wait_shm_fd
);
1051 PERROR("Error closing fd");
1057 char *get_map_shm(struct sock_info
*sock_info
)
1060 int wait_shm_fd
, ret
;
1061 char *wait_shm_mmap
;
1063 page_size
= sysconf(_SC_PAGE_SIZE
);
1064 if (page_size
< 0) {
1068 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1069 if (wait_shm_fd
< 0) {
1072 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1073 MAP_SHARED
, wait_shm_fd
, 0);
1074 /* close shm fd immediately after taking the mmap reference */
1075 ret
= close(wait_shm_fd
);
1077 PERROR("Error closing fd");
1079 if (wait_shm_mmap
== MAP_FAILED
) {
1080 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1083 return wait_shm_mmap
;
1090 void wait_for_sessiond(struct sock_info
*sock_info
)
1097 if (wait_poll_fallback
) {
1100 if (!sock_info
->wait_shm_mmap
) {
1101 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
1102 if (!sock_info
->wait_shm_mmap
)
1107 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1108 /* Wait for futex wakeup */
1109 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
) == 0) {
1110 ret
= futex_async((int32_t *) sock_info
->wait_shm_mmap
,
1111 FUTEX_WAIT
, 0, NULL
, NULL
, 0);
1113 if (errno
== EFAULT
) {
1114 wait_poll_fallback
= 1;
1116 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1117 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1118 "Please upgrade your kernel "
1119 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1120 "mainline). LTTng-UST will use polling mode fallback.");
1138 * This thread does not allocate any resource, except within
1139 * handle_message, within mutex protection. This mutex protects against
1141 * The other moment it allocates resources is at socket connection, which
1142 * is also protected by the mutex.
1145 void *ust_listener_thread(void *arg
)
1147 struct sock_info
*sock_info
= arg
;
1148 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
1151 /* Restart trying to connect to the session daemon */
1153 if (prev_connect_failed
) {
1154 /* Wait for sessiond availability with pipe */
1155 wait_for_sessiond(sock_info
);
1159 * Sleep for 5 seconds before retrying after a
1160 * sequence of failure / wait / failure. This
1161 * deals with a killed or broken session daemon.
1166 prev_connect_failed
= 0;
1169 if (sock_info
->socket
!= -1) {
1170 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1172 ERR("Error closing %s ust cmd socket",
1175 sock_info
->socket
= -1;
1177 if (sock_info
->notify_socket
!= -1) {
1178 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1180 ERR("Error closing %s ust notify socket",
1183 sock_info
->notify_socket
= -1;
1187 * Register. We need to perform both connect and sending
1188 * registration message before doing the next connect otherwise
1189 * we may reach unix socket connect queue max limits and block
1190 * on the 2nd connect while the session daemon is awaiting the
1191 * first connect registration message.
1193 /* Connect cmd socket */
1194 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1196 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1197 prev_connect_failed
= 1;
1204 * If we cannot find the sessiond daemon, don't delay
1205 * constructor execution.
1207 ret
= handle_register_done(sock_info
);
1212 sock_info
->socket
= ret
;
1219 * Create only one root handle per listener thread for the whole
1220 * process lifetime, so we ensure we get ID which is statically
1221 * assigned to the root handle.
1223 if (sock_info
->root_handle
== -1) {
1224 ret
= lttng_abi_create_root_handle();
1226 ERR("Error creating root handle");
1229 sock_info
->root_handle
= ret
;
1232 ret
= register_to_sessiond(sock_info
->socket
, USTCTL_SOCKET_CMD
);
1234 ERR("Error registering to %s ust cmd socket",
1236 prev_connect_failed
= 1;
1238 * If we cannot register to the sessiond daemon, don't
1239 * delay constructor execution.
1241 ret
= handle_register_done(sock_info
);
1249 /* Connect notify socket */
1250 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1252 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1253 prev_connect_failed
= 1;
1260 * If we cannot find the sessiond daemon, don't delay
1261 * constructor execution.
1263 ret
= handle_register_done(sock_info
);
1268 sock_info
->notify_socket
= ret
;
1270 timeout
= get_notify_sock_timeout();
1273 * Give at least 10ms to sessiond to reply to
1278 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
1281 WARN("Error setting socket receive timeout");
1283 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
1286 WARN("Error setting socket send timeout");
1288 } else if (timeout
< -1) {
1289 WARN("Unsupported timeout value %ld", timeout
);
1296 ret
= register_to_sessiond(sock_info
->notify_socket
,
1297 USTCTL_SOCKET_NOTIFY
);
1299 ERR("Error registering to %s ust notify socket",
1301 prev_connect_failed
= 1;
1303 * If we cannot register to the sessiond daemon, don't
1304 * delay constructor execution.
1306 ret
= handle_register_done(sock_info
);
1311 sock
= sock_info
->socket
;
1317 struct ustcomm_ust_msg lum
;
1319 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
1321 case 0: /* orderly shutdown */
1322 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
1327 * Either sessiond has shutdown or refused us by closing the socket.
1328 * In either case, we don't want to delay construction execution,
1329 * and we need to wait before retry.
1331 prev_connect_failed
= 1;
1333 * If we cannot register to the sessiond daemon, don't
1334 * delay constructor execution.
1336 ret
= handle_register_done(sock_info
);
1341 print_cmd(lum
.cmd
, lum
.handle
);
1342 ret
= handle_message(sock_info
, sock
, &lum
);
1344 ERR("Error handling message for %s socket", sock_info
->name
);
1349 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1351 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
1353 if (len
== -ECONNRESET
) {
1354 DBG("%s remote end closed connection", sock_info
->name
);
1365 /* Cleanup socket handles before trying to reconnect */
1366 lttng_ust_objd_table_owner_cleanup(sock_info
);
1368 goto restart
; /* try to reconnect */
1373 pthread_mutex_lock(&ust_exit_mutex
);
1374 sock_info
->thread_active
= 0;
1375 pthread_mutex_unlock(&ust_exit_mutex
);
1380 * Weak symbol to call when the ust malloc wrapper is not loaded.
1382 __attribute__((weak
))
1383 void lttng_ust_malloc_wrapper_init(void)
1388 * sessiond monitoring thread: monitor presence of global and per-user
1389 * sessiond by polling the application common named pipe.
1391 void __attribute__((constructor
)) lttng_ust_init(void)
1393 struct timespec constructor_timeout
;
1394 sigset_t sig_all_blocked
, orig_parent_mask
;
1395 pthread_attr_t thread_attr
;
1399 if (uatomic_xchg(&initialized
, 1) == 1)
1403 * Fixup interdependency between TLS fixup mutex (which happens
1404 * to be the dynamic linker mutex) and ust_lock, taken within
1407 lttng_fixup_ringbuffer_tls();
1408 lttng_fixup_vtid_tls();
1409 lttng_fixup_nest_count_tls();
1410 lttng_fixup_procname_tls();
1411 lttng_fixup_ust_mutex_nest_tls();
1414 * We want precise control over the order in which we construct
1415 * our sub-libraries vs starting to receive commands from
1416 * sessiond (otherwise leading to errors when trying to create
1417 * sessiond before the init functions are completed).
1421 lttng_ust_baddr_statedump_init();
1422 lttng_ring_buffer_metadata_client_init();
1423 lttng_ring_buffer_client_overwrite_init();
1424 lttng_ring_buffer_client_overwrite_rt_init();
1425 lttng_ring_buffer_client_discard_init();
1426 lttng_ring_buffer_client_discard_rt_init();
1427 lttng_perf_counter_init();
1428 lttng_context_init();
1430 * Invoke ust malloc wrapper init before starting other threads.
1432 lttng_ust_malloc_wrapper_init();
1434 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
1436 ret
= sem_init(&constructor_wait
, 0, 0);
1439 ret
= setup_local_apps();
1441 DBG("local apps setup returned %d", ret
);
1444 /* A new thread created by pthread_create inherits the signal mask
1445 * from the parent. To avoid any signal being received by the
1446 * listener thread, we block all signals temporarily in the parent,
1447 * while we create the listener thread.
1449 sigfillset(&sig_all_blocked
);
1450 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
1452 ERR("pthread_sigmask: %s", strerror(ret
));
1455 ret
= pthread_attr_init(&thread_attr
);
1457 ERR("pthread_attr_init: %s", strerror(ret
));
1459 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
1461 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
1464 pthread_mutex_lock(&ust_exit_mutex
);
1465 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
1466 ust_listener_thread
, &global_apps
);
1468 ERR("pthread_create global: %s", strerror(ret
));
1470 global_apps
.thread_active
= 1;
1471 pthread_mutex_unlock(&ust_exit_mutex
);
1473 if (local_apps
.allowed
) {
1474 pthread_mutex_lock(&ust_exit_mutex
);
1475 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
1476 ust_listener_thread
, &local_apps
);
1478 ERR("pthread_create local: %s", strerror(ret
));
1480 local_apps
.thread_active
= 1;
1481 pthread_mutex_unlock(&ust_exit_mutex
);
1483 handle_register_done(&local_apps
);
1485 ret
= pthread_attr_destroy(&thread_attr
);
1487 ERR("pthread_attr_destroy: %s", strerror(ret
));
1490 /* Restore original signal mask in parent */
1491 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
1493 ERR("pthread_sigmask: %s", strerror(ret
));
1496 switch (timeout_mode
) {
1497 case 1: /* timeout wait */
1499 ret
= sem_timedwait(&constructor_wait
,
1500 &constructor_timeout
);
1501 } while (ret
< 0 && errno
== EINTR
);
1502 if (ret
< 0 && errno
== ETIMEDOUT
) {
1503 ERR("Timed out waiting for lttng-sessiond");
1508 case -1:/* wait forever */
1510 ret
= sem_wait(&constructor_wait
);
1511 } while (ret
< 0 && errno
== EINTR
);
1514 case 0: /* no timeout */
1520 void lttng_ust_cleanup(int exiting
)
1522 cleanup_sock_info(&global_apps
, exiting
);
1523 if (local_apps
.allowed
) {
1524 cleanup_sock_info(&local_apps
, exiting
);
1527 * The teardown in this function all affect data structures
1528 * accessed under the UST lock by the listener thread. This
1529 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1530 * that none of these threads are accessing this data at this
1533 lttng_ust_abi_exit();
1534 lttng_ust_events_exit();
1535 lttng_context_exit();
1536 lttng_perf_counter_exit();
1537 lttng_ring_buffer_client_discard_rt_exit();
1538 lttng_ring_buffer_client_discard_exit();
1539 lttng_ring_buffer_client_overwrite_rt_exit();
1540 lttng_ring_buffer_client_overwrite_exit();
1541 lttng_ring_buffer_metadata_client_exit();
1542 lttng_ust_baddr_statedump_destroy();
1545 /* Reinitialize values for fork */
1547 lttng_ust_comm_should_quit
= 0;
1552 void __attribute__((destructor
)) lttng_ust_exit(void)
1557 * Using pthread_cancel here because:
1558 * A) we don't want to hang application teardown.
1559 * B) the thread is not allocating any resource.
1563 * Require the communication thread to quit. Synchronize with
1564 * mutexes to ensure it is not in a mutex critical section when
1565 * pthread_cancel is later called.
1568 lttng_ust_comm_should_quit
= 1;
1571 pthread_mutex_lock(&ust_exit_mutex
);
1572 /* cancel threads */
1573 if (global_apps
.thread_active
) {
1574 ret
= pthread_cancel(global_apps
.ust_listener
);
1576 ERR("Error cancelling global ust listener thread: %s",
1579 global_apps
.thread_active
= 0;
1582 if (local_apps
.thread_active
) {
1583 ret
= pthread_cancel(local_apps
.ust_listener
);
1585 ERR("Error cancelling local ust listener thread: %s",
1588 local_apps
.thread_active
= 0;
1591 pthread_mutex_unlock(&ust_exit_mutex
);
1594 * Do NOT join threads: use of sys_futex makes it impossible to
1595 * join the threads without using async-cancel, but async-cancel
1596 * is delivered by a signal, which could hit the target thread
1597 * anywhere in its code path, including while the ust_lock() is
1598 * held, causing a deadlock for the other thread. Let the OS
1599 * cleanup the threads if there are stalled in a syscall.
1601 lttng_ust_cleanup(1);
1605 * We exclude the worker threads across fork and clone (except
1606 * CLONE_VM), because these system calls only keep the forking thread
1607 * running in the child. Therefore, we don't want to call fork or clone
1608 * in the middle of an tracepoint or ust tracing state modification.
1609 * Holding this mutex protects these structures across fork and clone.
1611 void ust_before_fork(sigset_t
*save_sigset
)
1614 * Disable signals. This is to avoid that the child intervenes
1615 * before it is properly setup for tracing. It is safer to
1616 * disable all signals, because then we know we are not breaking
1617 * anything by restoring the original mask.
1622 if (URCU_TLS(lttng_ust_nest_count
))
1624 /* Disable signals */
1625 sigfillset(&all_sigs
);
1626 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
1628 PERROR("sigprocmask");
1631 rcu_bp_before_fork();
1634 static void ust_after_fork_common(sigset_t
*restore_sigset
)
1638 DBG("process %d", getpid());
1640 /* Restore signals */
1641 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
1643 PERROR("sigprocmask");
1647 void ust_after_fork_parent(sigset_t
*restore_sigset
)
1649 if (URCU_TLS(lttng_ust_nest_count
))
1651 DBG("process %d", getpid());
1652 rcu_bp_after_fork_parent();
1653 /* Release mutexes and reenable signals */
1654 ust_after_fork_common(restore_sigset
);
1658 * After fork, in the child, we need to cleanup all the leftover state,
1659 * except the worker thread which already magically disappeared thanks
1660 * to the weird Linux fork semantics. After tyding up, we call
1661 * lttng_ust_init() again to start over as a new PID.
1663 * This is meant for forks() that have tracing in the child between the
1664 * fork and following exec call (if there is any).
1666 void ust_after_fork_child(sigset_t
*restore_sigset
)
1668 if (URCU_TLS(lttng_ust_nest_count
))
1670 DBG("process %d", getpid());
1671 /* Release urcu mutexes */
1672 rcu_bp_after_fork_child();
1673 lttng_ust_cleanup(0);
1674 lttng_context_vtid_reset();
1675 /* Release mutexes and reenable signals */
1676 ust_after_fork_common(restore_sigset
);
1680 void lttng_ust_sockinfo_session_enabled(void *owner
)
1682 struct sock_info
*sock_info
= owner
;
1683 sock_info
->statedump_pending
= 1;