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>
38 #include <urcu/uatomic.h>
39 #include <urcu/futex.h>
40 #include <urcu/compiler.h>
42 #include <lttng/ust-events.h>
43 #include <lttng/ust-abi.h>
44 #include <lttng/ust.h>
45 #include <lttng/ust-error.h>
46 #include <lttng/ust-ctl.h>
47 #include <urcu/tls-compat.h>
49 #include <usterr-signal-safe.h>
51 #include "tracepoint-internal.h"
52 #include "lttng-tracer-core.h"
54 #include "../libringbuffer/tlsfixup.h"
55 #include "lttng-ust-baddr.h"
58 * Has lttng ust comm constructor been called ?
60 static int initialized
;
63 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
64 * Held when handling a command, also held by fork() to deal with
65 * removal of threads, and by exit path.
68 /* Should the ust comm thread quit ? */
69 static int lttng_ust_comm_should_quit
;
72 * Wait for either of these before continuing to the main
74 * - the register_done message from sessiond daemon
75 * (will let the sessiond daemon enable sessions before main
77 * - sessiond daemon is not reachable.
78 * - timeout (ensuring applications are resilient to session
81 static sem_t constructor_wait
;
83 * Doing this for both the global and local sessiond.
85 static int sem_count
= { 2 };
88 * Counting nesting within lttng-ust. Used to ensure that calling fork()
89 * from liblttng-ust does not execute the pre/post fork handlers.
91 static DEFINE_URCU_TLS(int, lttng_ust_nest_count
);
94 * Info about socket and associated listener thread.
98 pthread_t ust_listener
; /* listener thread */
100 int constructor_sem_posted
;
105 char sock_path
[PATH_MAX
];
109 char wait_shm_path
[PATH_MAX
];
114 /* Socket from app (connect) to session daemon (listen) for communication */
115 struct sock_info global_apps
= {
123 .sock_path
= LTTNG_DEFAULT_RUNDIR
"/" LTTNG_UST_SOCK_FILENAME
,
127 .wait_shm_path
= "/" LTTNG_UST_WAIT_FILENAME
,
129 .session_enabled
= 0,
132 /* TODO: allow global_apps_sock_path override */
134 struct sock_info local_apps
= {
138 .allowed
= 0, /* Check setuid bit first */
144 .session_enabled
= 0,
147 static int wait_poll_fallback
;
149 static const char *cmd_name_mapping
[] = {
150 [ LTTNG_UST_RELEASE
] = "Release",
151 [ LTTNG_UST_SESSION
] = "Create Session",
152 [ LTTNG_UST_TRACER_VERSION
] = "Get Tracer Version",
154 [ LTTNG_UST_TRACEPOINT_LIST
] = "Create Tracepoint List",
155 [ LTTNG_UST_WAIT_QUIESCENT
] = "Wait for Quiescent State",
156 [ LTTNG_UST_REGISTER_DONE
] = "Registration Done",
157 [ LTTNG_UST_TRACEPOINT_FIELD_LIST
] = "Create Tracepoint Field List",
159 /* Session FD commands */
160 [ LTTNG_UST_CHANNEL
] = "Create Channel",
161 [ LTTNG_UST_SESSION_START
] = "Start Session",
162 [ LTTNG_UST_SESSION_STOP
] = "Stop Session",
164 /* Channel FD commands */
165 [ LTTNG_UST_STREAM
] = "Create Stream",
166 [ LTTNG_UST_EVENT
] = "Create Event",
168 /* Event and Channel FD commands */
169 [ LTTNG_UST_CONTEXT
] = "Create Context",
170 [ LTTNG_UST_FLUSH_BUFFER
] = "Flush Buffer",
172 /* Event, Channel and Session commands */
173 [ LTTNG_UST_ENABLE
] = "Enable",
174 [ LTTNG_UST_DISABLE
] = "Disable",
176 /* Tracepoint list commands */
177 [ LTTNG_UST_TRACEPOINT_LIST_GET
] = "List Next Tracepoint",
178 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
] = "List Next Tracepoint Field",
180 /* Event FD commands */
181 [ LTTNG_UST_FILTER
] = "Create Filter",
182 [ LTTNG_UST_EXCLUSION
] = "Add exclusions to event",
185 static const char *str_timeout
;
186 static int got_timeout_env
;
188 extern void lttng_ring_buffer_client_overwrite_init(void);
189 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
190 extern void lttng_ring_buffer_client_discard_init(void);
191 extern void lttng_ring_buffer_client_discard_rt_init(void);
192 extern void lttng_ring_buffer_metadata_client_init(void);
193 extern void lttng_ring_buffer_client_overwrite_exit(void);
194 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
195 extern void lttng_ring_buffer_client_discard_exit(void);
196 extern void lttng_ring_buffer_client_discard_rt_exit(void);
197 extern void lttng_ring_buffer_metadata_client_exit(void);
200 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
204 const char *get_lttng_home_dir(void)
208 val
= (const char *) getenv("LTTNG_HOME");
212 return (const char *) getenv("HOME");
216 * Force a read (imply TLS fixup for dlopen) of TLS variables.
219 void lttng_fixup_nest_count_tls(void)
221 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count
)));
224 int lttng_get_notify_socket(void *owner
)
226 struct sock_info
*info
= owner
;
228 return info
->notify_socket
;
232 void print_cmd(int cmd
, int handle
)
234 const char *cmd_name
= "Unknown";
236 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
237 && cmd_name_mapping
[cmd
]) {
238 cmd_name
= cmd_name_mapping
[cmd
];
240 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
242 lttng_ust_obj_get_name(handle
), handle
);
246 int setup_local_apps(void)
248 const char *home_dir
;
253 * Disallow per-user tracing for setuid binaries.
255 if (uid
!= geteuid()) {
256 assert(local_apps
.allowed
== 0);
259 home_dir
= get_lttng_home_dir();
261 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
262 assert(local_apps
.allowed
== 0);
265 local_apps
.allowed
= 1;
266 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
268 LTTNG_DEFAULT_HOME_RUNDIR
,
269 LTTNG_UST_SOCK_FILENAME
);
270 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
271 LTTNG_UST_WAIT_FILENAME
,
277 * Get notify_sock timeout, in ms.
278 * -1: don't wait. 0: wait forever. >0: timeout, in ms.
281 long get_timeout(void)
283 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
285 if (!got_timeout_env
) {
286 str_timeout
= getenv("LTTNG_UST_REGISTER_TIMEOUT");
290 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
291 return constructor_delay_ms
;
295 long get_notify_sock_timeout(void)
297 return get_timeout();
301 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
304 int get_constructor_timeout(struct timespec
*constructor_timeout
)
306 long constructor_delay_ms
;
309 constructor_delay_ms
= get_timeout();
311 switch (constructor_delay_ms
) {
312 case -1:/* fall-through */
314 return constructor_delay_ms
;
320 * If we are unable to find the current time, don't wait.
322 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
326 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
327 constructor_timeout
->tv_nsec
+=
328 (constructor_delay_ms
% 1000UL) * 1000000UL;
329 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
330 constructor_timeout
->tv_sec
++;
331 constructor_timeout
->tv_nsec
-= 1000000000UL;
337 int register_to_sessiond(int socket
, enum ustctl_socket_type type
)
339 return ustcomm_send_reg_msg(socket
,
342 lttng_alignof(uint8_t) * CHAR_BIT
,
343 lttng_alignof(uint16_t) * CHAR_BIT
,
344 lttng_alignof(uint32_t) * CHAR_BIT
,
345 lttng_alignof(uint64_t) * CHAR_BIT
,
346 lttng_alignof(unsigned long) * CHAR_BIT
);
350 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
354 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
357 DBG("message successfully sent");
360 if (len
== -ECONNRESET
) {
361 DBG("remote end closed connection");
366 DBG("incorrect message size: %zd", len
);
372 int handle_register_done(struct sock_info
*sock_info
)
376 if (sock_info
->constructor_sem_posted
)
378 sock_info
->constructor_sem_posted
= 1;
379 if (uatomic_read(&sem_count
) <= 0) {
382 ret
= uatomic_add_return(&sem_count
, -1);
384 ret
= sem_post(&constructor_wait
);
391 int handle_message(struct sock_info
*sock_info
,
392 int sock
, struct ustcomm_ust_msg
*lum
)
395 const struct lttng_ust_objd_ops
*ops
;
396 struct ustcomm_ust_reply lur
;
402 memset(&lur
, 0, sizeof(lur
));
404 if (lttng_ust_comm_should_quit
) {
405 ret
= -LTTNG_UST_ERR_EXITING
;
409 ops
= objd_ops(lum
->handle
);
416 case LTTNG_UST_REGISTER_DONE
:
417 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
418 ret
= handle_register_done(sock_info
);
422 case LTTNG_UST_RELEASE
:
423 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
426 ret
= lttng_ust_objd_unref(lum
->handle
, 1);
428 case LTTNG_UST_FILTER
:
430 /* Receive filter data */
431 struct lttng_ust_filter_bytecode_node
*bytecode
;
433 if (lum
->u
.filter
.data_size
> FILTER_BYTECODE_MAX_LEN
) {
434 ERR("Filter data size is too large: %u bytes",
435 lum
->u
.filter
.data_size
);
440 if (lum
->u
.filter
.reloc_offset
> lum
->u
.filter
.data_size
) {
441 ERR("Filter reloc offset %u is not within data",
442 lum
->u
.filter
.reloc_offset
);
447 bytecode
= zmalloc(sizeof(*bytecode
) + lum
->u
.filter
.data_size
);
452 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
,
453 lum
->u
.filter
.data_size
);
455 case 0: /* orderly shutdown */
460 if (len
== lum
->u
.filter
.data_size
) {
461 DBG("filter data received");
463 } else if (len
< 0) {
464 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
465 if (len
== -ECONNRESET
) {
466 ERR("%s remote end closed connection", sock_info
->name
);
475 DBG("incorrect filter data message size: %zd", len
);
481 bytecode
->bc
.len
= lum
->u
.filter
.data_size
;
482 bytecode
->bc
.reloc_offset
= lum
->u
.filter
.reloc_offset
;
483 bytecode
->bc
.seqnum
= lum
->u
.filter
.seqnum
;
485 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
486 (unsigned long) bytecode
,
491 /* don't free bytecode if everything went fine. */
498 case LTTNG_UST_EXCLUSION
:
500 /* Receive exclusion names */
501 struct lttng_ust_excluder_node
*node
;
504 count
= lum
->u
.exclusion
.count
;
506 /* There are no names to read */
510 node
= zmalloc(sizeof(*node
) +
511 count
* LTTNG_UST_SYM_NAME_LEN
);
516 node
->excluder
.count
= count
;
517 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
518 count
* LTTNG_UST_SYM_NAME_LEN
);
520 case 0: /* orderly shutdown */
525 if (len
== count
* LTTNG_UST_SYM_NAME_LEN
) {
526 DBG("Exclusion data received");
528 } else if (len
< 0) {
529 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
530 if (len
== -ECONNRESET
) {
531 ERR("%s remote end closed connection", sock_info
->name
);
540 DBG("Incorrect exclusion data message size: %zd", len
);
547 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
548 (unsigned long) node
,
553 /* Don't free exclusion data if everything went fine. */
560 case LTTNG_UST_CHANNEL
:
565 len
= ustcomm_recv_channel_from_sessiond(sock
,
566 &chan_data
, lum
->u
.channel
.len
,
569 case 0: /* orderly shutdown */
573 if (len
== lum
->u
.channel
.len
) {
574 DBG("channel data received");
576 } else if (len
< 0) {
577 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
578 if (len
== -ECONNRESET
) {
579 ERR("%s remote end closed connection", sock_info
->name
);
586 DBG("incorrect channel data message size: %zd", len
);
591 args
.channel
.chan_data
= chan_data
;
592 args
.channel
.wakeup_fd
= wakeup_fd
;
594 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
595 (unsigned long) &lum
->u
,
601 case LTTNG_UST_STREAM
:
603 /* Receive shm_fd, wakeup_fd */
604 ret
= ustcomm_recv_stream_from_sessiond(sock
,
607 &args
.stream
.wakeup_fd
);
612 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
613 (unsigned long) &lum
->u
,
621 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
622 (unsigned long) &lum
->u
,
630 lur
.handle
= lum
->handle
;
634 lur
.ret_code
= LTTNG_UST_OK
;
637 * Use -LTTNG_UST_ERR as wildcard for UST internal
638 * error that are not caused by the transport, except if
639 * we already have a more precise error message to
642 if (ret
> -LTTNG_UST_ERR
) {
643 /* Translate code to UST error. */
646 lur
.ret_code
= -LTTNG_UST_ERR_EXIST
;
649 lur
.ret_code
= -LTTNG_UST_ERR_INVAL
;
652 lur
.ret_code
= -LTTNG_UST_ERR_NOENT
;
655 lur
.ret_code
= -LTTNG_UST_ERR_PERM
;
658 lur
.ret_code
= -LTTNG_UST_ERR_NOSYS
;
661 lur
.ret_code
= -LTTNG_UST_ERR
;
670 case LTTNG_UST_TRACER_VERSION
:
671 lur
.u
.version
= lum
->u
.version
;
673 case LTTNG_UST_TRACEPOINT_LIST_GET
:
674 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
678 DBG("Return value: %d", lur
.ret_val
);
679 ret
= send_reply(sock
, &lur
);
681 DBG("error sending reply");
686 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
689 if (lur
.ret_code
== LTTNG_UST_OK
) {
691 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
:
692 len
= ustcomm_send_unix_sock(sock
,
693 &args
.field_list
.entry
,
694 sizeof(args
.field_list
.entry
));
699 if (len
!= sizeof(args
.field_list
.entry
)) {
712 void handle_pending_statedumps(struct sock_info
*sock_info
)
714 int ctor_passed
= sock_info
->constructor_sem_posted
;
716 if (ctor_passed
&& sock_info
->session_enabled
) {
717 sock_info
->session_enabled
= 0;
718 lttng_handle_pending_statedumps(<tng_ust_baddr_statedump
);
723 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
727 if (sock_info
->root_handle
!= -1) {
728 ret
= lttng_ust_objd_unref(sock_info
->root_handle
, 1);
730 ERR("Error unref root handle");
732 sock_info
->root_handle
= -1;
734 sock_info
->constructor_sem_posted
= 0;
737 * wait_shm_mmap, socket and notify socket are used by listener
738 * threads outside of the ust lock, so we cannot tear them down
739 * ourselves, because we cannot join on these threads. Leave
740 * responsibility of cleaning up these resources to the OS
746 if (sock_info
->socket
!= -1) {
747 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
749 ERR("Error closing ust cmd socket");
751 sock_info
->socket
= -1;
753 if (sock_info
->notify_socket
!= -1) {
754 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
756 ERR("Error closing ust notify socket");
758 sock_info
->notify_socket
= -1;
760 if (sock_info
->wait_shm_mmap
) {
761 ret
= munmap(sock_info
->wait_shm_mmap
, sysconf(_SC_PAGE_SIZE
));
763 ERR("Error unmapping wait shm");
765 sock_info
->wait_shm_mmap
= NULL
;
770 * Using fork to set umask in the child process (not multi-thread safe).
771 * We deal with the shm_open vs ftruncate race (happening when the
772 * sessiond owns the shm and does not let everybody modify it, to ensure
773 * safety against shm_unlink) by simply letting the mmap fail and
774 * retrying after a few seconds.
775 * For global shm, everybody has rw access to it until the sessiond
779 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
781 int wait_shm_fd
, ret
;
785 * Try to open read-only.
787 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
788 if (wait_shm_fd
>= 0) {
791 size_t bytes_read
= 0;
794 * Try to read the fd. If unable to do so, try opening
798 len
= read(wait_shm_fd
,
799 &((char *) &tmp_read
)[bytes_read
],
800 sizeof(tmp_read
) - bytes_read
);
804 } while ((len
< 0 && errno
== EINTR
)
805 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
806 if (bytes_read
!= sizeof(tmp_read
)) {
807 ret
= close(wait_shm_fd
);
809 ERR("close wait_shm_fd");
814 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
816 * Real-only open did not work, and it's not because the
817 * entry was not present. It's a failure that prohibits
820 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
826 * If the open failed because the file did not exist, or because
827 * the file was not truncated yet, try creating it ourself.
829 URCU_TLS(lttng_ust_nest_count
)++;
831 URCU_TLS(lttng_ust_nest_count
)--;
836 * Parent: wait for child to return, in which case the
837 * shared memory map will have been created.
840 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
845 * Try to open read-only again after creation.
847 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
848 if (wait_shm_fd
< 0) {
850 * Real-only open did not work. It's a failure
851 * that prohibits using shm.
853 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
857 } else if (pid
== 0) {
861 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
862 if (sock_info
->global
)
863 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
865 * We're alone in a child process, so we can modify the
866 * process-wide umask.
870 * Try creating shm (or get rw access).
871 * We don't do an exclusive open, because we allow other
872 * processes to create+ftruncate it concurrently.
874 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
875 O_RDWR
| O_CREAT
, create_mode
);
876 if (wait_shm_fd
>= 0) {
877 ret
= ftruncate(wait_shm_fd
, mmap_size
);
885 * For local shm, we need to have rw access to accept
886 * opening it: this means the local sessiond will be
887 * able to wake us up. For global shm, we open it even
888 * if rw access is not granted, because the root.root
889 * sessiond will be able to override all rights and wake
892 if (!sock_info
->global
&& errno
!= EACCES
) {
893 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
897 * The shm exists, but we cannot open it RW. Report
905 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
909 * Ensure that our user is the owner of the shm file for
910 * local shm. If we do not own the file, it means our
911 * sessiond will not have access to wake us up (there is
912 * probably a rogue process trying to fake our
913 * sessiond). Fallback to polling method in this case.
915 ret
= fstat(wait_shm_fd
, &statbuf
);
920 if (statbuf
.st_uid
!= getuid())
926 ret
= close(wait_shm_fd
);
928 PERROR("Error closing fd");
934 char *get_map_shm(struct sock_info
*sock_info
)
936 size_t mmap_size
= sysconf(_SC_PAGE_SIZE
);
937 int wait_shm_fd
, ret
;
940 wait_shm_fd
= get_wait_shm(sock_info
, mmap_size
);
941 if (wait_shm_fd
< 0) {
944 wait_shm_mmap
= mmap(NULL
, mmap_size
, PROT_READ
,
945 MAP_SHARED
, wait_shm_fd
, 0);
946 /* close shm fd immediately after taking the mmap reference */
947 ret
= close(wait_shm_fd
);
949 PERROR("Error closing fd");
951 if (wait_shm_mmap
== MAP_FAILED
) {
952 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
955 return wait_shm_mmap
;
962 void wait_for_sessiond(struct sock_info
*sock_info
)
967 if (lttng_ust_comm_should_quit
) {
970 if (wait_poll_fallback
) {
973 if (!sock_info
->wait_shm_mmap
) {
974 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
975 if (!sock_info
->wait_shm_mmap
)
980 DBG("Waiting for %s apps sessiond", sock_info
->name
);
981 /* Wait for futex wakeup */
982 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
) == 0) {
983 ret
= futex_async((int32_t *) sock_info
->wait_shm_mmap
,
984 FUTEX_WAIT
, 0, NULL
, NULL
, 0);
986 if (errno
== EFAULT
) {
987 wait_poll_fallback
= 1;
989 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
990 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
991 "Please upgrade your kernel "
992 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
993 "mainline). LTTng-UST will use polling mode fallback.");
1011 * This thread does not allocate any resource, except within
1012 * handle_message, within mutex protection. This mutex protects against
1014 * The other moment it allocates resources is at socket connection, which
1015 * is also protected by the mutex.
1018 void *ust_listener_thread(void *arg
)
1020 struct sock_info
*sock_info
= arg
;
1021 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
1024 /* Restart trying to connect to the session daemon */
1026 if (prev_connect_failed
) {
1027 /* Wait for sessiond availability with pipe */
1028 wait_for_sessiond(sock_info
);
1032 * Sleep for 5 seconds before retrying after a
1033 * sequence of failure / wait / failure. This
1034 * deals with a killed or broken session daemon.
1039 prev_connect_failed
= 0;
1042 if (sock_info
->socket
!= -1) {
1043 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1045 ERR("Error closing %s ust cmd socket",
1048 sock_info
->socket
= -1;
1050 if (sock_info
->notify_socket
!= -1) {
1051 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1053 ERR("Error closing %s ust notify socket",
1056 sock_info
->notify_socket
= -1;
1060 * Register. We need to perform both connect and sending
1061 * registration message before doing the next connect otherwise
1062 * we may reach unix socket connect queue max limits and block
1063 * on the 2nd connect while the session daemon is awaiting the
1064 * first connect registration message.
1066 /* Connect cmd socket */
1067 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1069 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1070 prev_connect_failed
= 1;
1074 if (lttng_ust_comm_should_quit
) {
1079 * If we cannot find the sessiond daemon, don't delay
1080 * constructor execution.
1082 ret
= handle_register_done(sock_info
);
1087 sock_info
->socket
= ret
;
1091 if (lttng_ust_comm_should_quit
) {
1096 * Create only one root handle per listener thread for the whole
1097 * process lifetime, so we ensure we get ID which is statically
1098 * assigned to the root handle.
1100 if (sock_info
->root_handle
== -1) {
1101 ret
= lttng_abi_create_root_handle();
1103 ERR("Error creating root handle");
1106 sock_info
->root_handle
= ret
;
1109 ret
= register_to_sessiond(sock_info
->socket
, USTCTL_SOCKET_CMD
);
1111 ERR("Error registering to %s ust cmd socket",
1113 prev_connect_failed
= 1;
1115 * If we cannot register to the sessiond daemon, don't
1116 * delay constructor execution.
1118 ret
= handle_register_done(sock_info
);
1126 /* Connect notify socket */
1127 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1129 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1130 prev_connect_failed
= 1;
1134 if (lttng_ust_comm_should_quit
) {
1139 * If we cannot find the sessiond daemon, don't delay
1140 * constructor execution.
1142 ret
= handle_register_done(sock_info
);
1147 sock_info
->notify_socket
= ret
;
1149 timeout
= get_notify_sock_timeout();
1152 * Give at least 10ms to sessiond to reply to
1157 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
1160 WARN("Error setting socket receive timeout");
1162 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
1165 WARN("Error setting socket send timeout");
1167 } else if (timeout
< -1) {
1168 WARN("Unsupported timeout value %ld", timeout
);
1173 if (lttng_ust_comm_should_quit
) {
1177 ret
= register_to_sessiond(sock_info
->notify_socket
,
1178 USTCTL_SOCKET_NOTIFY
);
1180 ERR("Error registering to %s ust notify socket",
1182 prev_connect_failed
= 1;
1184 * If we cannot register to the sessiond daemon, don't
1185 * delay constructor execution.
1187 ret
= handle_register_done(sock_info
);
1192 sock
= sock_info
->socket
;
1198 struct ustcomm_ust_msg lum
;
1200 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
1202 case 0: /* orderly shutdown */
1203 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
1205 if (lttng_ust_comm_should_quit
) {
1209 * Either sessiond has shutdown or refused us by closing the socket.
1210 * In either case, we don't want to delay construction execution,
1211 * and we need to wait before retry.
1213 prev_connect_failed
= 1;
1215 * If we cannot register to the sessiond daemon, don't
1216 * delay constructor execution.
1218 ret
= handle_register_done(sock_info
);
1223 print_cmd(lum
.cmd
, lum
.handle
);
1224 ret
= handle_message(sock_info
, sock
, &lum
);
1226 ERR("Error handling message for %s socket", sock_info
->name
);
1228 handle_pending_statedumps(sock_info
);
1233 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1235 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
1237 if (len
== -ECONNRESET
) {
1238 DBG("%s remote end closed connection", sock_info
->name
);
1247 if (lttng_ust_comm_should_quit
) {
1250 /* Cleanup socket handles before trying to reconnect */
1251 lttng_ust_objd_table_owner_cleanup(sock_info
);
1253 goto restart
; /* try to reconnect */
1256 sock_info
->thread_active
= 0;
1262 * sessiond monitoring thread: monitor presence of global and per-user
1263 * sessiond by polling the application common named pipe.
1265 void __attribute__((constructor
)) lttng_ust_init(void)
1267 struct timespec constructor_timeout
;
1268 sigset_t sig_all_blocked
, orig_parent_mask
;
1269 pthread_attr_t thread_attr
;
1273 if (uatomic_xchg(&initialized
, 1) == 1)
1277 * Fixup interdependency between TLS fixup mutex (which happens
1278 * to be the dynamic linker mutex) and ust_lock, taken within
1281 lttng_fixup_ringbuffer_tls();
1282 lttng_fixup_vtid_tls();
1283 lttng_fixup_nest_count_tls();
1284 lttng_fixup_procname_tls();
1287 * We want precise control over the order in which we construct
1288 * our sub-libraries vs starting to receive commands from
1289 * sessiond (otherwise leading to errors when trying to create
1290 * sessiond before the init functions are completed).
1294 lttng_ring_buffer_metadata_client_init();
1295 lttng_ring_buffer_client_overwrite_init();
1296 lttng_ring_buffer_client_overwrite_rt_init();
1297 lttng_ring_buffer_client_discard_init();
1298 lttng_ring_buffer_client_discard_rt_init();
1299 lttng_context_init();
1301 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
1303 ret
= sem_init(&constructor_wait
, 0, 0);
1306 ret
= setup_local_apps();
1308 DBG("local apps setup returned %d", ret
);
1311 /* A new thread created by pthread_create inherits the signal mask
1312 * from the parent. To avoid any signal being received by the
1313 * listener thread, we block all signals temporarily in the parent,
1314 * while we create the listener thread.
1316 sigfillset(&sig_all_blocked
);
1317 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
1319 ERR("pthread_sigmask: %s", strerror(ret
));
1322 ret
= pthread_attr_init(&thread_attr
);
1324 ERR("pthread_attr_init: %s", strerror(ret
));
1326 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
1328 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
1332 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
1333 ust_listener_thread
, &global_apps
);
1335 ERR("pthread_create global: %s", strerror(ret
));
1337 global_apps
.thread_active
= 1;
1340 if (local_apps
.allowed
) {
1342 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
1343 ust_listener_thread
, &local_apps
);
1345 ERR("pthread_create local: %s", strerror(ret
));
1347 local_apps
.thread_active
= 1;
1350 handle_register_done(&local_apps
);
1352 ret
= pthread_attr_destroy(&thread_attr
);
1354 ERR("pthread_attr_destroy: %s", strerror(ret
));
1357 /* Restore original signal mask in parent */
1358 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
1360 ERR("pthread_sigmask: %s", strerror(ret
));
1363 switch (timeout_mode
) {
1364 case 1: /* timeout wait */
1366 ret
= sem_timedwait(&constructor_wait
,
1367 &constructor_timeout
);
1368 } while (ret
< 0 && errno
== EINTR
);
1369 if (ret
< 0 && errno
== ETIMEDOUT
) {
1370 ERR("Timed out waiting for lttng-sessiond");
1375 case -1:/* wait forever */
1377 ret
= sem_wait(&constructor_wait
);
1378 } while (ret
< 0 && errno
== EINTR
);
1381 case 0: /* no timeout */
1387 void lttng_ust_cleanup(int exiting
)
1389 cleanup_sock_info(&global_apps
, exiting
);
1390 if (local_apps
.allowed
) {
1391 cleanup_sock_info(&local_apps
, exiting
);
1394 * The teardown in this function all affect data structures
1395 * accessed under the UST lock by the listener thread. This
1396 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1397 * that none of these threads are accessing this data at this
1400 lttng_ust_abi_exit();
1401 lttng_ust_events_exit();
1402 lttng_context_exit();
1403 lttng_ring_buffer_client_discard_rt_exit();
1404 lttng_ring_buffer_client_discard_exit();
1405 lttng_ring_buffer_client_overwrite_rt_exit();
1406 lttng_ring_buffer_client_overwrite_exit();
1407 lttng_ring_buffer_metadata_client_exit();
1410 /* Reinitialize values for fork */
1412 lttng_ust_comm_should_quit
= 0;
1417 void __attribute__((destructor
)) lttng_ust_exit(void)
1422 * Using pthread_cancel here because:
1423 * A) we don't want to hang application teardown.
1424 * B) the thread is not allocating any resource.
1428 * Require the communication thread to quit. Synchronize with
1429 * mutexes to ensure it is not in a mutex critical section when
1430 * pthread_cancel is later called.
1433 lttng_ust_comm_should_quit
= 1;
1435 /* cancel threads */
1436 if (global_apps
.thread_active
) {
1437 ret
= pthread_cancel(global_apps
.ust_listener
);
1439 ERR("Error cancelling global ust listener thread: %s",
1442 global_apps
.thread_active
= 0;
1445 if (local_apps
.thread_active
) {
1446 ret
= pthread_cancel(local_apps
.ust_listener
);
1448 ERR("Error cancelling local ust listener thread: %s",
1451 local_apps
.thread_active
= 0;
1457 * Do NOT join threads: use of sys_futex makes it impossible to
1458 * join the threads without using async-cancel, but async-cancel
1459 * is delivered by a signal, which could hit the target thread
1460 * anywhere in its code path, including while the ust_lock() is
1461 * held, causing a deadlock for the other thread. Let the OS
1462 * cleanup the threads if there are stalled in a syscall.
1464 lttng_ust_cleanup(1);
1468 * We exclude the worker threads across fork and clone (except
1469 * CLONE_VM), because these system calls only keep the forking thread
1470 * running in the child. Therefore, we don't want to call fork or clone
1471 * in the middle of an tracepoint or ust tracing state modification.
1472 * Holding this mutex protects these structures across fork and clone.
1474 void ust_before_fork(sigset_t
*save_sigset
)
1477 * Disable signals. This is to avoid that the child intervenes
1478 * before it is properly setup for tracing. It is safer to
1479 * disable all signals, because then we know we are not breaking
1480 * anything by restoring the original mask.
1485 if (URCU_TLS(lttng_ust_nest_count
))
1487 /* Disable signals */
1488 sigfillset(&all_sigs
);
1489 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
1491 PERROR("sigprocmask");
1494 rcu_bp_before_fork();
1497 static void ust_after_fork_common(sigset_t
*restore_sigset
)
1501 DBG("process %d", getpid());
1503 /* Restore signals */
1504 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
1506 PERROR("sigprocmask");
1510 void ust_after_fork_parent(sigset_t
*restore_sigset
)
1512 if (URCU_TLS(lttng_ust_nest_count
))
1514 DBG("process %d", getpid());
1515 rcu_bp_after_fork_parent();
1516 /* Release mutexes and reenable signals */
1517 ust_after_fork_common(restore_sigset
);
1521 * After fork, in the child, we need to cleanup all the leftover state,
1522 * except the worker thread which already magically disappeared thanks
1523 * to the weird Linux fork semantics. After tyding up, we call
1524 * lttng_ust_init() again to start over as a new PID.
1526 * This is meant for forks() that have tracing in the child between the
1527 * fork and following exec call (if there is any).
1529 void ust_after_fork_child(sigset_t
*restore_sigset
)
1531 if (URCU_TLS(lttng_ust_nest_count
))
1533 DBG("process %d", getpid());
1534 /* Release urcu mutexes */
1535 rcu_bp_after_fork_child();
1536 lttng_ust_cleanup(0);
1537 lttng_context_vtid_reset();
1538 /* Release mutexes and reenable signals */
1539 ust_after_fork_common(restore_sigset
);
1543 void lttng_ust_sockinfo_session_enabled(void *owner
)
1545 struct sock_info
*sock_info
= owner
;
1546 sock_info
->session_enabled
= 1;