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"
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.
67 * The UST lock is the centralized mutex across UST tracing control and
70 * ust_exit_mutex must never nest in ust_mutex.
72 * ust_fork_mutex must never nest in ust_mutex.
74 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
75 * counter lazy initialization called by events within the statedump,
76 * which traces while the ust_mutex is held.
78 * ust_lock nests within the dynamic loader lock (within glibc) because
79 * it is taken within the library constructor.
81 static pthread_mutex_t ust_mutex
= PTHREAD_MUTEX_INITIALIZER
;
83 /* Allow nesting the ust_mutex within the same thread. */
84 static DEFINE_URCU_TLS(int, ust_mutex_nest
);
87 * ust_exit_mutex protects thread_active variable wrt thread exit. It
88 * cannot be done by ust_mutex because pthread_cancel(), which takes an
89 * internal libc lock, cannot nest within ust_mutex.
91 * It never nests within a ust_mutex.
93 static pthread_mutex_t ust_exit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
96 * ust_fork_mutex protects base address statedump tracing against forks. It
97 * prevents the dynamic loader lock to be taken (by base address statedump
98 * tracing) while a fork is happening, thus preventing deadlock issues with
99 * the dynamic loader lock.
101 static pthread_mutex_t ust_fork_mutex
= PTHREAD_MUTEX_INITIALIZER
;
103 /* Should the ust comm thread quit ? */
104 static int lttng_ust_comm_should_quit
;
107 * Return 0 on success, -1 if should quit.
108 * The lock is taken in both cases.
113 sigset_t sig_all_blocked
, orig_mask
;
116 ret
= pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &oldstate
);
118 ERR("pthread_setcancelstate: %s", strerror(ret
));
120 if (oldstate
!= PTHREAD_CANCEL_ENABLE
) {
121 ERR("pthread_setcancelstate: unexpected oldstate");
123 sigfillset(&sig_all_blocked
);
124 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
126 ERR("pthread_sigmask: %s", strerror(ret
));
128 if (!URCU_TLS(ust_mutex_nest
)++)
129 pthread_mutex_lock(&ust_mutex
);
130 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
132 ERR("pthread_sigmask: %s", strerror(ret
));
134 if (lttng_ust_comm_should_quit
) {
142 * ust_lock_nocheck() can be used in constructors/destructors, because
143 * they are already nested within the dynamic loader lock, and therefore
144 * have exclusive access against execution of liblttng-ust destructor.
147 void ust_lock_nocheck(void)
149 sigset_t sig_all_blocked
, orig_mask
;
152 ret
= pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &oldstate
);
154 ERR("pthread_setcancelstate: %s", strerror(ret
));
156 if (oldstate
!= PTHREAD_CANCEL_ENABLE
) {
157 ERR("pthread_setcancelstate: unexpected oldstate");
159 sigfillset(&sig_all_blocked
);
160 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
162 ERR("pthread_sigmask: %s", strerror(ret
));
164 if (!URCU_TLS(ust_mutex_nest
)++)
165 pthread_mutex_lock(&ust_mutex
);
166 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
168 ERR("pthread_sigmask: %s", strerror(ret
));
175 void ust_unlock(void)
177 sigset_t sig_all_blocked
, orig_mask
;
180 sigfillset(&sig_all_blocked
);
181 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
183 ERR("pthread_sigmask: %s", strerror(ret
));
185 if (!--URCU_TLS(ust_mutex_nest
))
186 pthread_mutex_unlock(&ust_mutex
);
187 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
189 ERR("pthread_sigmask: %s", strerror(ret
));
191 ret
= pthread_setcancelstate(PTHREAD_CANCEL_ENABLE
, &oldstate
);
193 ERR("pthread_setcancelstate: %s", strerror(ret
));
195 if (oldstate
!= PTHREAD_CANCEL_DISABLE
) {
196 ERR("pthread_setcancelstate: unexpected oldstate");
201 * Wait for either of these before continuing to the main
203 * - the register_done message from sessiond daemon
204 * (will let the sessiond daemon enable sessions before main
206 * - sessiond daemon is not reachable.
207 * - timeout (ensuring applications are resilient to session
210 static sem_t constructor_wait
;
212 * Doing this for both the global and local sessiond.
214 static int sem_count
= { 2 };
217 * Counting nesting within lttng-ust. Used to ensure that calling fork()
218 * from liblttng-ust does not execute the pre/post fork handlers.
220 static DEFINE_URCU_TLS(int, lttng_ust_nest_count
);
223 * Info about socket and associated listener thread.
227 pthread_t ust_listener
; /* listener thread */
229 int constructor_sem_posted
;
234 char sock_path
[PATH_MAX
];
238 char wait_shm_path
[PATH_MAX
];
240 /* Keep track of lazy state dump not performed yet. */
241 int statedump_pending
;
244 /* Socket from app (connect) to session daemon (listen) for communication */
245 struct sock_info global_apps
= {
253 .sock_path
= LTTNG_DEFAULT_RUNDIR
"/" LTTNG_UST_SOCK_FILENAME
,
257 .wait_shm_path
= "/" LTTNG_UST_WAIT_FILENAME
,
259 .statedump_pending
= 0,
262 /* TODO: allow global_apps_sock_path override */
264 struct sock_info local_apps
= {
268 .allowed
= 0, /* Check setuid bit first */
274 .statedump_pending
= 0,
277 static int wait_poll_fallback
;
279 static const char *cmd_name_mapping
[] = {
280 [ LTTNG_UST_RELEASE
] = "Release",
281 [ LTTNG_UST_SESSION
] = "Create Session",
282 [ LTTNG_UST_TRACER_VERSION
] = "Get Tracer Version",
284 [ LTTNG_UST_TRACEPOINT_LIST
] = "Create Tracepoint List",
285 [ LTTNG_UST_WAIT_QUIESCENT
] = "Wait for Quiescent State",
286 [ LTTNG_UST_REGISTER_DONE
] = "Registration Done",
287 [ LTTNG_UST_TRACEPOINT_FIELD_LIST
] = "Create Tracepoint Field List",
289 /* Session FD commands */
290 [ LTTNG_UST_CHANNEL
] = "Create Channel",
291 [ LTTNG_UST_SESSION_START
] = "Start Session",
292 [ LTTNG_UST_SESSION_STOP
] = "Stop Session",
294 /* Channel FD commands */
295 [ LTTNG_UST_STREAM
] = "Create Stream",
296 [ LTTNG_UST_EVENT
] = "Create Event",
298 /* Event and Channel FD commands */
299 [ LTTNG_UST_CONTEXT
] = "Create Context",
300 [ LTTNG_UST_FLUSH_BUFFER
] = "Flush Buffer",
302 /* Event, Channel and Session commands */
303 [ LTTNG_UST_ENABLE
] = "Enable",
304 [ LTTNG_UST_DISABLE
] = "Disable",
306 /* Tracepoint list commands */
307 [ LTTNG_UST_TRACEPOINT_LIST_GET
] = "List Next Tracepoint",
308 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
] = "List Next Tracepoint Field",
310 /* Event FD commands */
311 [ LTTNG_UST_FILTER
] = "Create Filter",
312 [ LTTNG_UST_EXCLUSION
] = "Add exclusions to event",
315 static const char *str_timeout
;
316 static int got_timeout_env
;
318 extern void lttng_ring_buffer_client_overwrite_init(void);
319 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
320 extern void lttng_ring_buffer_client_discard_init(void);
321 extern void lttng_ring_buffer_client_discard_rt_init(void);
322 extern void lttng_ring_buffer_metadata_client_init(void);
323 extern void lttng_ring_buffer_client_overwrite_exit(void);
324 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
325 extern void lttng_ring_buffer_client_discard_exit(void);
326 extern void lttng_ring_buffer_client_discard_rt_exit(void);
327 extern void lttng_ring_buffer_metadata_client_exit(void);
330 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
334 const char *get_lttng_home_dir(void)
338 val
= (const char *) lttng_secure_getenv("LTTNG_HOME");
342 return (const char *) lttng_secure_getenv("HOME");
346 * Force a read (imply TLS fixup for dlopen) of TLS variables.
349 void lttng_fixup_nest_count_tls(void)
351 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count
)));
355 void lttng_fixup_ust_mutex_nest_tls(void)
357 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest
)));
364 void lttng_fixup_urcu_bp_tls(void)
370 int lttng_get_notify_socket(void *owner
)
372 struct sock_info
*info
= owner
;
374 return info
->notify_socket
;
378 void print_cmd(int cmd
, int handle
)
380 const char *cmd_name
= "Unknown";
382 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
383 && cmd_name_mapping
[cmd
]) {
384 cmd_name
= cmd_name_mapping
[cmd
];
386 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
388 lttng_ust_obj_get_name(handle
), handle
);
392 int setup_local_apps(void)
394 const char *home_dir
;
399 * Disallow per-user tracing for setuid binaries.
401 if (uid
!= geteuid()) {
402 assert(local_apps
.allowed
== 0);
405 home_dir
= get_lttng_home_dir();
407 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
408 assert(local_apps
.allowed
== 0);
411 local_apps
.allowed
= 1;
412 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
414 LTTNG_DEFAULT_HOME_RUNDIR
,
415 LTTNG_UST_SOCK_FILENAME
);
416 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
417 LTTNG_UST_WAIT_FILENAME
,
423 * Get notify_sock timeout, in ms.
424 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
427 long get_timeout(void)
429 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
431 if (!got_timeout_env
) {
432 str_timeout
= getenv("LTTNG_UST_REGISTER_TIMEOUT");
436 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
437 return constructor_delay_ms
;
441 long get_notify_sock_timeout(void)
443 return get_timeout();
447 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
450 int get_constructor_timeout(struct timespec
*constructor_timeout
)
452 long constructor_delay_ms
;
455 constructor_delay_ms
= get_timeout();
457 switch (constructor_delay_ms
) {
458 case -1:/* fall-through */
460 return constructor_delay_ms
;
466 * If we are unable to find the current time, don't wait.
468 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
473 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
474 constructor_timeout
->tv_nsec
+=
475 (constructor_delay_ms
% 1000UL) * 1000000UL;
476 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
477 constructor_timeout
->tv_sec
++;
478 constructor_timeout
->tv_nsec
-= 1000000000UL;
480 /* Timeout wait (constructor_delay_ms). */
485 int register_to_sessiond(int socket
, enum ustctl_socket_type type
)
487 return ustcomm_send_reg_msg(socket
,
490 lttng_alignof(uint8_t) * CHAR_BIT
,
491 lttng_alignof(uint16_t) * CHAR_BIT
,
492 lttng_alignof(uint32_t) * CHAR_BIT
,
493 lttng_alignof(uint64_t) * CHAR_BIT
,
494 lttng_alignof(unsigned long) * CHAR_BIT
);
498 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
502 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
505 DBG("message successfully sent");
508 if (len
== -ECONNRESET
) {
509 DBG("remote end closed connection");
514 DBG("incorrect message size: %zd", len
);
520 int handle_register_done(struct sock_info
*sock_info
)
524 if (sock_info
->constructor_sem_posted
)
526 sock_info
->constructor_sem_posted
= 1;
527 if (uatomic_read(&sem_count
) <= 0) {
530 ret
= uatomic_add_return(&sem_count
, -1);
532 ret
= sem_post(&constructor_wait
);
539 * Only execute pending statedump after the constructor semaphore has
540 * been posted by each listener thread. This means statedump will only
541 * be performed after the "registration done" command is received from
542 * each session daemon the application is connected to.
544 * This ensures we don't run into deadlock issues with the dynamic
545 * loader mutex, which is held while the constructor is called and
546 * waiting on the constructor semaphore. All operations requiring this
547 * dynamic loader lock need to be postponed using this mechanism.
550 void handle_pending_statedump(struct sock_info
*sock_info
)
552 int ctor_passed
= sock_info
->constructor_sem_posted
;
554 if (ctor_passed
&& sock_info
->statedump_pending
) {
555 sock_info
->statedump_pending
= 0;
556 pthread_mutex_lock(&ust_fork_mutex
);
557 lttng_handle_pending_statedump(sock_info
);
558 pthread_mutex_unlock(&ust_fork_mutex
);
563 int handle_message(struct sock_info
*sock_info
,
564 int sock
, struct ustcomm_ust_msg
*lum
)
567 const struct lttng_ust_objd_ops
*ops
;
568 struct ustcomm_ust_reply lur
;
572 memset(&lur
, 0, sizeof(lur
));
575 ret
= -LTTNG_UST_ERR_EXITING
;
579 ops
= objd_ops(lum
->handle
);
586 case LTTNG_UST_REGISTER_DONE
:
587 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
588 ret
= handle_register_done(sock_info
);
592 case LTTNG_UST_RELEASE
:
593 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
596 ret
= lttng_ust_objd_unref(lum
->handle
, 1);
598 case LTTNG_UST_FILTER
:
600 /* Receive filter data */
601 struct lttng_ust_filter_bytecode_node
*bytecode
;
603 if (lum
->u
.filter
.data_size
> FILTER_BYTECODE_MAX_LEN
) {
604 ERR("Filter data size is too large: %u bytes",
605 lum
->u
.filter
.data_size
);
610 if (lum
->u
.filter
.reloc_offset
> lum
->u
.filter
.data_size
) {
611 ERR("Filter reloc offset %u is not within data",
612 lum
->u
.filter
.reloc_offset
);
617 bytecode
= zmalloc(sizeof(*bytecode
) + lum
->u
.filter
.data_size
);
622 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
,
623 lum
->u
.filter
.data_size
);
625 case 0: /* orderly shutdown */
630 if (len
== lum
->u
.filter
.data_size
) {
631 DBG("filter data received");
633 } else if (len
< 0) {
634 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
635 if (len
== -ECONNRESET
) {
636 ERR("%s remote end closed connection", sock_info
->name
);
645 DBG("incorrect filter data message size: %zd", len
);
651 bytecode
->bc
.len
= lum
->u
.filter
.data_size
;
652 bytecode
->bc
.reloc_offset
= lum
->u
.filter
.reloc_offset
;
653 bytecode
->bc
.seqnum
= lum
->u
.filter
.seqnum
;
655 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
656 (unsigned long) bytecode
,
661 /* don't free bytecode if everything went fine. */
668 case LTTNG_UST_EXCLUSION
:
670 /* Receive exclusion names */
671 struct lttng_ust_excluder_node
*node
;
674 count
= lum
->u
.exclusion
.count
;
676 /* There are no names to read */
680 node
= zmalloc(sizeof(*node
) +
681 count
* LTTNG_UST_SYM_NAME_LEN
);
686 node
->excluder
.count
= count
;
687 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
688 count
* LTTNG_UST_SYM_NAME_LEN
);
690 case 0: /* orderly shutdown */
695 if (len
== count
* LTTNG_UST_SYM_NAME_LEN
) {
696 DBG("Exclusion data received");
698 } else if (len
< 0) {
699 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
700 if (len
== -ECONNRESET
) {
701 ERR("%s remote end closed connection", sock_info
->name
);
710 DBG("Incorrect exclusion data message size: %zd", len
);
717 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
718 (unsigned long) node
,
723 /* Don't free exclusion data if everything went fine. */
730 case LTTNG_UST_CHANNEL
:
735 len
= ustcomm_recv_channel_from_sessiond(sock
,
736 &chan_data
, lum
->u
.channel
.len
,
739 case 0: /* orderly shutdown */
743 if (len
== lum
->u
.channel
.len
) {
744 DBG("channel data received");
746 } else if (len
< 0) {
747 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
748 if (len
== -ECONNRESET
) {
749 ERR("%s remote end closed connection", sock_info
->name
);
756 DBG("incorrect channel data message size: %zd", len
);
761 args
.channel
.chan_data
= chan_data
;
762 args
.channel
.wakeup_fd
= wakeup_fd
;
764 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
765 (unsigned long) &lum
->u
,
771 case LTTNG_UST_STREAM
:
773 /* Receive shm_fd, wakeup_fd */
774 ret
= ustcomm_recv_stream_from_sessiond(sock
,
777 &args
.stream
.wakeup_fd
);
782 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
783 (unsigned long) &lum
->u
,
791 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
792 (unsigned long) &lum
->u
,
799 lur
.handle
= lum
->handle
;
803 lur
.ret_code
= LTTNG_UST_OK
;
806 * Use -LTTNG_UST_ERR as wildcard for UST internal
807 * error that are not caused by the transport, except if
808 * we already have a more precise error message to
811 if (ret
> -LTTNG_UST_ERR
) {
812 /* Translate code to UST error. */
815 lur
.ret_code
= -LTTNG_UST_ERR_EXIST
;
818 lur
.ret_code
= -LTTNG_UST_ERR_INVAL
;
821 lur
.ret_code
= -LTTNG_UST_ERR_NOENT
;
824 lur
.ret_code
= -LTTNG_UST_ERR_PERM
;
827 lur
.ret_code
= -LTTNG_UST_ERR_NOSYS
;
830 lur
.ret_code
= -LTTNG_UST_ERR
;
839 case LTTNG_UST_TRACER_VERSION
:
840 lur
.u
.version
= lum
->u
.version
;
842 case LTTNG_UST_TRACEPOINT_LIST_GET
:
843 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
847 DBG("Return value: %d", lur
.ret_val
);
848 ret
= send_reply(sock
, &lur
);
850 DBG("error sending reply");
855 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
858 if (lur
.ret_code
== LTTNG_UST_OK
) {
860 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
:
861 len
= ustcomm_send_unix_sock(sock
,
862 &args
.field_list
.entry
,
863 sizeof(args
.field_list
.entry
));
868 if (len
!= sizeof(args
.field_list
.entry
)) {
879 * Performed delayed statedump operations outside of the UST
880 * lock. We need to take the dynamic loader lock before we take
881 * the UST lock internally within handle_pending_statedump().
883 handle_pending_statedump(sock_info
);
889 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
893 if (sock_info
->root_handle
!= -1) {
894 ret
= lttng_ust_objd_unref(sock_info
->root_handle
, 1);
896 ERR("Error unref root handle");
898 sock_info
->root_handle
= -1;
900 sock_info
->constructor_sem_posted
= 0;
903 * wait_shm_mmap, socket and notify socket are used by listener
904 * threads outside of the ust lock, so we cannot tear them down
905 * ourselves, because we cannot join on these threads. Leave
906 * responsibility of cleaning up these resources to the OS
912 if (sock_info
->socket
!= -1) {
913 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
915 ERR("Error closing ust cmd socket");
917 sock_info
->socket
= -1;
919 if (sock_info
->notify_socket
!= -1) {
920 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
922 ERR("Error closing ust notify socket");
924 sock_info
->notify_socket
= -1;
926 if (sock_info
->wait_shm_mmap
) {
929 page_size
= sysconf(_SC_PAGE_SIZE
);
931 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
933 ERR("Error unmapping wait shm");
936 sock_info
->wait_shm_mmap
= NULL
;
941 * Using fork to set umask in the child process (not multi-thread safe).
942 * We deal with the shm_open vs ftruncate race (happening when the
943 * sessiond owns the shm and does not let everybody modify it, to ensure
944 * safety against shm_unlink) by simply letting the mmap fail and
945 * retrying after a few seconds.
946 * For global shm, everybody has rw access to it until the sessiond
950 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
952 int wait_shm_fd
, ret
;
956 * Try to open read-only.
958 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
959 if (wait_shm_fd
>= 0) {
962 size_t bytes_read
= 0;
965 * Try to read the fd. If unable to do so, try opening
969 len
= read(wait_shm_fd
,
970 &((char *) &tmp_read
)[bytes_read
],
971 sizeof(tmp_read
) - bytes_read
);
975 } while ((len
< 0 && errno
== EINTR
)
976 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
977 if (bytes_read
!= sizeof(tmp_read
)) {
978 ret
= close(wait_shm_fd
);
980 ERR("close wait_shm_fd");
985 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
987 * Real-only open did not work, and it's not because the
988 * entry was not present. It's a failure that prohibits
991 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
997 * If the open failed because the file did not exist, or because
998 * the file was not truncated yet, try creating it ourself.
1000 URCU_TLS(lttng_ust_nest_count
)++;
1002 URCU_TLS(lttng_ust_nest_count
)--;
1007 * Parent: wait for child to return, in which case the
1008 * shared memory map will have been created.
1010 pid
= wait(&status
);
1011 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
1016 * Try to open read-only again after creation.
1018 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1019 if (wait_shm_fd
< 0) {
1021 * Real-only open did not work. It's a failure
1022 * that prohibits using shm.
1024 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1028 } else if (pid
== 0) {
1032 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
1033 if (sock_info
->global
)
1034 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
1036 * We're alone in a child process, so we can modify the
1037 * process-wide umask.
1039 umask(~create_mode
);
1041 * Try creating shm (or get rw access).
1042 * We don't do an exclusive open, because we allow other
1043 * processes to create+ftruncate it concurrently.
1045 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
1046 O_RDWR
| O_CREAT
, create_mode
);
1047 if (wait_shm_fd
>= 0) {
1048 ret
= ftruncate(wait_shm_fd
, mmap_size
);
1050 PERROR("ftruncate");
1051 _exit(EXIT_FAILURE
);
1053 _exit(EXIT_SUCCESS
);
1056 * For local shm, we need to have rw access to accept
1057 * opening it: this means the local sessiond will be
1058 * able to wake us up. For global shm, we open it even
1059 * if rw access is not granted, because the root.root
1060 * sessiond will be able to override all rights and wake
1063 if (!sock_info
->global
&& errno
!= EACCES
) {
1064 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1065 _exit(EXIT_FAILURE
);
1068 * The shm exists, but we cannot open it RW. Report
1071 _exit(EXIT_SUCCESS
);
1076 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
1077 struct stat statbuf
;
1080 * Ensure that our user is the owner of the shm file for
1081 * local shm. If we do not own the file, it means our
1082 * sessiond will not have access to wake us up (there is
1083 * probably a rogue process trying to fake our
1084 * sessiond). Fallback to polling method in this case.
1086 ret
= fstat(wait_shm_fd
, &statbuf
);
1091 if (statbuf
.st_uid
!= getuid())
1097 ret
= close(wait_shm_fd
);
1099 PERROR("Error closing fd");
1105 char *get_map_shm(struct sock_info
*sock_info
)
1108 int wait_shm_fd
, ret
;
1109 char *wait_shm_mmap
;
1111 page_size
= sysconf(_SC_PAGE_SIZE
);
1112 if (page_size
< 0) {
1116 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1117 if (wait_shm_fd
< 0) {
1120 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1121 MAP_SHARED
, wait_shm_fd
, 0);
1122 /* close shm fd immediately after taking the mmap reference */
1123 ret
= close(wait_shm_fd
);
1125 PERROR("Error closing fd");
1127 if (wait_shm_mmap
== MAP_FAILED
) {
1128 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1131 return wait_shm_mmap
;
1138 void wait_for_sessiond(struct sock_info
*sock_info
)
1143 if (wait_poll_fallback
) {
1146 if (!sock_info
->wait_shm_mmap
) {
1147 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
1148 if (!sock_info
->wait_shm_mmap
)
1153 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1154 /* Wait for futex wakeup */
1155 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
))
1158 while (futex_async((int32_t *) sock_info
->wait_shm_mmap
,
1159 FUTEX_WAIT
, 0, NULL
, NULL
, 0)) {
1162 /* Value already changed. */
1165 /* Retry if interrupted by signal. */
1166 break; /* Get out of switch. */
1168 wait_poll_fallback
= 1;
1170 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1171 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1172 "Please upgrade your kernel "
1173 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1174 "mainline). LTTng-UST will use polling mode fallback.");
1193 * This thread does not allocate any resource, except within
1194 * handle_message, within mutex protection. This mutex protects against
1196 * The other moment it allocates resources is at socket connection, which
1197 * is also protected by the mutex.
1200 void *ust_listener_thread(void *arg
)
1202 struct sock_info
*sock_info
= arg
;
1203 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
1206 /* Restart trying to connect to the session daemon */
1208 if (prev_connect_failed
) {
1209 /* Wait for sessiond availability with pipe */
1210 wait_for_sessiond(sock_info
);
1214 * Sleep for 5 seconds before retrying after a
1215 * sequence of failure / wait / failure. This
1216 * deals with a killed or broken session daemon.
1221 prev_connect_failed
= 0;
1224 if (sock_info
->socket
!= -1) {
1225 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1227 ERR("Error closing %s ust cmd socket",
1230 sock_info
->socket
= -1;
1232 if (sock_info
->notify_socket
!= -1) {
1233 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1235 ERR("Error closing %s ust notify socket",
1238 sock_info
->notify_socket
= -1;
1242 * Register. We need to perform both connect and sending
1243 * registration message before doing the next connect otherwise
1244 * we may reach unix socket connect queue max limits and block
1245 * on the 2nd connect while the session daemon is awaiting the
1246 * first connect registration message.
1248 /* Connect cmd socket */
1249 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1251 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1252 prev_connect_failed
= 1;
1259 * If we cannot find the sessiond daemon, don't delay
1260 * constructor execution.
1262 ret
= handle_register_done(sock_info
);
1267 sock_info
->socket
= ret
;
1274 * Create only one root handle per listener thread for the whole
1275 * process lifetime, so we ensure we get ID which is statically
1276 * assigned to the root handle.
1278 if (sock_info
->root_handle
== -1) {
1279 ret
= lttng_abi_create_root_handle();
1281 ERR("Error creating root handle");
1284 sock_info
->root_handle
= ret
;
1287 ret
= register_to_sessiond(sock_info
->socket
, USTCTL_SOCKET_CMD
);
1289 ERR("Error registering to %s ust cmd socket",
1291 prev_connect_failed
= 1;
1293 * If we cannot register to the sessiond daemon, don't
1294 * delay constructor execution.
1296 ret
= handle_register_done(sock_info
);
1304 /* Connect notify socket */
1305 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1307 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1308 prev_connect_failed
= 1;
1315 * If we cannot find the sessiond daemon, don't delay
1316 * constructor execution.
1318 ret
= handle_register_done(sock_info
);
1323 sock_info
->notify_socket
= ret
;
1325 timeout
= get_notify_sock_timeout();
1328 * Give at least 10ms to sessiond to reply to
1333 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
1336 WARN("Error setting socket receive timeout");
1338 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
1341 WARN("Error setting socket send timeout");
1343 } else if (timeout
< -1) {
1344 WARN("Unsupported timeout value %ld", timeout
);
1351 ret
= register_to_sessiond(sock_info
->notify_socket
,
1352 USTCTL_SOCKET_NOTIFY
);
1354 ERR("Error registering to %s ust notify socket",
1356 prev_connect_failed
= 1;
1358 * If we cannot register to the sessiond daemon, don't
1359 * delay constructor execution.
1361 ret
= handle_register_done(sock_info
);
1366 sock
= sock_info
->socket
;
1372 struct ustcomm_ust_msg lum
;
1374 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
1376 case 0: /* orderly shutdown */
1377 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
1382 * Either sessiond has shutdown or refused us by closing the socket.
1383 * In either case, we don't want to delay construction execution,
1384 * and we need to wait before retry.
1386 prev_connect_failed
= 1;
1388 * If we cannot register to the sessiond daemon, don't
1389 * delay constructor execution.
1391 ret
= handle_register_done(sock_info
);
1396 print_cmd(lum
.cmd
, lum
.handle
);
1397 ret
= handle_message(sock_info
, sock
, &lum
);
1399 ERR("Error handling message for %s socket",
1402 * Close socket if protocol error is
1410 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1412 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
1414 if (len
== -ECONNRESET
) {
1415 DBG("%s remote end closed connection", sock_info
->name
);
1426 /* Cleanup socket handles before trying to reconnect */
1427 lttng_ust_objd_table_owner_cleanup(sock_info
);
1429 goto restart
; /* try to reconnect */
1434 pthread_mutex_lock(&ust_exit_mutex
);
1435 sock_info
->thread_active
= 0;
1436 pthread_mutex_unlock(&ust_exit_mutex
);
1441 * Weak symbol to call when the ust malloc wrapper is not loaded.
1443 __attribute__((weak
))
1444 void lttng_ust_malloc_wrapper_init(void)
1449 * sessiond monitoring thread: monitor presence of global and per-user
1450 * sessiond by polling the application common named pipe.
1452 void __attribute__((constructor
)) lttng_ust_init(void)
1454 struct timespec constructor_timeout
;
1455 sigset_t sig_all_blocked
, orig_parent_mask
;
1456 pthread_attr_t thread_attr
;
1460 if (uatomic_xchg(&initialized
, 1) == 1)
1464 * Fixup interdependency between TLS fixup mutex (which happens
1465 * to be the dynamic linker mutex) and ust_lock, taken within
1468 lttng_fixup_urcu_bp_tls();
1469 lttng_fixup_ringbuffer_tls();
1470 lttng_fixup_vtid_tls();
1471 lttng_fixup_nest_count_tls();
1472 lttng_fixup_procname_tls();
1473 lttng_fixup_ust_mutex_nest_tls();
1476 * We want precise control over the order in which we construct
1477 * our sub-libraries vs starting to receive commands from
1478 * sessiond (otherwise leading to errors when trying to create
1479 * sessiond before the init functions are completed).
1483 lttng_ust_baddr_statedump_init();
1484 lttng_ring_buffer_metadata_client_init();
1485 lttng_ring_buffer_client_overwrite_init();
1486 lttng_ring_buffer_client_overwrite_rt_init();
1487 lttng_ring_buffer_client_discard_init();
1488 lttng_ring_buffer_client_discard_rt_init();
1489 lttng_perf_counter_init();
1490 lttng_context_init();
1492 * Invoke ust malloc wrapper init before starting other threads.
1494 lttng_ust_malloc_wrapper_init();
1496 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
1498 ret
= sem_init(&constructor_wait
, 0, 0);
1501 ret
= setup_local_apps();
1503 DBG("local apps setup returned %d", ret
);
1506 /* A new thread created by pthread_create inherits the signal mask
1507 * from the parent. To avoid any signal being received by the
1508 * listener thread, we block all signals temporarily in the parent,
1509 * while we create the listener thread.
1511 sigfillset(&sig_all_blocked
);
1512 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
1514 ERR("pthread_sigmask: %s", strerror(ret
));
1517 ret
= pthread_attr_init(&thread_attr
);
1519 ERR("pthread_attr_init: %s", strerror(ret
));
1521 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
1523 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
1526 pthread_mutex_lock(&ust_exit_mutex
);
1527 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
1528 ust_listener_thread
, &global_apps
);
1530 ERR("pthread_create global: %s", strerror(ret
));
1532 global_apps
.thread_active
= 1;
1533 pthread_mutex_unlock(&ust_exit_mutex
);
1535 if (local_apps
.allowed
) {
1536 pthread_mutex_lock(&ust_exit_mutex
);
1537 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
1538 ust_listener_thread
, &local_apps
);
1540 ERR("pthread_create local: %s", strerror(ret
));
1542 local_apps
.thread_active
= 1;
1543 pthread_mutex_unlock(&ust_exit_mutex
);
1545 handle_register_done(&local_apps
);
1547 ret
= pthread_attr_destroy(&thread_attr
);
1549 ERR("pthread_attr_destroy: %s", strerror(ret
));
1552 /* Restore original signal mask in parent */
1553 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
1555 ERR("pthread_sigmask: %s", strerror(ret
));
1558 switch (timeout_mode
) {
1559 case 1: /* timeout wait */
1561 ret
= sem_timedwait(&constructor_wait
,
1562 &constructor_timeout
);
1563 } while (ret
< 0 && errno
== EINTR
);
1564 if (ret
< 0 && errno
== ETIMEDOUT
) {
1565 ERR("Timed out waiting for lttng-sessiond");
1570 case -1:/* wait forever */
1572 ret
= sem_wait(&constructor_wait
);
1573 } while (ret
< 0 && errno
== EINTR
);
1576 case 0: /* no timeout */
1582 void lttng_ust_cleanup(int exiting
)
1584 cleanup_sock_info(&global_apps
, exiting
);
1585 cleanup_sock_info(&local_apps
, exiting
);
1587 * The teardown in this function all affect data structures
1588 * accessed under the UST lock by the listener thread. This
1589 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1590 * that none of these threads are accessing this data at this
1593 lttng_ust_abi_exit();
1594 lttng_ust_events_exit();
1595 lttng_context_exit();
1596 lttng_perf_counter_exit();
1597 lttng_ring_buffer_client_discard_rt_exit();
1598 lttng_ring_buffer_client_discard_exit();
1599 lttng_ring_buffer_client_overwrite_rt_exit();
1600 lttng_ring_buffer_client_overwrite_exit();
1601 lttng_ring_buffer_metadata_client_exit();
1602 lttng_ust_baddr_statedump_destroy();
1605 /* Reinitialize values for fork */
1607 lttng_ust_comm_should_quit
= 0;
1612 void __attribute__((destructor
)) lttng_ust_exit(void)
1617 * Using pthread_cancel here because:
1618 * A) we don't want to hang application teardown.
1619 * B) the thread is not allocating any resource.
1623 * Require the communication thread to quit. Synchronize with
1624 * mutexes to ensure it is not in a mutex critical section when
1625 * pthread_cancel is later called.
1628 lttng_ust_comm_should_quit
= 1;
1631 pthread_mutex_lock(&ust_exit_mutex
);
1632 /* cancel threads */
1633 if (global_apps
.thread_active
) {
1634 ret
= pthread_cancel(global_apps
.ust_listener
);
1636 ERR("Error cancelling global ust listener thread: %s",
1639 global_apps
.thread_active
= 0;
1642 if (local_apps
.thread_active
) {
1643 ret
= pthread_cancel(local_apps
.ust_listener
);
1645 ERR("Error cancelling local ust listener thread: %s",
1648 local_apps
.thread_active
= 0;
1651 pthread_mutex_unlock(&ust_exit_mutex
);
1654 * Do NOT join threads: use of sys_futex makes it impossible to
1655 * join the threads without using async-cancel, but async-cancel
1656 * is delivered by a signal, which could hit the target thread
1657 * anywhere in its code path, including while the ust_lock() is
1658 * held, causing a deadlock for the other thread. Let the OS
1659 * cleanup the threads if there are stalled in a syscall.
1661 lttng_ust_cleanup(1);
1665 * We exclude the worker threads across fork and clone (except
1666 * CLONE_VM), because these system calls only keep the forking thread
1667 * running in the child. Therefore, we don't want to call fork or clone
1668 * in the middle of an tracepoint or ust tracing state modification.
1669 * Holding this mutex protects these structures across fork and clone.
1671 void ust_before_fork(sigset_t
*save_sigset
)
1674 * Disable signals. This is to avoid that the child intervenes
1675 * before it is properly setup for tracing. It is safer to
1676 * disable all signals, because then we know we are not breaking
1677 * anything by restoring the original mask.
1682 if (URCU_TLS(lttng_ust_nest_count
))
1684 /* Disable signals */
1685 sigfillset(&all_sigs
);
1686 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
1688 PERROR("sigprocmask");
1691 pthread_mutex_lock(&ust_fork_mutex
);
1694 rcu_bp_before_fork();
1697 static void ust_after_fork_common(sigset_t
*restore_sigset
)
1701 DBG("process %d", getpid());
1704 pthread_mutex_unlock(&ust_fork_mutex
);
1706 /* Restore signals */
1707 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
1709 PERROR("sigprocmask");
1713 void ust_after_fork_parent(sigset_t
*restore_sigset
)
1715 if (URCU_TLS(lttng_ust_nest_count
))
1717 DBG("process %d", getpid());
1718 rcu_bp_after_fork_parent();
1719 /* Release mutexes and reenable signals */
1720 ust_after_fork_common(restore_sigset
);
1724 * After fork, in the child, we need to cleanup all the leftover state,
1725 * except the worker thread which already magically disappeared thanks
1726 * to the weird Linux fork semantics. After tyding up, we call
1727 * lttng_ust_init() again to start over as a new PID.
1729 * This is meant for forks() that have tracing in the child between the
1730 * fork and following exec call (if there is any).
1732 void ust_after_fork_child(sigset_t
*restore_sigset
)
1734 if (URCU_TLS(lttng_ust_nest_count
))
1736 DBG("process %d", getpid());
1737 /* Release urcu mutexes */
1738 rcu_bp_after_fork_child();
1739 lttng_ust_cleanup(0);
1740 lttng_context_vtid_reset();
1741 /* Release mutexes and reenable signals */
1742 ust_after_fork_common(restore_sigset
);
1746 void lttng_ust_sockinfo_session_enabled(void *owner
)
1748 struct sock_info
*sock_info
= owner
;
1749 sock_info
->statedump_pending
= 1;