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 static pthread_mutex_t ust_mutex
= PTHREAD_MUTEX_INITIALIZER
;
74 * ust_exit_mutex protects thread_active variable wrt thread exit. It
75 * cannot be done by ust_mutex because pthread_cancel(), which takes an
76 * internal libc lock, cannot nest within ust_mutex.
78 * It never nests within a ust_mutex.
80 static pthread_mutex_t ust_exit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
82 /* Should the ust comm thread quit ? */
83 static int lttng_ust_comm_should_quit
;
86 * Return 0 on success, -1 if should quilt.
87 * The lock is taken in both cases.
91 pthread_mutex_lock(&ust_mutex
);
92 if (lttng_ust_comm_should_quit
) {
100 * ust_lock_nocheck() can be used in constructors/destructors, because
101 * they are already nested within the dynamic loader lock, and therefore
102 * have exclusive access against execution of liblttng-ust destructor.
104 void ust_lock_nocheck(void)
106 pthread_mutex_lock(&ust_mutex
);
109 void ust_unlock(void)
111 pthread_mutex_unlock(&ust_mutex
);
115 * Wait for either of these before continuing to the main
117 * - the register_done message from sessiond daemon
118 * (will let the sessiond daemon enable sessions before main
120 * - sessiond daemon is not reachable.
121 * - timeout (ensuring applications are resilient to session
124 static sem_t constructor_wait
;
126 * Doing this for both the global and local sessiond.
128 static int sem_count
= { 2 };
131 * Counting nesting within lttng-ust. Used to ensure that calling fork()
132 * from liblttng-ust does not execute the pre/post fork handlers.
134 static DEFINE_URCU_TLS(int, lttng_ust_nest_count
);
137 * Info about socket and associated listener thread.
141 pthread_t ust_listener
; /* listener thread */
143 int constructor_sem_posted
;
148 char sock_path
[PATH_MAX
];
152 char wait_shm_path
[PATH_MAX
];
154 /* Keep track of lazy state dump not performed yet. */
155 int statedump_pending
;
158 /* Socket from app (connect) to session daemon (listen) for communication */
159 struct sock_info global_apps
= {
167 .sock_path
= LTTNG_DEFAULT_RUNDIR
"/" LTTNG_UST_SOCK_FILENAME
,
171 .wait_shm_path
= "/" LTTNG_UST_WAIT_FILENAME
,
173 .statedump_pending
= 0,
176 /* TODO: allow global_apps_sock_path override */
178 struct sock_info local_apps
= {
182 .allowed
= 0, /* Check setuid bit first */
188 .statedump_pending
= 0,
191 static int wait_poll_fallback
;
193 static const char *cmd_name_mapping
[] = {
194 [ LTTNG_UST_RELEASE
] = "Release",
195 [ LTTNG_UST_SESSION
] = "Create Session",
196 [ LTTNG_UST_TRACER_VERSION
] = "Get Tracer Version",
198 [ LTTNG_UST_TRACEPOINT_LIST
] = "Create Tracepoint List",
199 [ LTTNG_UST_WAIT_QUIESCENT
] = "Wait for Quiescent State",
200 [ LTTNG_UST_REGISTER_DONE
] = "Registration Done",
201 [ LTTNG_UST_TRACEPOINT_FIELD_LIST
] = "Create Tracepoint Field List",
203 /* Session FD commands */
204 [ LTTNG_UST_CHANNEL
] = "Create Channel",
205 [ LTTNG_UST_SESSION_START
] = "Start Session",
206 [ LTTNG_UST_SESSION_STOP
] = "Stop Session",
208 /* Channel FD commands */
209 [ LTTNG_UST_STREAM
] = "Create Stream",
210 [ LTTNG_UST_EVENT
] = "Create Event",
212 /* Event and Channel FD commands */
213 [ LTTNG_UST_CONTEXT
] = "Create Context",
214 [ LTTNG_UST_FLUSH_BUFFER
] = "Flush Buffer",
216 /* Event, Channel and Session commands */
217 [ LTTNG_UST_ENABLE
] = "Enable",
218 [ LTTNG_UST_DISABLE
] = "Disable",
220 /* Tracepoint list commands */
221 [ LTTNG_UST_TRACEPOINT_LIST_GET
] = "List Next Tracepoint",
222 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
] = "List Next Tracepoint Field",
224 /* Event FD commands */
225 [ LTTNG_UST_FILTER
] = "Create Filter",
226 [ LTTNG_UST_EXCLUSION
] = "Add exclusions to event",
229 static const char *str_timeout
;
230 static int got_timeout_env
;
232 extern void lttng_ring_buffer_client_overwrite_init(void);
233 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
234 extern void lttng_ring_buffer_client_discard_init(void);
235 extern void lttng_ring_buffer_client_discard_rt_init(void);
236 extern void lttng_ring_buffer_metadata_client_init(void);
237 extern void lttng_ring_buffer_client_overwrite_exit(void);
238 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
239 extern void lttng_ring_buffer_client_discard_exit(void);
240 extern void lttng_ring_buffer_client_discard_rt_exit(void);
241 extern void lttng_ring_buffer_metadata_client_exit(void);
244 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
248 const char *get_lttng_home_dir(void)
252 val
= (const char *) getenv("LTTNG_HOME");
256 return (const char *) getenv("HOME");
260 * Force a read (imply TLS fixup for dlopen) of TLS variables.
263 void lttng_fixup_nest_count_tls(void)
265 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count
)));
268 int lttng_get_notify_socket(void *owner
)
270 struct sock_info
*info
= owner
;
272 return info
->notify_socket
;
276 void print_cmd(int cmd
, int handle
)
278 const char *cmd_name
= "Unknown";
280 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
281 && cmd_name_mapping
[cmd
]) {
282 cmd_name
= cmd_name_mapping
[cmd
];
284 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
286 lttng_ust_obj_get_name(handle
), handle
);
290 int setup_local_apps(void)
292 const char *home_dir
;
297 * Disallow per-user tracing for setuid binaries.
299 if (uid
!= geteuid()) {
300 assert(local_apps
.allowed
== 0);
303 home_dir
= get_lttng_home_dir();
305 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
306 assert(local_apps
.allowed
== 0);
309 local_apps
.allowed
= 1;
310 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
312 LTTNG_DEFAULT_HOME_RUNDIR
,
313 LTTNG_UST_SOCK_FILENAME
);
314 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
315 LTTNG_UST_WAIT_FILENAME
,
321 * Get notify_sock timeout, in ms.
322 * -1: don't wait. 0: wait forever. >0: timeout, in ms.
325 long get_timeout(void)
327 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
329 if (!got_timeout_env
) {
330 str_timeout
= getenv("LTTNG_UST_REGISTER_TIMEOUT");
334 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
335 return constructor_delay_ms
;
339 long get_notify_sock_timeout(void)
341 return get_timeout();
345 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
348 int get_constructor_timeout(struct timespec
*constructor_timeout
)
350 long constructor_delay_ms
;
353 constructor_delay_ms
= get_timeout();
355 switch (constructor_delay_ms
) {
356 case -1:/* fall-through */
358 return constructor_delay_ms
;
364 * If we are unable to find the current time, don't wait.
366 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
370 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
371 constructor_timeout
->tv_nsec
+=
372 (constructor_delay_ms
% 1000UL) * 1000000UL;
373 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
374 constructor_timeout
->tv_sec
++;
375 constructor_timeout
->tv_nsec
-= 1000000000UL;
381 int register_to_sessiond(int socket
, enum ustctl_socket_type type
)
383 return ustcomm_send_reg_msg(socket
,
386 lttng_alignof(uint8_t) * CHAR_BIT
,
387 lttng_alignof(uint16_t) * CHAR_BIT
,
388 lttng_alignof(uint32_t) * CHAR_BIT
,
389 lttng_alignof(uint64_t) * CHAR_BIT
,
390 lttng_alignof(unsigned long) * CHAR_BIT
);
394 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
398 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
401 DBG("message successfully sent");
404 if (len
== -ECONNRESET
) {
405 DBG("remote end closed connection");
410 DBG("incorrect message size: %zd", len
);
416 int handle_register_done(struct sock_info
*sock_info
)
420 if (sock_info
->constructor_sem_posted
)
422 sock_info
->constructor_sem_posted
= 1;
423 if (uatomic_read(&sem_count
) <= 0) {
426 ret
= uatomic_add_return(&sem_count
, -1);
428 ret
= sem_post(&constructor_wait
);
435 * Only execute pending statedump after the constructor semaphore has
436 * been posted by each listener thread. This means statedump will only
437 * be performed after the "registration done" command is received from
438 * each session daemon the application is connected to.
440 * This ensures we don't run into deadlock issues with the dynamic
441 * loader mutex, which is held while the constructor is called and
442 * waiting on the constructor semaphore. All operations requiring this
443 * dynamic loader lock need to be postponed using this mechanism.
446 void handle_pending_statedump(struct sock_info
*sock_info
)
448 int ctor_passed
= sock_info
->constructor_sem_posted
;
450 if (ctor_passed
&& sock_info
->statedump_pending
) {
451 sock_info
->statedump_pending
= 0;
452 lttng_handle_pending_statedump(sock_info
);
457 int handle_message(struct sock_info
*sock_info
,
458 int sock
, struct ustcomm_ust_msg
*lum
)
461 const struct lttng_ust_objd_ops
*ops
;
462 struct ustcomm_ust_reply lur
;
466 memset(&lur
, 0, sizeof(lur
));
469 ret
= -LTTNG_UST_ERR_EXITING
;
473 ops
= objd_ops(lum
->handle
);
480 case LTTNG_UST_REGISTER_DONE
:
481 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
482 ret
= handle_register_done(sock_info
);
486 case LTTNG_UST_RELEASE
:
487 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
490 ret
= lttng_ust_objd_unref(lum
->handle
, 1);
492 case LTTNG_UST_FILTER
:
494 /* Receive filter data */
495 struct lttng_ust_filter_bytecode_node
*bytecode
;
497 if (lum
->u
.filter
.data_size
> FILTER_BYTECODE_MAX_LEN
) {
498 ERR("Filter data size is too large: %u bytes",
499 lum
->u
.filter
.data_size
);
504 if (lum
->u
.filter
.reloc_offset
> lum
->u
.filter
.data_size
) {
505 ERR("Filter reloc offset %u is not within data",
506 lum
->u
.filter
.reloc_offset
);
511 bytecode
= zmalloc(sizeof(*bytecode
) + lum
->u
.filter
.data_size
);
516 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
,
517 lum
->u
.filter
.data_size
);
519 case 0: /* orderly shutdown */
524 if (len
== lum
->u
.filter
.data_size
) {
525 DBG("filter data received");
527 } else if (len
< 0) {
528 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
529 if (len
== -ECONNRESET
) {
530 ERR("%s remote end closed connection", sock_info
->name
);
539 DBG("incorrect filter data message size: %zd", len
);
545 bytecode
->bc
.len
= lum
->u
.filter
.data_size
;
546 bytecode
->bc
.reloc_offset
= lum
->u
.filter
.reloc_offset
;
547 bytecode
->bc
.seqnum
= lum
->u
.filter
.seqnum
;
549 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
550 (unsigned long) bytecode
,
555 /* don't free bytecode if everything went fine. */
562 case LTTNG_UST_EXCLUSION
:
564 /* Receive exclusion names */
565 struct lttng_ust_excluder_node
*node
;
568 count
= lum
->u
.exclusion
.count
;
570 /* There are no names to read */
574 node
= zmalloc(sizeof(*node
) +
575 count
* LTTNG_UST_SYM_NAME_LEN
);
580 node
->excluder
.count
= count
;
581 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
582 count
* LTTNG_UST_SYM_NAME_LEN
);
584 case 0: /* orderly shutdown */
589 if (len
== count
* LTTNG_UST_SYM_NAME_LEN
) {
590 DBG("Exclusion data received");
592 } else if (len
< 0) {
593 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
594 if (len
== -ECONNRESET
) {
595 ERR("%s remote end closed connection", sock_info
->name
);
604 DBG("Incorrect exclusion data message size: %zd", len
);
611 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
612 (unsigned long) node
,
617 /* Don't free exclusion data if everything went fine. */
624 case LTTNG_UST_CHANNEL
:
629 len
= ustcomm_recv_channel_from_sessiond(sock
,
630 &chan_data
, lum
->u
.channel
.len
,
633 case 0: /* orderly shutdown */
637 if (len
== lum
->u
.channel
.len
) {
638 DBG("channel data received");
640 } else if (len
< 0) {
641 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
642 if (len
== -ECONNRESET
) {
643 ERR("%s remote end closed connection", sock_info
->name
);
650 DBG("incorrect channel data message size: %zd", len
);
655 args
.channel
.chan_data
= chan_data
;
656 args
.channel
.wakeup_fd
= wakeup_fd
;
658 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
659 (unsigned long) &lum
->u
,
665 case LTTNG_UST_STREAM
:
667 /* Receive shm_fd, wakeup_fd */
668 ret
= ustcomm_recv_stream_from_sessiond(sock
,
671 &args
.stream
.wakeup_fd
);
676 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
677 (unsigned long) &lum
->u
,
685 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
686 (unsigned long) &lum
->u
,
694 lur
.handle
= lum
->handle
;
698 lur
.ret_code
= LTTNG_UST_OK
;
701 * Use -LTTNG_UST_ERR as wildcard for UST internal
702 * error that are not caused by the transport, except if
703 * we already have a more precise error message to
706 if (ret
> -LTTNG_UST_ERR
) {
707 /* Translate code to UST error. */
710 lur
.ret_code
= -LTTNG_UST_ERR_EXIST
;
713 lur
.ret_code
= -LTTNG_UST_ERR_INVAL
;
716 lur
.ret_code
= -LTTNG_UST_ERR_NOENT
;
719 lur
.ret_code
= -LTTNG_UST_ERR_PERM
;
722 lur
.ret_code
= -LTTNG_UST_ERR_NOSYS
;
725 lur
.ret_code
= -LTTNG_UST_ERR
;
734 case LTTNG_UST_TRACER_VERSION
:
735 lur
.u
.version
= lum
->u
.version
;
737 case LTTNG_UST_TRACEPOINT_LIST_GET
:
738 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
742 DBG("Return value: %d", lur
.ret_val
);
743 ret
= send_reply(sock
, &lur
);
745 DBG("error sending reply");
750 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
753 if (lur
.ret_code
== LTTNG_UST_OK
) {
755 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
:
756 len
= ustcomm_send_unix_sock(sock
,
757 &args
.field_list
.entry
,
758 sizeof(args
.field_list
.entry
));
763 if (len
!= sizeof(args
.field_list
.entry
)) {
774 * Performed delayed statedump operations outside of the UST
775 * lock. We need to take the dynamic loader lock before we take
776 * the UST lock internally within handle_pending_statedump().
778 handle_pending_statedump(sock_info
);
784 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
788 if (sock_info
->root_handle
!= -1) {
789 ret
= lttng_ust_objd_unref(sock_info
->root_handle
, 1);
791 ERR("Error unref root handle");
793 sock_info
->root_handle
= -1;
795 sock_info
->constructor_sem_posted
= 0;
798 * wait_shm_mmap, socket and notify socket are used by listener
799 * threads outside of the ust lock, so we cannot tear them down
800 * ourselves, because we cannot join on these threads. Leave
801 * responsibility of cleaning up these resources to the OS
807 if (sock_info
->socket
!= -1) {
808 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
810 ERR("Error closing ust cmd socket");
812 sock_info
->socket
= -1;
814 if (sock_info
->notify_socket
!= -1) {
815 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
817 ERR("Error closing ust notify socket");
819 sock_info
->notify_socket
= -1;
821 if (sock_info
->wait_shm_mmap
) {
824 page_size
= sysconf(_SC_PAGE_SIZE
);
826 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
828 ERR("Error unmapping wait shm");
831 sock_info
->wait_shm_mmap
= NULL
;
836 * Using fork to set umask in the child process (not multi-thread safe).
837 * We deal with the shm_open vs ftruncate race (happening when the
838 * sessiond owns the shm and does not let everybody modify it, to ensure
839 * safety against shm_unlink) by simply letting the mmap fail and
840 * retrying after a few seconds.
841 * For global shm, everybody has rw access to it until the sessiond
845 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
847 int wait_shm_fd
, ret
;
851 * Try to open read-only.
853 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
854 if (wait_shm_fd
>= 0) {
857 size_t bytes_read
= 0;
860 * Try to read the fd. If unable to do so, try opening
864 len
= read(wait_shm_fd
,
865 &((char *) &tmp_read
)[bytes_read
],
866 sizeof(tmp_read
) - bytes_read
);
870 } while ((len
< 0 && errno
== EINTR
)
871 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
872 if (bytes_read
!= sizeof(tmp_read
)) {
873 ret
= close(wait_shm_fd
);
875 ERR("close wait_shm_fd");
880 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
882 * Real-only open did not work, and it's not because the
883 * entry was not present. It's a failure that prohibits
886 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
892 * If the open failed because the file did not exist, or because
893 * the file was not truncated yet, try creating it ourself.
895 URCU_TLS(lttng_ust_nest_count
)++;
897 URCU_TLS(lttng_ust_nest_count
)--;
902 * Parent: wait for child to return, in which case the
903 * shared memory map will have been created.
906 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
911 * Try to open read-only again after creation.
913 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
914 if (wait_shm_fd
< 0) {
916 * Real-only open did not work. It's a failure
917 * that prohibits using shm.
919 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
923 } else if (pid
== 0) {
927 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
928 if (sock_info
->global
)
929 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
931 * We're alone in a child process, so we can modify the
932 * process-wide umask.
936 * Try creating shm (or get rw access).
937 * We don't do an exclusive open, because we allow other
938 * processes to create+ftruncate it concurrently.
940 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
941 O_RDWR
| O_CREAT
, create_mode
);
942 if (wait_shm_fd
>= 0) {
943 ret
= ftruncate(wait_shm_fd
, mmap_size
);
951 * For local shm, we need to have rw access to accept
952 * opening it: this means the local sessiond will be
953 * able to wake us up. For global shm, we open it even
954 * if rw access is not granted, because the root.root
955 * sessiond will be able to override all rights and wake
958 if (!sock_info
->global
&& errno
!= EACCES
) {
959 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
963 * The shm exists, but we cannot open it RW. Report
971 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
975 * Ensure that our user is the owner of the shm file for
976 * local shm. If we do not own the file, it means our
977 * sessiond will not have access to wake us up (there is
978 * probably a rogue process trying to fake our
979 * sessiond). Fallback to polling method in this case.
981 ret
= fstat(wait_shm_fd
, &statbuf
);
986 if (statbuf
.st_uid
!= getuid())
992 ret
= close(wait_shm_fd
);
994 PERROR("Error closing fd");
1000 char *get_map_shm(struct sock_info
*sock_info
)
1003 int wait_shm_fd
, ret
;
1004 char *wait_shm_mmap
;
1006 page_size
= sysconf(_SC_PAGE_SIZE
);
1007 if (page_size
< 0) {
1011 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1012 if (wait_shm_fd
< 0) {
1015 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1016 MAP_SHARED
, wait_shm_fd
, 0);
1017 /* close shm fd immediately after taking the mmap reference */
1018 ret
= close(wait_shm_fd
);
1020 PERROR("Error closing fd");
1022 if (wait_shm_mmap
== MAP_FAILED
) {
1023 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1026 return wait_shm_mmap
;
1033 void wait_for_sessiond(struct sock_info
*sock_info
)
1040 if (wait_poll_fallback
) {
1043 if (!sock_info
->wait_shm_mmap
) {
1044 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
1045 if (!sock_info
->wait_shm_mmap
)
1050 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1051 /* Wait for futex wakeup */
1052 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
) == 0) {
1053 ret
= futex_async((int32_t *) sock_info
->wait_shm_mmap
,
1054 FUTEX_WAIT
, 0, NULL
, NULL
, 0);
1056 if (errno
== EFAULT
) {
1057 wait_poll_fallback
= 1;
1059 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1060 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1061 "Please upgrade your kernel "
1062 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1063 "mainline). LTTng-UST will use polling mode fallback.");
1081 * This thread does not allocate any resource, except within
1082 * handle_message, within mutex protection. This mutex protects against
1084 * The other moment it allocates resources is at socket connection, which
1085 * is also protected by the mutex.
1088 void *ust_listener_thread(void *arg
)
1090 struct sock_info
*sock_info
= arg
;
1091 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
1094 /* Restart trying to connect to the session daemon */
1096 if (prev_connect_failed
) {
1097 /* Wait for sessiond availability with pipe */
1098 wait_for_sessiond(sock_info
);
1102 * Sleep for 5 seconds before retrying after a
1103 * sequence of failure / wait / failure. This
1104 * deals with a killed or broken session daemon.
1109 prev_connect_failed
= 0;
1112 if (sock_info
->socket
!= -1) {
1113 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1115 ERR("Error closing %s ust cmd socket",
1118 sock_info
->socket
= -1;
1120 if (sock_info
->notify_socket
!= -1) {
1121 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1123 ERR("Error closing %s ust notify socket",
1126 sock_info
->notify_socket
= -1;
1130 * Register. We need to perform both connect and sending
1131 * registration message before doing the next connect otherwise
1132 * we may reach unix socket connect queue max limits and block
1133 * on the 2nd connect while the session daemon is awaiting the
1134 * first connect registration message.
1136 /* Connect cmd socket */
1137 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1139 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1140 prev_connect_failed
= 1;
1147 * If we cannot find the sessiond daemon, don't delay
1148 * constructor execution.
1150 ret
= handle_register_done(sock_info
);
1155 sock_info
->socket
= ret
;
1162 * Create only one root handle per listener thread for the whole
1163 * process lifetime, so we ensure we get ID which is statically
1164 * assigned to the root handle.
1166 if (sock_info
->root_handle
== -1) {
1167 ret
= lttng_abi_create_root_handle();
1169 ERR("Error creating root handle");
1172 sock_info
->root_handle
= ret
;
1175 ret
= register_to_sessiond(sock_info
->socket
, USTCTL_SOCKET_CMD
);
1177 ERR("Error registering to %s ust cmd socket",
1179 prev_connect_failed
= 1;
1181 * If we cannot register to the sessiond daemon, don't
1182 * delay constructor execution.
1184 ret
= handle_register_done(sock_info
);
1192 /* Connect notify socket */
1193 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1195 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1196 prev_connect_failed
= 1;
1203 * If we cannot find the sessiond daemon, don't delay
1204 * constructor execution.
1206 ret
= handle_register_done(sock_info
);
1211 sock_info
->notify_socket
= ret
;
1213 timeout
= get_notify_sock_timeout();
1216 * Give at least 10ms to sessiond to reply to
1221 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
1224 WARN("Error setting socket receive timeout");
1226 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
1229 WARN("Error setting socket send timeout");
1231 } else if (timeout
< -1) {
1232 WARN("Unsupported timeout value %ld", timeout
);
1239 ret
= register_to_sessiond(sock_info
->notify_socket
,
1240 USTCTL_SOCKET_NOTIFY
);
1242 ERR("Error registering to %s ust notify socket",
1244 prev_connect_failed
= 1;
1246 * If we cannot register to the sessiond daemon, don't
1247 * delay constructor execution.
1249 ret
= handle_register_done(sock_info
);
1254 sock
= sock_info
->socket
;
1260 struct ustcomm_ust_msg lum
;
1262 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
1264 case 0: /* orderly shutdown */
1265 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
1270 * Either sessiond has shutdown or refused us by closing the socket.
1271 * In either case, we don't want to delay construction execution,
1272 * and we need to wait before retry.
1274 prev_connect_failed
= 1;
1276 * If we cannot register to the sessiond daemon, don't
1277 * delay constructor execution.
1279 ret
= handle_register_done(sock_info
);
1284 print_cmd(lum
.cmd
, lum
.handle
);
1285 ret
= handle_message(sock_info
, sock
, &lum
);
1287 ERR("Error handling message for %s socket", sock_info
->name
);
1292 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1294 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
1296 if (len
== -ECONNRESET
) {
1297 DBG("%s remote end closed connection", sock_info
->name
);
1308 /* Cleanup socket handles before trying to reconnect */
1309 lttng_ust_objd_table_owner_cleanup(sock_info
);
1311 goto restart
; /* try to reconnect */
1316 pthread_mutex_lock(&ust_exit_mutex
);
1317 sock_info
->thread_active
= 0;
1318 pthread_mutex_unlock(&ust_exit_mutex
);
1323 * Weak symbol to call when the ust malloc wrapper is not loaded.
1325 __attribute__((weak
))
1326 void lttng_ust_malloc_wrapper_init(void)
1331 * sessiond monitoring thread: monitor presence of global and per-user
1332 * sessiond by polling the application common named pipe.
1334 void __attribute__((constructor
)) lttng_ust_init(void)
1336 struct timespec constructor_timeout
;
1337 sigset_t sig_all_blocked
, orig_parent_mask
;
1338 pthread_attr_t thread_attr
;
1342 if (uatomic_xchg(&initialized
, 1) == 1)
1346 * Fixup interdependency between TLS fixup mutex (which happens
1347 * to be the dynamic linker mutex) and ust_lock, taken within
1350 lttng_fixup_ringbuffer_tls();
1351 lttng_fixup_vtid_tls();
1352 lttng_fixup_nest_count_tls();
1353 lttng_fixup_procname_tls();
1356 * We want precise control over the order in which we construct
1357 * our sub-libraries vs starting to receive commands from
1358 * sessiond (otherwise leading to errors when trying to create
1359 * sessiond before the init functions are completed).
1363 lttng_ust_baddr_statedump_init();
1364 lttng_ring_buffer_metadata_client_init();
1365 lttng_ring_buffer_client_overwrite_init();
1366 lttng_ring_buffer_client_overwrite_rt_init();
1367 lttng_ring_buffer_client_discard_init();
1368 lttng_ring_buffer_client_discard_rt_init();
1369 lttng_context_init();
1371 * Invoke ust malloc wrapper init before starting other threads.
1373 lttng_ust_malloc_wrapper_init();
1375 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
1377 ret
= sem_init(&constructor_wait
, 0, 0);
1380 ret
= setup_local_apps();
1382 DBG("local apps setup returned %d", ret
);
1385 /* A new thread created by pthread_create inherits the signal mask
1386 * from the parent. To avoid any signal being received by the
1387 * listener thread, we block all signals temporarily in the parent,
1388 * while we create the listener thread.
1390 sigfillset(&sig_all_blocked
);
1391 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
1393 ERR("pthread_sigmask: %s", strerror(ret
));
1396 ret
= pthread_attr_init(&thread_attr
);
1398 ERR("pthread_attr_init: %s", strerror(ret
));
1400 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
1402 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
1405 pthread_mutex_lock(&ust_exit_mutex
);
1406 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
1407 ust_listener_thread
, &global_apps
);
1409 ERR("pthread_create global: %s", strerror(ret
));
1411 global_apps
.thread_active
= 1;
1412 pthread_mutex_unlock(&ust_exit_mutex
);
1414 if (local_apps
.allowed
) {
1415 pthread_mutex_lock(&ust_exit_mutex
);
1416 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
1417 ust_listener_thread
, &local_apps
);
1419 ERR("pthread_create local: %s", strerror(ret
));
1421 local_apps
.thread_active
= 1;
1422 pthread_mutex_unlock(&ust_exit_mutex
);
1424 handle_register_done(&local_apps
);
1426 ret
= pthread_attr_destroy(&thread_attr
);
1428 ERR("pthread_attr_destroy: %s", strerror(ret
));
1431 /* Restore original signal mask in parent */
1432 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
1434 ERR("pthread_sigmask: %s", strerror(ret
));
1437 switch (timeout_mode
) {
1438 case 1: /* timeout wait */
1440 ret
= sem_timedwait(&constructor_wait
,
1441 &constructor_timeout
);
1442 } while (ret
< 0 && errno
== EINTR
);
1443 if (ret
< 0 && errno
== ETIMEDOUT
) {
1444 ERR("Timed out waiting for lttng-sessiond");
1449 case -1:/* wait forever */
1451 ret
= sem_wait(&constructor_wait
);
1452 } while (ret
< 0 && errno
== EINTR
);
1455 case 0: /* no timeout */
1461 void lttng_ust_cleanup(int exiting
)
1463 cleanup_sock_info(&global_apps
, exiting
);
1464 if (local_apps
.allowed
) {
1465 cleanup_sock_info(&local_apps
, exiting
);
1468 * The teardown in this function all affect data structures
1469 * accessed under the UST lock by the listener thread. This
1470 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1471 * that none of these threads are accessing this data at this
1474 lttng_ust_abi_exit();
1475 lttng_ust_events_exit();
1476 lttng_context_exit();
1477 lttng_ring_buffer_client_discard_rt_exit();
1478 lttng_ring_buffer_client_discard_exit();
1479 lttng_ring_buffer_client_overwrite_rt_exit();
1480 lttng_ring_buffer_client_overwrite_exit();
1481 lttng_ring_buffer_metadata_client_exit();
1482 lttng_ust_baddr_statedump_destroy();
1485 /* Reinitialize values for fork */
1487 lttng_ust_comm_should_quit
= 0;
1492 void __attribute__((destructor
)) lttng_ust_exit(void)
1497 * Using pthread_cancel here because:
1498 * A) we don't want to hang application teardown.
1499 * B) the thread is not allocating any resource.
1503 * Require the communication thread to quit. Synchronize with
1504 * mutexes to ensure it is not in a mutex critical section when
1505 * pthread_cancel is later called.
1508 lttng_ust_comm_should_quit
= 1;
1511 pthread_mutex_lock(&ust_exit_mutex
);
1512 /* cancel threads */
1513 if (global_apps
.thread_active
) {
1514 ret
= pthread_cancel(global_apps
.ust_listener
);
1516 ERR("Error cancelling global ust listener thread: %s",
1519 global_apps
.thread_active
= 0;
1522 if (local_apps
.thread_active
) {
1523 ret
= pthread_cancel(local_apps
.ust_listener
);
1525 ERR("Error cancelling local ust listener thread: %s",
1528 local_apps
.thread_active
= 0;
1531 pthread_mutex_unlock(&ust_exit_mutex
);
1534 * Do NOT join threads: use of sys_futex makes it impossible to
1535 * join the threads without using async-cancel, but async-cancel
1536 * is delivered by a signal, which could hit the target thread
1537 * anywhere in its code path, including while the ust_lock() is
1538 * held, causing a deadlock for the other thread. Let the OS
1539 * cleanup the threads if there are stalled in a syscall.
1541 lttng_ust_cleanup(1);
1545 * We exclude the worker threads across fork and clone (except
1546 * CLONE_VM), because these system calls only keep the forking thread
1547 * running in the child. Therefore, we don't want to call fork or clone
1548 * in the middle of an tracepoint or ust tracing state modification.
1549 * Holding this mutex protects these structures across fork and clone.
1551 void ust_before_fork(sigset_t
*save_sigset
)
1554 * Disable signals. This is to avoid that the child intervenes
1555 * before it is properly setup for tracing. It is safer to
1556 * disable all signals, because then we know we are not breaking
1557 * anything by restoring the original mask.
1562 if (URCU_TLS(lttng_ust_nest_count
))
1564 /* Disable signals */
1565 sigfillset(&all_sigs
);
1566 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
1568 PERROR("sigprocmask");
1571 rcu_bp_before_fork();
1574 static void ust_after_fork_common(sigset_t
*restore_sigset
)
1578 DBG("process %d", getpid());
1580 /* Restore signals */
1581 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
1583 PERROR("sigprocmask");
1587 void ust_after_fork_parent(sigset_t
*restore_sigset
)
1589 if (URCU_TLS(lttng_ust_nest_count
))
1591 DBG("process %d", getpid());
1592 rcu_bp_after_fork_parent();
1593 /* Release mutexes and reenable signals */
1594 ust_after_fork_common(restore_sigset
);
1598 * After fork, in the child, we need to cleanup all the leftover state,
1599 * except the worker thread which already magically disappeared thanks
1600 * to the weird Linux fork semantics. After tyding up, we call
1601 * lttng_ust_init() again to start over as a new PID.
1603 * This is meant for forks() that have tracing in the child between the
1604 * fork and following exec call (if there is any).
1606 void ust_after_fork_child(sigset_t
*restore_sigset
)
1608 if (URCU_TLS(lttng_ust_nest_count
))
1610 DBG("process %d", getpid());
1611 /* Release urcu mutexes */
1612 rcu_bp_after_fork_child();
1613 lttng_ust_cleanup(0);
1614 lttng_context_vtid_reset();
1615 /* Release mutexes and reenable signals */
1616 ust_after_fork_common(restore_sigset
);
1620 void lttng_ust_sockinfo_session_enabled(void *owner
)
1622 struct sock_info
*sock_info
= owner
;
1623 sock_info
->statedump_pending
= 1;