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>
45 #include <usterr-signal-safe.h>
46 #include "tracepoint-internal.h"
47 #include "ltt-tracer-core.h"
51 * Has lttng ust comm constructor been called ?
53 static int initialized
;
56 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
57 * Held when handling a command, also held by fork() to deal with
58 * removal of threads, and by exit path.
61 /* Should the ust comm thread quit ? */
62 static int lttng_ust_comm_should_quit
;
65 * Wait for either of these before continuing to the main
67 * - the register_done message from sessiond daemon
68 * (will let the sessiond daemon enable sessions before main
70 * - sessiond daemon is not reachable.
71 * - timeout (ensuring applications are resilient to session
74 static sem_t constructor_wait
;
76 * Doing this for both the global and local sessiond.
78 static int sem_count
= { 2 };
81 * Info about socket and associated listener thread.
85 pthread_t ust_listener
; /* listener thread */
87 int constructor_sem_posted
;
91 char sock_path
[PATH_MAX
];
94 char wait_shm_path
[PATH_MAX
];
98 /* Socket from app (connect) to session daemon (listen) for communication */
99 struct sock_info global_apps
= {
106 .sock_path
= DEFAULT_GLOBAL_APPS_UNIX_SOCK
,
109 .wait_shm_path
= DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH
,
112 /* TODO: allow global_apps_sock_path override */
114 struct sock_info local_apps
= {
118 .allowed
= 0, /* Check setuid bit first */
123 static int wait_poll_fallback
;
125 extern void ltt_ring_buffer_client_overwrite_init(void);
126 extern void ltt_ring_buffer_client_discard_init(void);
127 extern void ltt_ring_buffer_metadata_client_init(void);
128 extern void ltt_ring_buffer_client_overwrite_exit(void);
129 extern void ltt_ring_buffer_client_discard_exit(void);
130 extern void ltt_ring_buffer_metadata_client_exit(void);
133 int setup_local_apps(void)
135 const char *home_dir
;
140 * Disallow per-user tracing for setuid binaries.
142 if (uid
!= geteuid()) {
143 local_apps
.allowed
= 0;
146 local_apps
.allowed
= 1;
148 home_dir
= (const char *) getenv("HOME");
151 snprintf(local_apps
.sock_path
, PATH_MAX
,
152 DEFAULT_HOME_APPS_UNIX_SOCK
, home_dir
);
153 snprintf(local_apps
.wait_shm_path
, PATH_MAX
,
154 DEFAULT_HOME_APPS_WAIT_SHM_PATH
, uid
);
159 int register_app_to_sessiond(int socket
)
169 uint32_t bits_per_long
;
170 char name
[16]; /* process name */
173 reg_msg
.major
= LTTNG_UST_COMM_VERSION_MAJOR
;
174 reg_msg
.minor
= LTTNG_UST_COMM_VERSION_MINOR
;
175 reg_msg
.pid
= getpid();
176 reg_msg
.ppid
= getppid();
177 reg_msg
.uid
= getuid();
178 reg_msg
.gid
= getgid();
179 reg_msg
.bits_per_long
= CAA_BITS_PER_LONG
;
180 lttng_ust_getprocname(reg_msg
.name
);
182 ret
= ustcomm_send_unix_sock(socket
, ®_msg
, sizeof(reg_msg
));
183 if (ret
>= 0 && ret
!= sizeof(reg_msg
))
189 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
193 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
196 DBG("message successfully sent");
199 if (errno
== ECONNRESET
) {
200 printf("remote end closed connection\n");
205 printf("incorrect message size: %zd\n", len
);
211 int handle_register_done(struct sock_info
*sock_info
)
215 if (sock_info
->constructor_sem_posted
)
217 sock_info
->constructor_sem_posted
= 1;
218 if (uatomic_read(&sem_count
) <= 0) {
221 ret
= uatomic_add_return(&sem_count
, -1);
223 ret
= sem_post(&constructor_wait
);
230 int handle_message(struct sock_info
*sock_info
,
231 int sock
, struct ustcomm_ust_msg
*lum
)
234 const struct lttng_ust_objd_ops
*ops
;
235 struct ustcomm_ust_reply lur
;
241 memset(&lur
, 0, sizeof(lur
));
243 if (lttng_ust_comm_should_quit
) {
248 ops
= objd_ops(lum
->handle
);
255 case LTTNG_UST_REGISTER_DONE
:
256 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
257 ret
= handle_register_done(sock_info
);
261 case LTTNG_UST_RELEASE
:
262 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
265 ret
= lttng_ust_objd_unref(lum
->handle
);
269 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
270 (unsigned long) &lum
->u
,
278 lur
.handle
= lum
->handle
;
282 lur
.ret_code
= USTCOMM_OK
;
284 //lur.ret_code = USTCOMM_SESSION_FAIL;
288 case LTTNG_UST_STREAM
:
290 * Special-case reply to send stream info.
293 lur
.u
.stream
.memory_map_size
= *args
.stream
.memory_map_size
;
294 shm_fd
= *args
.stream
.shm_fd
;
295 wait_fd
= *args
.stream
.wait_fd
;
297 case LTTNG_UST_METADATA
:
298 case LTTNG_UST_CHANNEL
:
299 lur
.u
.channel
.memory_map_size
= *args
.channel
.memory_map_size
;
300 shm_fd
= *args
.channel
.shm_fd
;
301 wait_fd
= *args
.channel
.wait_fd
;
303 case LTTNG_UST_TRACER_VERSION
:
304 lur
.u
.version
= lum
->u
.version
;
306 case LTTNG_UST_TRACEPOINT_LIST_GET
:
307 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
310 ret
= send_reply(sock
, &lur
);
312 perror("error sending reply");
316 if ((lum
->cmd
== LTTNG_UST_STREAM
317 || lum
->cmd
== LTTNG_UST_CHANNEL
318 || lum
->cmd
== LTTNG_UST_METADATA
)
319 && lur
.ret_code
== USTCOMM_OK
) {
320 /* we also need to send the file descriptors. */
321 ret
= ustcomm_send_fds_unix_sock(sock
,
325 perror("send shm_fd");
328 ret
= ustcomm_send_fds_unix_sock(sock
,
332 perror("send wait_fd");
337 * We still have the memory map reference, and the fds have been
338 * sent to the sessiond. We can therefore close those fds. Note
339 * that we keep the write side of the wait_fd open, but close
342 if (lur
.ret_code
== USTCOMM_OK
) {
344 case LTTNG_UST_STREAM
:
348 PERROR("Error closing stream shm_fd");
350 *args
.stream
.shm_fd
= -1;
353 ret
= close(wait_fd
);
355 PERROR("Error closing stream wait_fd");
357 *args
.stream
.wait_fd
= -1;
360 case LTTNG_UST_METADATA
:
361 case LTTNG_UST_CHANNEL
:
365 PERROR("Error closing channel shm_fd");
367 *args
.channel
.shm_fd
= -1;
370 ret
= close(wait_fd
);
372 PERROR("Error closing channel wait_fd");
374 *args
.channel
.wait_fd
= -1;
386 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
390 if (sock_info
->socket
!= -1) {
391 ret
= close(sock_info
->socket
);
393 ERR("Error closing apps socket");
395 sock_info
->socket
= -1;
397 if (sock_info
->root_handle
!= -1) {
398 ret
= lttng_ust_objd_unref(sock_info
->root_handle
);
400 ERR("Error unref root handle");
402 sock_info
->root_handle
= -1;
404 sock_info
->constructor_sem_posted
= 0;
406 * wait_shm_mmap is used by listener threads outside of the
407 * ust lock, so we cannot tear it down ourselves, because we
408 * cannot join on these threads. Leave this task to the OS
411 if (!exiting
&& sock_info
->wait_shm_mmap
) {
412 ret
= munmap(sock_info
->wait_shm_mmap
, sysconf(_SC_PAGE_SIZE
));
414 ERR("Error unmapping wait shm");
416 sock_info
->wait_shm_mmap
= NULL
;
421 * Using fork to set umask in the child process (not multi-thread safe).
422 * We deal with the shm_open vs ftruncate race (happening when the
423 * sessiond owns the shm and does not let everybody modify it, to ensure
424 * safety against shm_unlink) by simply letting the mmap fail and
425 * retrying after a few seconds.
426 * For global shm, everybody has rw access to it until the sessiond
430 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
432 int wait_shm_fd
, ret
;
436 * Try to open read-only.
438 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
439 if (wait_shm_fd
>= 0) {
441 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
443 * Real-only open did not work, and it's not because the
444 * entry was not present. It's a failure that prohibits
447 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
451 * If the open failed because the file did not exist, try
452 * creating it ourself.
459 * Parent: wait for child to return, in which case the
460 * shared memory map will have been created.
463 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
468 * Try to open read-only again after creation.
470 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
471 if (wait_shm_fd
< 0) {
473 * Real-only open did not work. It's a failure
474 * that prohibits using shm.
476 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
480 } else if (pid
== 0) {
484 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
485 if (sock_info
->global
)
486 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
488 * We're alone in a child process, so we can modify the
489 * process-wide umask.
493 * Try creating shm (or get rw access).
494 * We don't do an exclusive open, because we allow other
495 * processes to create+ftruncate it concurrently.
497 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
498 O_RDWR
| O_CREAT
, create_mode
);
499 if (wait_shm_fd
>= 0) {
500 ret
= ftruncate(wait_shm_fd
, mmap_size
);
508 * For local shm, we need to have rw access to accept
509 * opening it: this means the local sessiond will be
510 * able to wake us up. For global shm, we open it even
511 * if rw access is not granted, because the root.root
512 * sessiond will be able to override all rights and wake
515 if (!sock_info
->global
&& errno
!= EACCES
) {
516 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
520 * The shm exists, but we cannot open it RW. Report
528 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
532 * Ensure that our user is the owner of the shm file for
533 * local shm. If we do not own the file, it means our
534 * sessiond will not have access to wake us up (there is
535 * probably a rogue process trying to fake our
536 * sessiond). Fallback to polling method in this case.
538 ret
= fstat(wait_shm_fd
, &statbuf
);
543 if (statbuf
.st_uid
!= getuid())
549 ret
= close(wait_shm_fd
);
551 PERROR("Error closing fd");
557 char *get_map_shm(struct sock_info
*sock_info
)
559 size_t mmap_size
= sysconf(_SC_PAGE_SIZE
);
560 int wait_shm_fd
, ret
;
563 wait_shm_fd
= get_wait_shm(sock_info
, mmap_size
);
564 if (wait_shm_fd
< 0) {
567 wait_shm_mmap
= mmap(NULL
, mmap_size
, PROT_READ
,
568 MAP_SHARED
, wait_shm_fd
, 0);
569 /* close shm fd immediately after taking the mmap reference */
570 ret
= close(wait_shm_fd
);
572 PERROR("Error closing fd");
574 if (wait_shm_mmap
== MAP_FAILED
) {
575 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
578 return wait_shm_mmap
;
585 void wait_for_sessiond(struct sock_info
*sock_info
)
590 if (lttng_ust_comm_should_quit
) {
593 if (wait_poll_fallback
) {
596 if (!sock_info
->wait_shm_mmap
) {
597 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
598 if (!sock_info
->wait_shm_mmap
)
603 DBG("Waiting for %s apps sessiond", sock_info
->name
);
604 /* Wait for futex wakeup */
605 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
) == 0) {
606 ret
= futex_async((int32_t *) sock_info
->wait_shm_mmap
,
607 FUTEX_WAIT
, 0, NULL
, NULL
, 0);
609 if (errno
== EFAULT
) {
610 wait_poll_fallback
= 1;
612 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
613 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
614 "Please upgrade your kernel "
615 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
616 "mainline). LTTng-UST will use polling mode fallback.");
634 * This thread does not allocate any resource, except within
635 * handle_message, within mutex protection. This mutex protects against
637 * The other moment it allocates resources is at socket connexion, which
638 * is also protected by the mutex.
641 void *ust_listener_thread(void *arg
)
643 struct sock_info
*sock_info
= arg
;
644 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
646 /* Restart trying to connect to the session daemon */
648 if (prev_connect_failed
) {
649 /* Wait for sessiond availability with pipe */
650 wait_for_sessiond(sock_info
);
654 * Sleep for 5 seconds before retrying after a
655 * sequence of failure / wait / failure. This
656 * deals with a killed or broken session daemon.
661 prev_connect_failed
= 0;
665 if (lttng_ust_comm_should_quit
) {
670 if (sock_info
->socket
!= -1) {
671 ret
= close(sock_info
->socket
);
673 ERR("Error closing %s apps socket", sock_info
->name
);
675 sock_info
->socket
= -1;
679 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
681 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
682 prev_connect_failed
= 1;
684 * If we cannot find the sessiond daemon, don't delay
685 * constructor execution.
687 ret
= handle_register_done(sock_info
);
693 sock_info
->socket
= sock
= ret
;
696 * Create only one root handle per listener thread for the whole
699 if (sock_info
->root_handle
== -1) {
700 ret
= lttng_abi_create_root_handle();
702 ERR("Error creating root handle");
706 sock_info
->root_handle
= ret
;
709 ret
= register_app_to_sessiond(sock
);
711 ERR("Error registering to %s apps socket", sock_info
->name
);
712 prev_connect_failed
= 1;
714 * If we cannot register to the sessiond daemon, don't
715 * delay constructor execution.
717 ret
= handle_register_done(sock_info
);
726 struct ustcomm_ust_msg lum
;
728 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
730 case 0: /* orderly shutdown */
731 DBG("%s ltt-sessiond has performed an orderly shutdown\n", sock_info
->name
);
734 * Either sessiond has shutdown or refused us by closing the socket.
735 * In either case, we don't want to delay construction execution,
736 * and we need to wait before retry.
738 prev_connect_failed
= 1;
740 * If we cannot register to the sessiond daemon, don't
741 * delay constructor execution.
743 ret
= handle_register_done(sock_info
);
748 DBG("message received\n");
749 ret
= handle_message(sock_info
, sock
, &lum
);
751 ERR("Error handling message for %s socket", sock_info
->name
);
755 DBG("Receive failed from lttng-sessiond with errno %d", errno
);
756 if (errno
== ECONNRESET
) {
757 ERR("%s remote end closed connection\n", sock_info
->name
);
762 ERR("incorrect message size (%s socket): %zd\n", sock_info
->name
, len
);
768 goto restart
; /* try to reconnect */
774 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
777 int get_timeout(struct timespec
*constructor_timeout
)
779 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
783 str_delay
= getenv("LTTNG_UST_REGISTER_TIMEOUT");
785 constructor_delay_ms
= strtol(str_delay
, NULL
, 10);
788 switch (constructor_delay_ms
) {
789 case -1:/* fall-through */
791 return constructor_delay_ms
;
797 * If we are unable to find the current time, don't wait.
799 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
803 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
804 constructor_timeout
->tv_nsec
+=
805 (constructor_delay_ms
% 1000UL) * 1000000UL;
806 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
807 constructor_timeout
->tv_sec
++;
808 constructor_timeout
->tv_nsec
-= 1000000000UL;
814 * sessiond monitoring thread: monitor presence of global and per-user
815 * sessiond by polling the application common named pipe.
819 void __attribute__((constructor
)) lttng_ust_init(void)
821 struct timespec constructor_timeout
;
825 if (uatomic_xchg(&initialized
, 1) == 1)
829 * We want precise control over the order in which we construct
830 * our sub-libraries vs starting to receive commands from
831 * sessiond (otherwise leading to errors when trying to create
832 * sessiond before the init functions are completed).
836 ltt_ring_buffer_metadata_client_init();
837 ltt_ring_buffer_client_overwrite_init();
838 ltt_ring_buffer_client_discard_init();
840 timeout_mode
= get_timeout(&constructor_timeout
);
842 ret
= sem_init(&constructor_wait
, 0, 0);
845 ret
= setup_local_apps();
847 ERR("Error setting up to local apps");
849 ret
= pthread_create(&local_apps
.ust_listener
, NULL
,
850 ust_listener_thread
, &local_apps
);
852 if (local_apps
.allowed
) {
853 ret
= pthread_create(&global_apps
.ust_listener
, NULL
,
854 ust_listener_thread
, &global_apps
);
856 handle_register_done(&local_apps
);
859 switch (timeout_mode
) {
860 case 1: /* timeout wait */
862 ret
= sem_timedwait(&constructor_wait
,
863 &constructor_timeout
);
864 } while (ret
< 0 && errno
== EINTR
);
865 if (ret
< 0 && errno
== ETIMEDOUT
) {
866 ERR("Timed out waiting for ltt-sessiond");
871 case -1:/* wait forever */
873 ret
= sem_wait(&constructor_wait
);
874 } while (ret
< 0 && errno
== EINTR
);
877 case 0: /* no timeout */
883 void lttng_ust_cleanup(int exiting
)
885 cleanup_sock_info(&global_apps
, exiting
);
886 if (local_apps
.allowed
) {
887 cleanup_sock_info(&local_apps
, exiting
);
890 * The teardown in this function all affect data structures
891 * accessed under the UST lock by the listener thread. This
892 * lock, along with the lttng_ust_comm_should_quit flag, ensure
893 * that none of these threads are accessing this data at this
896 lttng_ust_abi_exit();
897 lttng_ust_events_exit();
898 ltt_ring_buffer_client_discard_exit();
899 ltt_ring_buffer_client_overwrite_exit();
900 ltt_ring_buffer_metadata_client_exit();
903 /* Reinitialize values for fork */
905 lttng_ust_comm_should_quit
= 0;
910 void __attribute__((destructor
)) lttng_ust_exit(void)
915 * Using pthread_cancel here because:
916 * A) we don't want to hang application teardown.
917 * B) the thread is not allocating any resource.
921 * Require the communication thread to quit. Synchronize with
922 * mutexes to ensure it is not in a mutex critical section when
923 * pthread_cancel is later called.
926 lttng_ust_comm_should_quit
= 1;
930 ret
= pthread_cancel(global_apps
.ust_listener
);
932 ERR("Error cancelling global ust listener thread");
934 if (local_apps
.allowed
) {
935 ret
= pthread_cancel(local_apps
.ust_listener
);
937 ERR("Error cancelling local ust listener thread");
941 * Do NOT join threads: use of sys_futex makes it impossible to
942 * join the threads without using async-cancel, but async-cancel
943 * is delivered by a signal, which could hit the target thread
944 * anywhere in its code path, including while the ust_lock() is
945 * held, causing a deadlock for the other thread. Let the OS
946 * cleanup the threads if there are stalled in a syscall.
948 lttng_ust_cleanup(1);
952 * We exclude the worker threads across fork and clone (except
953 * CLONE_VM), because these system calls only keep the forking thread
954 * running in the child. Therefore, we don't want to call fork or clone
955 * in the middle of an tracepoint or ust tracing state modification.
956 * Holding this mutex protects these structures across fork and clone.
958 void ust_before_fork(sigset_t
*save_sigset
)
961 * Disable signals. This is to avoid that the child intervenes
962 * before it is properly setup for tracing. It is safer to
963 * disable all signals, because then we know we are not breaking
964 * anything by restoring the original mask.
969 /* Disable signals */
970 sigfillset(&all_sigs
);
971 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
973 PERROR("sigprocmask");
976 rcu_bp_before_fork();
979 static void ust_after_fork_common(sigset_t
*restore_sigset
)
983 DBG("process %d", getpid());
985 /* Restore signals */
986 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
988 PERROR("sigprocmask");
992 void ust_after_fork_parent(sigset_t
*restore_sigset
)
994 DBG("process %d", getpid());
995 rcu_bp_after_fork_parent();
996 /* Release mutexes and reenable signals */
997 ust_after_fork_common(restore_sigset
);
1001 * After fork, in the child, we need to cleanup all the leftover state,
1002 * except the worker thread which already magically disappeared thanks
1003 * to the weird Linux fork semantics. After tyding up, we call
1004 * lttng_ust_init() again to start over as a new PID.
1006 * This is meant for forks() that have tracing in the child between the
1007 * fork and following exec call (if there is any).
1009 void ust_after_fork_child(sigset_t
*restore_sigset
)
1011 DBG("process %d", getpid());
1012 /* Release urcu mutexes */
1013 rcu_bp_after_fork_child();
1014 lttng_ust_cleanup(0);
1015 lttng_context_vtid_reset();
1016 /* Release mutexes and reenable signals */
1017 ust_after_fork_common(restore_sigset
);