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
)));
272 void lttng_fixup_urcu_bp_tls(void)
278 int lttng_get_notify_socket(void *owner
)
280 struct sock_info
*info
= owner
;
282 return info
->notify_socket
;
286 void print_cmd(int cmd
, int handle
)
288 const char *cmd_name
= "Unknown";
290 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
291 && cmd_name_mapping
[cmd
]) {
292 cmd_name
= cmd_name_mapping
[cmd
];
294 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
296 lttng_ust_obj_get_name(handle
), handle
);
300 int setup_local_apps(void)
302 const char *home_dir
;
307 * Disallow per-user tracing for setuid binaries.
309 if (uid
!= geteuid()) {
310 assert(local_apps
.allowed
== 0);
313 home_dir
= get_lttng_home_dir();
315 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
316 assert(local_apps
.allowed
== 0);
319 local_apps
.allowed
= 1;
320 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
322 LTTNG_DEFAULT_HOME_RUNDIR
,
323 LTTNG_UST_SOCK_FILENAME
);
324 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
325 LTTNG_UST_WAIT_FILENAME
,
331 * Get notify_sock timeout, in ms.
332 * -1: don't wait. 0: wait forever. >0: timeout, in ms.
335 long get_timeout(void)
337 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
339 if (!got_timeout_env
) {
340 str_timeout
= getenv("LTTNG_UST_REGISTER_TIMEOUT");
344 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
345 return constructor_delay_ms
;
349 long get_notify_sock_timeout(void)
351 return get_timeout();
355 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
358 int get_constructor_timeout(struct timespec
*constructor_timeout
)
360 long constructor_delay_ms
;
363 constructor_delay_ms
= get_timeout();
365 switch (constructor_delay_ms
) {
366 case -1:/* fall-through */
368 return constructor_delay_ms
;
374 * If we are unable to find the current time, don't wait.
376 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
380 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
381 constructor_timeout
->tv_nsec
+=
382 (constructor_delay_ms
% 1000UL) * 1000000UL;
383 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
384 constructor_timeout
->tv_sec
++;
385 constructor_timeout
->tv_nsec
-= 1000000000UL;
391 int register_to_sessiond(int socket
, enum ustctl_socket_type type
)
393 return ustcomm_send_reg_msg(socket
,
396 lttng_alignof(uint8_t) * CHAR_BIT
,
397 lttng_alignof(uint16_t) * CHAR_BIT
,
398 lttng_alignof(uint32_t) * CHAR_BIT
,
399 lttng_alignof(uint64_t) * CHAR_BIT
,
400 lttng_alignof(unsigned long) * CHAR_BIT
);
404 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
408 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
411 DBG("message successfully sent");
414 if (len
== -ECONNRESET
) {
415 DBG("remote end closed connection");
420 DBG("incorrect message size: %zd", len
);
426 int handle_register_done(struct sock_info
*sock_info
)
430 if (sock_info
->constructor_sem_posted
)
432 sock_info
->constructor_sem_posted
= 1;
433 if (uatomic_read(&sem_count
) <= 0) {
436 ret
= uatomic_add_return(&sem_count
, -1);
438 ret
= sem_post(&constructor_wait
);
445 * Only execute pending statedump after the constructor semaphore has
446 * been posted by each listener thread. This means statedump will only
447 * be performed after the "registration done" command is received from
448 * each session daemon the application is connected to.
450 * This ensures we don't run into deadlock issues with the dynamic
451 * loader mutex, which is held while the constructor is called and
452 * waiting on the constructor semaphore. All operations requiring this
453 * dynamic loader lock need to be postponed using this mechanism.
456 void handle_pending_statedump(struct sock_info
*sock_info
)
458 int ctor_passed
= sock_info
->constructor_sem_posted
;
460 if (ctor_passed
&& sock_info
->statedump_pending
) {
461 sock_info
->statedump_pending
= 0;
462 lttng_handle_pending_statedump(sock_info
);
467 int handle_message(struct sock_info
*sock_info
,
468 int sock
, struct ustcomm_ust_msg
*lum
)
471 const struct lttng_ust_objd_ops
*ops
;
472 struct ustcomm_ust_reply lur
;
476 memset(&lur
, 0, sizeof(lur
));
479 ret
= -LTTNG_UST_ERR_EXITING
;
483 ops
= objd_ops(lum
->handle
);
490 case LTTNG_UST_REGISTER_DONE
:
491 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
492 ret
= handle_register_done(sock_info
);
496 case LTTNG_UST_RELEASE
:
497 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
500 ret
= lttng_ust_objd_unref(lum
->handle
, 1);
502 case LTTNG_UST_FILTER
:
504 /* Receive filter data */
505 struct lttng_ust_filter_bytecode_node
*bytecode
;
507 if (lum
->u
.filter
.data_size
> FILTER_BYTECODE_MAX_LEN
) {
508 ERR("Filter data size is too large: %u bytes",
509 lum
->u
.filter
.data_size
);
514 if (lum
->u
.filter
.reloc_offset
> lum
->u
.filter
.data_size
) {
515 ERR("Filter reloc offset %u is not within data",
516 lum
->u
.filter
.reloc_offset
);
521 bytecode
= zmalloc(sizeof(*bytecode
) + lum
->u
.filter
.data_size
);
526 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
,
527 lum
->u
.filter
.data_size
);
529 case 0: /* orderly shutdown */
534 if (len
== lum
->u
.filter
.data_size
) {
535 DBG("filter data received");
537 } else if (len
< 0) {
538 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
539 if (len
== -ECONNRESET
) {
540 ERR("%s remote end closed connection", sock_info
->name
);
549 DBG("incorrect filter data message size: %zd", len
);
555 bytecode
->bc
.len
= lum
->u
.filter
.data_size
;
556 bytecode
->bc
.reloc_offset
= lum
->u
.filter
.reloc_offset
;
557 bytecode
->bc
.seqnum
= lum
->u
.filter
.seqnum
;
559 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
560 (unsigned long) bytecode
,
565 /* don't free bytecode if everything went fine. */
572 case LTTNG_UST_EXCLUSION
:
574 /* Receive exclusion names */
575 struct lttng_ust_excluder_node
*node
;
578 count
= lum
->u
.exclusion
.count
;
580 /* There are no names to read */
584 node
= zmalloc(sizeof(*node
) +
585 count
* LTTNG_UST_SYM_NAME_LEN
);
590 node
->excluder
.count
= count
;
591 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
592 count
* LTTNG_UST_SYM_NAME_LEN
);
594 case 0: /* orderly shutdown */
599 if (len
== count
* LTTNG_UST_SYM_NAME_LEN
) {
600 DBG("Exclusion data received");
602 } else if (len
< 0) {
603 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
604 if (len
== -ECONNRESET
) {
605 ERR("%s remote end closed connection", sock_info
->name
);
614 DBG("Incorrect exclusion data message size: %zd", len
);
621 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
622 (unsigned long) node
,
627 /* Don't free exclusion data if everything went fine. */
634 case LTTNG_UST_CHANNEL
:
639 len
= ustcomm_recv_channel_from_sessiond(sock
,
640 &chan_data
, lum
->u
.channel
.len
,
643 case 0: /* orderly shutdown */
647 if (len
== lum
->u
.channel
.len
) {
648 DBG("channel data received");
650 } else if (len
< 0) {
651 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
652 if (len
== -ECONNRESET
) {
653 ERR("%s remote end closed connection", sock_info
->name
);
660 DBG("incorrect channel data message size: %zd", len
);
665 args
.channel
.chan_data
= chan_data
;
666 args
.channel
.wakeup_fd
= wakeup_fd
;
668 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
669 (unsigned long) &lum
->u
,
675 case LTTNG_UST_STREAM
:
677 /* Receive shm_fd, wakeup_fd */
678 ret
= ustcomm_recv_stream_from_sessiond(sock
,
681 &args
.stream
.wakeup_fd
);
686 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
687 (unsigned long) &lum
->u
,
695 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
696 (unsigned long) &lum
->u
,
704 lur
.handle
= lum
->handle
;
708 lur
.ret_code
= LTTNG_UST_OK
;
711 * Use -LTTNG_UST_ERR as wildcard for UST internal
712 * error that are not caused by the transport, except if
713 * we already have a more precise error message to
716 if (ret
> -LTTNG_UST_ERR
) {
717 /* Translate code to UST error. */
720 lur
.ret_code
= -LTTNG_UST_ERR_EXIST
;
723 lur
.ret_code
= -LTTNG_UST_ERR_INVAL
;
726 lur
.ret_code
= -LTTNG_UST_ERR_NOENT
;
729 lur
.ret_code
= -LTTNG_UST_ERR_PERM
;
732 lur
.ret_code
= -LTTNG_UST_ERR_NOSYS
;
735 lur
.ret_code
= -LTTNG_UST_ERR
;
744 case LTTNG_UST_TRACER_VERSION
:
745 lur
.u
.version
= lum
->u
.version
;
747 case LTTNG_UST_TRACEPOINT_LIST_GET
:
748 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
752 DBG("Return value: %d", lur
.ret_val
);
753 ret
= send_reply(sock
, &lur
);
755 DBG("error sending reply");
760 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
763 if (lur
.ret_code
== LTTNG_UST_OK
) {
765 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
:
766 len
= ustcomm_send_unix_sock(sock
,
767 &args
.field_list
.entry
,
768 sizeof(args
.field_list
.entry
));
773 if (len
!= sizeof(args
.field_list
.entry
)) {
784 * Performed delayed statedump operations outside of the UST
785 * lock. We need to take the dynamic loader lock before we take
786 * the UST lock internally within handle_pending_statedump().
788 handle_pending_statedump(sock_info
);
794 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
798 if (sock_info
->root_handle
!= -1) {
799 ret
= lttng_ust_objd_unref(sock_info
->root_handle
, 1);
801 ERR("Error unref root handle");
803 sock_info
->root_handle
= -1;
805 sock_info
->constructor_sem_posted
= 0;
808 * wait_shm_mmap, socket and notify socket are used by listener
809 * threads outside of the ust lock, so we cannot tear them down
810 * ourselves, because we cannot join on these threads. Leave
811 * responsibility of cleaning up these resources to the OS
817 if (sock_info
->socket
!= -1) {
818 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
820 ERR("Error closing ust cmd socket");
822 sock_info
->socket
= -1;
824 if (sock_info
->notify_socket
!= -1) {
825 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
827 ERR("Error closing ust notify socket");
829 sock_info
->notify_socket
= -1;
831 if (sock_info
->wait_shm_mmap
) {
834 page_size
= sysconf(_SC_PAGE_SIZE
);
836 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
838 ERR("Error unmapping wait shm");
841 sock_info
->wait_shm_mmap
= NULL
;
846 * Using fork to set umask in the child process (not multi-thread safe).
847 * We deal with the shm_open vs ftruncate race (happening when the
848 * sessiond owns the shm and does not let everybody modify it, to ensure
849 * safety against shm_unlink) by simply letting the mmap fail and
850 * retrying after a few seconds.
851 * For global shm, everybody has rw access to it until the sessiond
855 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
857 int wait_shm_fd
, ret
;
861 * Try to open read-only.
863 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
864 if (wait_shm_fd
>= 0) {
867 size_t bytes_read
= 0;
870 * Try to read the fd. If unable to do so, try opening
874 len
= read(wait_shm_fd
,
875 &((char *) &tmp_read
)[bytes_read
],
876 sizeof(tmp_read
) - bytes_read
);
880 } while ((len
< 0 && errno
== EINTR
)
881 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
882 if (bytes_read
!= sizeof(tmp_read
)) {
883 ret
= close(wait_shm_fd
);
885 ERR("close wait_shm_fd");
890 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
892 * Real-only open did not work, and it's not because the
893 * entry was not present. It's a failure that prohibits
896 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
902 * If the open failed because the file did not exist, or because
903 * the file was not truncated yet, try creating it ourself.
905 URCU_TLS(lttng_ust_nest_count
)++;
907 URCU_TLS(lttng_ust_nest_count
)--;
912 * Parent: wait for child to return, in which case the
913 * shared memory map will have been created.
916 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
921 * Try to open read-only again after creation.
923 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
924 if (wait_shm_fd
< 0) {
926 * Real-only open did not work. It's a failure
927 * that prohibits using shm.
929 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
933 } else if (pid
== 0) {
937 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
938 if (sock_info
->global
)
939 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
941 * We're alone in a child process, so we can modify the
942 * process-wide umask.
946 * Try creating shm (or get rw access).
947 * We don't do an exclusive open, because we allow other
948 * processes to create+ftruncate it concurrently.
950 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
951 O_RDWR
| O_CREAT
, create_mode
);
952 if (wait_shm_fd
>= 0) {
953 ret
= ftruncate(wait_shm_fd
, mmap_size
);
961 * For local shm, we need to have rw access to accept
962 * opening it: this means the local sessiond will be
963 * able to wake us up. For global shm, we open it even
964 * if rw access is not granted, because the root.root
965 * sessiond will be able to override all rights and wake
968 if (!sock_info
->global
&& errno
!= EACCES
) {
969 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
973 * The shm exists, but we cannot open it RW. Report
981 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
985 * Ensure that our user is the owner of the shm file for
986 * local shm. If we do not own the file, it means our
987 * sessiond will not have access to wake us up (there is
988 * probably a rogue process trying to fake our
989 * sessiond). Fallback to polling method in this case.
991 ret
= fstat(wait_shm_fd
, &statbuf
);
996 if (statbuf
.st_uid
!= getuid())
1002 ret
= close(wait_shm_fd
);
1004 PERROR("Error closing fd");
1010 char *get_map_shm(struct sock_info
*sock_info
)
1013 int wait_shm_fd
, ret
;
1014 char *wait_shm_mmap
;
1016 page_size
= sysconf(_SC_PAGE_SIZE
);
1017 if (page_size
< 0) {
1021 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1022 if (wait_shm_fd
< 0) {
1025 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1026 MAP_SHARED
, wait_shm_fd
, 0);
1027 /* close shm fd immediately after taking the mmap reference */
1028 ret
= close(wait_shm_fd
);
1030 PERROR("Error closing fd");
1032 if (wait_shm_mmap
== MAP_FAILED
) {
1033 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1036 return wait_shm_mmap
;
1043 void wait_for_sessiond(struct sock_info
*sock_info
)
1050 if (wait_poll_fallback
) {
1053 if (!sock_info
->wait_shm_mmap
) {
1054 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
1055 if (!sock_info
->wait_shm_mmap
)
1060 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1061 /* Wait for futex wakeup */
1062 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
) == 0) {
1063 ret
= futex_async((int32_t *) sock_info
->wait_shm_mmap
,
1064 FUTEX_WAIT
, 0, NULL
, NULL
, 0);
1066 if (errno
== EFAULT
) {
1067 wait_poll_fallback
= 1;
1069 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1070 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1071 "Please upgrade your kernel "
1072 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1073 "mainline). LTTng-UST will use polling mode fallback.");
1091 * This thread does not allocate any resource, except within
1092 * handle_message, within mutex protection. This mutex protects against
1094 * The other moment it allocates resources is at socket connection, which
1095 * is also protected by the mutex.
1098 void *ust_listener_thread(void *arg
)
1100 struct sock_info
*sock_info
= arg
;
1101 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
1104 /* Restart trying to connect to the session daemon */
1106 if (prev_connect_failed
) {
1107 /* Wait for sessiond availability with pipe */
1108 wait_for_sessiond(sock_info
);
1112 * Sleep for 5 seconds before retrying after a
1113 * sequence of failure / wait / failure. This
1114 * deals with a killed or broken session daemon.
1119 prev_connect_failed
= 0;
1122 if (sock_info
->socket
!= -1) {
1123 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1125 ERR("Error closing %s ust cmd socket",
1128 sock_info
->socket
= -1;
1130 if (sock_info
->notify_socket
!= -1) {
1131 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1133 ERR("Error closing %s ust notify socket",
1136 sock_info
->notify_socket
= -1;
1140 * Register. We need to perform both connect and sending
1141 * registration message before doing the next connect otherwise
1142 * we may reach unix socket connect queue max limits and block
1143 * on the 2nd connect while the session daemon is awaiting the
1144 * first connect registration message.
1146 /* Connect cmd socket */
1147 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1149 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1150 prev_connect_failed
= 1;
1157 * If we cannot find the sessiond daemon, don't delay
1158 * constructor execution.
1160 ret
= handle_register_done(sock_info
);
1165 sock_info
->socket
= ret
;
1172 * Create only one root handle per listener thread for the whole
1173 * process lifetime, so we ensure we get ID which is statically
1174 * assigned to the root handle.
1176 if (sock_info
->root_handle
== -1) {
1177 ret
= lttng_abi_create_root_handle();
1179 ERR("Error creating root handle");
1182 sock_info
->root_handle
= ret
;
1185 ret
= register_to_sessiond(sock_info
->socket
, USTCTL_SOCKET_CMD
);
1187 ERR("Error registering to %s ust cmd socket",
1189 prev_connect_failed
= 1;
1191 * If we cannot register to the sessiond daemon, don't
1192 * delay constructor execution.
1194 ret
= handle_register_done(sock_info
);
1202 /* Connect notify socket */
1203 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1205 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1206 prev_connect_failed
= 1;
1213 * If we cannot find the sessiond daemon, don't delay
1214 * constructor execution.
1216 ret
= handle_register_done(sock_info
);
1221 sock_info
->notify_socket
= ret
;
1223 timeout
= get_notify_sock_timeout();
1226 * Give at least 10ms to sessiond to reply to
1231 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
1234 WARN("Error setting socket receive timeout");
1236 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
1239 WARN("Error setting socket send timeout");
1241 } else if (timeout
< -1) {
1242 WARN("Unsupported timeout value %ld", timeout
);
1249 ret
= register_to_sessiond(sock_info
->notify_socket
,
1250 USTCTL_SOCKET_NOTIFY
);
1252 ERR("Error registering to %s ust notify socket",
1254 prev_connect_failed
= 1;
1256 * If we cannot register to the sessiond daemon, don't
1257 * delay constructor execution.
1259 ret
= handle_register_done(sock_info
);
1264 sock
= sock_info
->socket
;
1270 struct ustcomm_ust_msg lum
;
1272 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
1274 case 0: /* orderly shutdown */
1275 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
1280 * Either sessiond has shutdown or refused us by closing the socket.
1281 * In either case, we don't want to delay construction execution,
1282 * and we need to wait before retry.
1284 prev_connect_failed
= 1;
1286 * If we cannot register to the sessiond daemon, don't
1287 * delay constructor execution.
1289 ret
= handle_register_done(sock_info
);
1294 print_cmd(lum
.cmd
, lum
.handle
);
1295 ret
= handle_message(sock_info
, sock
, &lum
);
1297 ERR("Error handling message for %s socket", sock_info
->name
);
1302 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1304 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
1306 if (len
== -ECONNRESET
) {
1307 DBG("%s remote end closed connection", sock_info
->name
);
1318 /* Cleanup socket handles before trying to reconnect */
1319 lttng_ust_objd_table_owner_cleanup(sock_info
);
1321 goto restart
; /* try to reconnect */
1326 pthread_mutex_lock(&ust_exit_mutex
);
1327 sock_info
->thread_active
= 0;
1328 pthread_mutex_unlock(&ust_exit_mutex
);
1333 * Weak symbol to call when the ust malloc wrapper is not loaded.
1335 __attribute__((weak
))
1336 void lttng_ust_malloc_wrapper_init(void)
1341 * sessiond monitoring thread: monitor presence of global and per-user
1342 * sessiond by polling the application common named pipe.
1344 void __attribute__((constructor
)) lttng_ust_init(void)
1346 struct timespec constructor_timeout
;
1347 sigset_t sig_all_blocked
, orig_parent_mask
;
1348 pthread_attr_t thread_attr
;
1352 if (uatomic_xchg(&initialized
, 1) == 1)
1356 * Fixup interdependency between TLS fixup mutex (which happens
1357 * to be the dynamic linker mutex) and ust_lock, taken within
1360 lttng_fixup_urcu_bp_tls();
1361 lttng_fixup_ringbuffer_tls();
1362 lttng_fixup_vtid_tls();
1363 lttng_fixup_nest_count_tls();
1364 lttng_fixup_procname_tls();
1367 * We want precise control over the order in which we construct
1368 * our sub-libraries vs starting to receive commands from
1369 * sessiond (otherwise leading to errors when trying to create
1370 * sessiond before the init functions are completed).
1374 lttng_ust_baddr_statedump_init();
1375 lttng_ring_buffer_metadata_client_init();
1376 lttng_ring_buffer_client_overwrite_init();
1377 lttng_ring_buffer_client_overwrite_rt_init();
1378 lttng_ring_buffer_client_discard_init();
1379 lttng_ring_buffer_client_discard_rt_init();
1380 lttng_context_init();
1382 * Invoke ust malloc wrapper init before starting other threads.
1384 lttng_ust_malloc_wrapper_init();
1386 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
1388 ret
= sem_init(&constructor_wait
, 0, 0);
1391 ret
= setup_local_apps();
1393 DBG("local apps setup returned %d", ret
);
1396 /* A new thread created by pthread_create inherits the signal mask
1397 * from the parent. To avoid any signal being received by the
1398 * listener thread, we block all signals temporarily in the parent,
1399 * while we create the listener thread.
1401 sigfillset(&sig_all_blocked
);
1402 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
1404 ERR("pthread_sigmask: %s", strerror(ret
));
1407 ret
= pthread_attr_init(&thread_attr
);
1409 ERR("pthread_attr_init: %s", strerror(ret
));
1411 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
1413 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
1416 pthread_mutex_lock(&ust_exit_mutex
);
1417 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
1418 ust_listener_thread
, &global_apps
);
1420 ERR("pthread_create global: %s", strerror(ret
));
1422 global_apps
.thread_active
= 1;
1423 pthread_mutex_unlock(&ust_exit_mutex
);
1425 if (local_apps
.allowed
) {
1426 pthread_mutex_lock(&ust_exit_mutex
);
1427 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
1428 ust_listener_thread
, &local_apps
);
1430 ERR("pthread_create local: %s", strerror(ret
));
1432 local_apps
.thread_active
= 1;
1433 pthread_mutex_unlock(&ust_exit_mutex
);
1435 handle_register_done(&local_apps
);
1437 ret
= pthread_attr_destroy(&thread_attr
);
1439 ERR("pthread_attr_destroy: %s", strerror(ret
));
1442 /* Restore original signal mask in parent */
1443 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
1445 ERR("pthread_sigmask: %s", strerror(ret
));
1448 switch (timeout_mode
) {
1449 case 1: /* timeout wait */
1451 ret
= sem_timedwait(&constructor_wait
,
1452 &constructor_timeout
);
1453 } while (ret
< 0 && errno
== EINTR
);
1454 if (ret
< 0 && errno
== ETIMEDOUT
) {
1455 ERR("Timed out waiting for lttng-sessiond");
1460 case -1:/* wait forever */
1462 ret
= sem_wait(&constructor_wait
);
1463 } while (ret
< 0 && errno
== EINTR
);
1466 case 0: /* no timeout */
1472 void lttng_ust_cleanup(int exiting
)
1474 cleanup_sock_info(&global_apps
, exiting
);
1475 if (local_apps
.allowed
) {
1476 cleanup_sock_info(&local_apps
, exiting
);
1479 * The teardown in this function all affect data structures
1480 * accessed under the UST lock by the listener thread. This
1481 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1482 * that none of these threads are accessing this data at this
1485 lttng_ust_abi_exit();
1486 lttng_ust_events_exit();
1487 lttng_context_exit();
1488 lttng_ring_buffer_client_discard_rt_exit();
1489 lttng_ring_buffer_client_discard_exit();
1490 lttng_ring_buffer_client_overwrite_rt_exit();
1491 lttng_ring_buffer_client_overwrite_exit();
1492 lttng_ring_buffer_metadata_client_exit();
1493 lttng_ust_baddr_statedump_destroy();
1496 /* Reinitialize values for fork */
1498 lttng_ust_comm_should_quit
= 0;
1503 void __attribute__((destructor
)) lttng_ust_exit(void)
1508 * Using pthread_cancel here because:
1509 * A) we don't want to hang application teardown.
1510 * B) the thread is not allocating any resource.
1514 * Require the communication thread to quit. Synchronize with
1515 * mutexes to ensure it is not in a mutex critical section when
1516 * pthread_cancel is later called.
1519 lttng_ust_comm_should_quit
= 1;
1522 pthread_mutex_lock(&ust_exit_mutex
);
1523 /* cancel threads */
1524 if (global_apps
.thread_active
) {
1525 ret
= pthread_cancel(global_apps
.ust_listener
);
1527 ERR("Error cancelling global ust listener thread: %s",
1530 global_apps
.thread_active
= 0;
1533 if (local_apps
.thread_active
) {
1534 ret
= pthread_cancel(local_apps
.ust_listener
);
1536 ERR("Error cancelling local ust listener thread: %s",
1539 local_apps
.thread_active
= 0;
1542 pthread_mutex_unlock(&ust_exit_mutex
);
1545 * Do NOT join threads: use of sys_futex makes it impossible to
1546 * join the threads without using async-cancel, but async-cancel
1547 * is delivered by a signal, which could hit the target thread
1548 * anywhere in its code path, including while the ust_lock() is
1549 * held, causing a deadlock for the other thread. Let the OS
1550 * cleanup the threads if there are stalled in a syscall.
1552 lttng_ust_cleanup(1);
1556 * We exclude the worker threads across fork and clone (except
1557 * CLONE_VM), because these system calls only keep the forking thread
1558 * running in the child. Therefore, we don't want to call fork or clone
1559 * in the middle of an tracepoint or ust tracing state modification.
1560 * Holding this mutex protects these structures across fork and clone.
1562 void ust_before_fork(sigset_t
*save_sigset
)
1565 * Disable signals. This is to avoid that the child intervenes
1566 * before it is properly setup for tracing. It is safer to
1567 * disable all signals, because then we know we are not breaking
1568 * anything by restoring the original mask.
1573 if (URCU_TLS(lttng_ust_nest_count
))
1575 /* Disable signals */
1576 sigfillset(&all_sigs
);
1577 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
1579 PERROR("sigprocmask");
1582 rcu_bp_before_fork();
1585 static void ust_after_fork_common(sigset_t
*restore_sigset
)
1589 DBG("process %d", getpid());
1591 /* Restore signals */
1592 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
1594 PERROR("sigprocmask");
1598 void ust_after_fork_parent(sigset_t
*restore_sigset
)
1600 if (URCU_TLS(lttng_ust_nest_count
))
1602 DBG("process %d", getpid());
1603 rcu_bp_after_fork_parent();
1604 /* Release mutexes and reenable signals */
1605 ust_after_fork_common(restore_sigset
);
1609 * After fork, in the child, we need to cleanup all the leftover state,
1610 * except the worker thread which already magically disappeared thanks
1611 * to the weird Linux fork semantics. After tyding up, we call
1612 * lttng_ust_init() again to start over as a new PID.
1614 * This is meant for forks() that have tracing in the child between the
1615 * fork and following exec call (if there is any).
1617 void ust_after_fork_child(sigset_t
*restore_sigset
)
1619 if (URCU_TLS(lttng_ust_nest_count
))
1621 DBG("process %d", getpid());
1622 /* Release urcu mutexes */
1623 rcu_bp_after_fork_child();
1624 lttng_ust_cleanup(0);
1625 lttng_context_vtid_reset();
1626 /* Release mutexes and reenable signals */
1627 ust_after_fork_common(restore_sigset
);
1631 void lttng_ust_sockinfo_session_enabled(void *owner
)
1633 struct sock_info
*sock_info
= owner
;
1634 sock_info
->statedump_pending
= 1;