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>
25 #include <sys/prctl.h>
28 #include <sys/types.h>
34 #include <semaphore.h>
38 #include <urcu/uatomic.h>
39 #include <urcu/futex.h>
41 #include <lttng-ust-comm.h>
42 #include <ust/usterr-signal-safe.h>
43 #include <ust/lttng-ust-abi.h>
44 #include <ust/tracepoint.h>
45 #include <ust/tracepoint-internal.h>
47 #include "ltt-tracer-core.h"
50 * Has lttng ust comm constructor been called ?
52 static int initialized
;
55 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
56 * Held when handling a command, also held by fork() to deal with
57 * removal of threads, and by exit path.
60 /* Should the ust comm thread quit ? */
61 static int lttng_ust_comm_should_quit
;
64 * Wait for either of these before continuing to the main
66 * - the register_done message from sessiond daemon
67 * (will let the sessiond daemon enable sessions before main
69 * - sessiond daemon is not reachable.
70 * - timeout (ensuring applications are resilient to session
73 static sem_t constructor_wait
;
75 * Doing this for both the global and local sessiond.
77 static int sem_count
= { 2 };
80 * Info about socket and associated listener thread.
84 pthread_t ust_listener
; /* listener thread */
86 int constructor_sem_posted
;
90 char sock_path
[PATH_MAX
];
93 char wait_shm_path
[PATH_MAX
];
97 /* Socket from app (connect) to session daemon (listen) for communication */
98 struct sock_info global_apps
= {
105 .sock_path
= DEFAULT_GLOBAL_APPS_UNIX_SOCK
,
108 .wait_shm_path
= DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH
,
111 /* TODO: allow global_apps_sock_path override */
113 struct sock_info local_apps
= {
117 .allowed
= 0, /* Check setuid bit first */
122 static int wait_poll_fallback
;
124 extern void ltt_ring_buffer_client_overwrite_init(void);
125 extern void ltt_ring_buffer_client_discard_init(void);
126 extern void ltt_ring_buffer_metadata_client_init(void);
127 extern void ltt_ring_buffer_client_overwrite_exit(void);
128 extern void ltt_ring_buffer_client_discard_exit(void);
129 extern void ltt_ring_buffer_metadata_client_exit(void);
132 int setup_local_apps(void)
134 const char *home_dir
;
139 * Disallow per-user tracing for setuid binaries.
141 if (uid
!= geteuid()) {
142 local_apps
.allowed
= 0;
145 local_apps
.allowed
= 1;
147 home_dir
= (const char *) getenv("HOME");
150 snprintf(local_apps
.sock_path
, PATH_MAX
,
151 DEFAULT_HOME_APPS_UNIX_SOCK
, home_dir
);
152 snprintf(local_apps
.wait_shm_path
, PATH_MAX
,
153 DEFAULT_HOME_APPS_WAIT_SHM_PATH
, uid
);
158 int register_app_to_sessiond(int socket
)
169 char name
[16]; /* process name */
172 reg_msg
.major
= LTTNG_UST_COMM_VERSION_MAJOR
;
173 reg_msg
.minor
= LTTNG_UST_COMM_VERSION_MINOR
;
174 reg_msg
.pid
= getpid();
175 reg_msg
.ppid
= getppid();
176 reg_msg
.uid
= getuid();
177 reg_msg
.gid
= getgid();
178 prctl_ret
= prctl(PR_GET_NAME
, (unsigned long) reg_msg
.name
, 0, 0, 0);
180 ERR("Error executing prctl");
184 ret
= lttcomm_send_unix_sock(socket
, ®_msg
, sizeof(reg_msg
));
185 if (ret
>= 0 && ret
!= sizeof(reg_msg
))
191 int send_reply(int sock
, struct lttcomm_ust_reply
*lur
)
195 len
= lttcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
198 DBG("message successfully sent");
201 if (errno
== ECONNRESET
) {
202 printf("remote end closed connection\n");
207 printf("incorrect message size: %zd\n", len
);
213 int handle_register_done(struct sock_info
*sock_info
)
217 if (sock_info
->constructor_sem_posted
)
219 sock_info
->constructor_sem_posted
= 1;
220 if (uatomic_read(&sem_count
) <= 0) {
223 ret
= uatomic_add_return(&sem_count
, -1);
225 ret
= sem_post(&constructor_wait
);
232 int handle_message(struct sock_info
*sock_info
,
233 int sock
, struct lttcomm_ust_msg
*lum
)
236 const struct objd_ops
*ops
;
237 struct lttcomm_ust_reply lur
;
242 memset(&lur
, 0, sizeof(lur
));
244 if (lttng_ust_comm_should_quit
) {
249 ops
= objd_ops(lum
->handle
);
256 case LTTNG_UST_REGISTER_DONE
:
257 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
258 ret
= handle_register_done(sock_info
);
262 case LTTNG_UST_RELEASE
:
263 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
266 ret
= objd_unref(lum
->handle
);
270 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
271 (unsigned long) &lum
->u
);
278 lur
.handle
= lum
->handle
;
282 lur
.ret_code
= LTTCOMM_OK
;
284 //lur.ret_code = LTTCOMM_SESSION_FAIL;
288 case LTTNG_UST_STREAM
:
290 * Special-case reply to send stream info.
293 lur
.u
.stream
.memory_map_size
= lum
->u
.stream
.memory_map_size
;
294 shm_fd
= lum
->u
.stream
.shm_fd
;
295 wait_fd
= lum
->u
.stream
.wait_fd
;
297 case LTTNG_UST_CHANNEL
:
298 lur
.u
.channel
.memory_map_size
= lum
->u
.channel
.memory_map_size
;
299 shm_fd
= lum
->u
.channel
.shm_fd
;
300 wait_fd
= lum
->u
.channel
.wait_fd
;
303 ret
= send_reply(sock
, &lur
);
305 perror("error sending reply");
309 if ((lum
->cmd
== LTTNG_UST_STREAM
|| lum
->cmd
== LTTNG_UST_CHANNEL
)
310 && lur
.ret_code
== LTTCOMM_OK
) {
311 /* we also need to send the file descriptors. */
312 ret
= lttcomm_send_fds_unix_sock(sock
,
316 perror("send shm_fd");
319 ret
= lttcomm_send_fds_unix_sock(sock
,
323 perror("send wait_fd");
333 void cleanup_sock_info(struct sock_info
*sock_info
)
337 if (sock_info
->socket
!= -1) {
338 ret
= close(sock_info
->socket
);
340 ERR("Error closing apps socket");
342 sock_info
->socket
= -1;
344 if (sock_info
->root_handle
!= -1) {
345 ret
= objd_unref(sock_info
->root_handle
);
347 ERR("Error unref root handle");
349 sock_info
->root_handle
= -1;
351 sock_info
->constructor_sem_posted
= 0;
352 if (sock_info
->wait_shm_mmap
) {
353 ret
= munmap(sock_info
->wait_shm_mmap
, sysconf(_SC_PAGE_SIZE
));
355 ERR("Error unmapping wait shm");
357 sock_info
->wait_shm_mmap
= NULL
;
362 * Using fork to set umask in the child process (not multi-thread safe).
363 * We deal with the shm_open vs ftruncate race (happening when the
364 * sessiond owns the shm and does not let everybody modify it, to ensure
365 * safety against shm_unlink) by simply letting the mmap fail and
366 * retrying after a few seconds.
367 * For global shm, everybody has rw access to it until the sessiond
371 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
373 int wait_shm_fd
, ret
;
377 * Try to open read-only.
379 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
380 if (wait_shm_fd
>= 0) {
382 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
384 * Real-only open did not work, and it's not because the
385 * entry was not present. It's a failure that prohibits
388 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
392 * If the open failed because the file did not exist, try
393 * creating it ourself.
400 * Parent: wait for child to return, in which case the
401 * shared memory map will have been created.
404 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
409 * Try to open read-only again after creation.
411 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
412 if (wait_shm_fd
< 0) {
414 * Real-only open did not work. It's a failure
415 * that prohibits using shm.
417 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
421 } else if (pid
== 0) {
425 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
426 if (sock_info
->global
)
427 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
429 * We're alone in a child process, so we can modify the
430 * process-wide umask.
434 * Try creating shm (or get rw access).
435 * We don't do an exclusive open, because we allow other
436 * processes to create+ftruncate it concurrently.
438 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
439 O_RDWR
| O_CREAT
, create_mode
);
440 if (wait_shm_fd
>= 0) {
441 ret
= ftruncate(wait_shm_fd
, mmap_size
);
449 * For local shm, we need to have rw access to accept
450 * opening it: this means the local sessiond will be
451 * able to wake us up. For global shm, we open it even
452 * if rw access is not granted, because the root.root
453 * sessiond will be able to override all rights and wake
456 if (!sock_info
->global
&& errno
!= EACCES
) {
457 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
461 * The shm exists, but we cannot open it RW. Report
469 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
473 * Ensure that our user is the owner of the shm file for
474 * local shm. If we do not own the file, it means our
475 * sessiond will not have access to wake us up (there is
476 * probably a rogue process trying to fake our
477 * sessiond). Fallback to polling method in this case.
479 ret
= fstat(wait_shm_fd
, &statbuf
);
484 if (statbuf
.st_uid
!= getuid())
490 ret
= close(wait_shm_fd
);
492 PERROR("Error closing fd");
498 char *get_map_shm(struct sock_info
*sock_info
)
500 size_t mmap_size
= sysconf(_SC_PAGE_SIZE
);
501 int wait_shm_fd
, ret
;
504 wait_shm_fd
= get_wait_shm(sock_info
, mmap_size
);
505 if (wait_shm_fd
< 0) {
508 wait_shm_mmap
= mmap(NULL
, mmap_size
, PROT_READ
,
509 MAP_SHARED
, wait_shm_fd
, 0);
510 /* close shm fd immediately after taking the mmap reference */
511 ret
= close(wait_shm_fd
);
513 PERROR("Error closing fd");
515 if (wait_shm_mmap
== MAP_FAILED
) {
516 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
519 return wait_shm_mmap
;
526 void wait_for_sessiond(struct sock_info
*sock_info
)
531 if (lttng_ust_comm_should_quit
) {
534 if (wait_poll_fallback
) {
537 if (!sock_info
->wait_shm_mmap
) {
538 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
539 if (!sock_info
->wait_shm_mmap
)
544 DBG("Waiting for %s apps sessiond", sock_info
->name
);
545 /* Wait for futex wakeup */
546 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
) == 0) {
547 ret
= futex_async((int32_t *) sock_info
->wait_shm_mmap
,
548 FUTEX_WAIT
, 0, NULL
, NULL
, 0);
550 if (errno
== EFAULT
) {
551 wait_poll_fallback
= 1;
553 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
554 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
555 "Please upgrade your kernel "
556 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
557 "mainline). LTTng-UST will use polling mode fallback.");
574 * This thread does not allocate any resource, except within
575 * handle_message, within mutex protection. This mutex protects against
577 * The other moment it allocates resources is at socket connexion, which
578 * is also protected by the mutex.
581 void *ust_listener_thread(void *arg
)
583 struct sock_info
*sock_info
= arg
;
584 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
586 /* Restart trying to connect to the session daemon */
588 if (prev_connect_failed
) {
589 /* Wait for sessiond availability with pipe */
590 wait_for_sessiond(sock_info
);
594 * Sleep for 5 seconds before retrying after a
595 * sequence of failure / wait / failure. This
596 * deals with a killed or broken session daemon.
601 prev_connect_failed
= 0;
605 if (lttng_ust_comm_should_quit
) {
610 if (sock_info
->socket
!= -1) {
611 ret
= close(sock_info
->socket
);
613 ERR("Error closing %s apps socket", sock_info
->name
);
615 sock_info
->socket
= -1;
619 ret
= lttcomm_connect_unix_sock(sock_info
->sock_path
);
621 ERR("Error connecting to %s apps socket", sock_info
->name
);
622 prev_connect_failed
= 1;
624 * If we cannot find the sessiond daemon, don't delay
625 * constructor execution.
627 ret
= handle_register_done(sock_info
);
633 sock_info
->socket
= sock
= ret
;
636 * Create only one root handle per listener thread for the whole
639 if (sock_info
->root_handle
== -1) {
640 ret
= lttng_abi_create_root_handle();
642 ERR("Error creating root handle");
646 sock_info
->root_handle
= ret
;
649 ret
= register_app_to_sessiond(sock
);
651 ERR("Error registering to %s apps socket", sock_info
->name
);
652 prev_connect_failed
= 1;
654 * If we cannot register to the sessiond daemon, don't
655 * delay constructor execution.
657 ret
= handle_register_done(sock_info
);
666 struct lttcomm_ust_msg lum
;
668 len
= lttcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
670 case 0: /* orderly shutdown */
671 DBG("%s ltt-sessiond has performed an orderly shutdown\n", sock_info
->name
);
674 DBG("message received\n");
675 ret
= handle_message(sock_info
, sock
, &lum
);
677 ERR("Error handling message for %s socket", sock_info
->name
);
681 if (errno
== ECONNRESET
) {
682 ERR("%s remote end closed connection\n", sock_info
->name
);
687 ERR("incorrect message size (%s socket): %zd\n", sock_info
->name
, len
);
693 goto restart
; /* try to reconnect */
699 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
702 int get_timeout(struct timespec
*constructor_timeout
)
704 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
708 str_delay
= getenv("UST_REGISTER_TIMEOUT");
710 constructor_delay_ms
= strtol(str_delay
, NULL
, 10);
713 switch (constructor_delay_ms
) {
714 case -1:/* fall-through */
716 return constructor_delay_ms
;
722 * If we are unable to find the current time, don't wait.
724 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
728 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
729 constructor_timeout
->tv_nsec
+=
730 (constructor_delay_ms
% 1000UL) * 1000000UL;
731 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
732 constructor_timeout
->tv_sec
++;
733 constructor_timeout
->tv_nsec
-= 1000000000UL;
739 * sessiond monitoring thread: monitor presence of global and per-user
740 * sessiond by polling the application common named pipe.
744 void __attribute__((constructor
)) lttng_ust_init(void)
746 struct timespec constructor_timeout
;
750 if (uatomic_xchg(&initialized
, 1) == 1)
754 * We want precise control over the order in which we construct
755 * our sub-libraries vs starting to receive commands from
756 * sessiond (otherwise leading to errors when trying to create
757 * sessiond before the init functions are completed).
761 ltt_ring_buffer_metadata_client_init();
762 ltt_ring_buffer_client_overwrite_init();
763 ltt_ring_buffer_client_discard_init();
765 timeout_mode
= get_timeout(&constructor_timeout
);
767 ret
= sem_init(&constructor_wait
, 0, 0);
770 ret
= setup_local_apps();
772 ERR("Error setting up to local apps");
774 ret
= pthread_create(&local_apps
.ust_listener
, NULL
,
775 ust_listener_thread
, &local_apps
);
777 if (local_apps
.allowed
) {
778 ret
= pthread_create(&global_apps
.ust_listener
, NULL
,
779 ust_listener_thread
, &global_apps
);
781 handle_register_done(&local_apps
);
784 switch (timeout_mode
) {
785 case 1: /* timeout wait */
787 ret
= sem_timedwait(&constructor_wait
,
788 &constructor_timeout
);
789 } while (ret
< 0 && errno
== EINTR
);
790 if (ret
< 0 && errno
== ETIMEDOUT
) {
791 ERR("Timed out waiting for ltt-sessiond");
796 case -1:/* wait forever */
798 ret
= sem_wait(&constructor_wait
);
799 } while (ret
< 0 && errno
== EINTR
);
802 case 0: /* no timeout */
808 void lttng_ust_cleanup(int exiting
)
810 cleanup_sock_info(&global_apps
);
811 if (local_apps
.allowed
) {
812 cleanup_sock_info(&local_apps
);
814 lttng_ust_abi_exit();
816 ltt_ring_buffer_client_discard_exit();
817 ltt_ring_buffer_client_overwrite_exit();
818 ltt_ring_buffer_metadata_client_exit();
821 /* Reinitialize values for fork */
823 lttng_ust_comm_should_quit
= 0;
828 void __attribute__((destructor
)) lttng_ust_exit(void)
833 * Using pthread_cancel here because:
834 * A) we don't want to hang application teardown.
835 * B) the thread is not allocating any resource.
839 * Require the communication thread to quit. Synchronize with
840 * mutexes to ensure it is not in a mutex critical section when
841 * pthread_cancel is later called.
844 lttng_ust_comm_should_quit
= 1;
847 ret
= pthread_cancel(global_apps
.ust_listener
);
849 ERR("Error cancelling global ust listener thread");
851 if (local_apps
.allowed
) {
852 ret
= pthread_cancel(local_apps
.ust_listener
);
854 ERR("Error cancelling local ust listener thread");
857 lttng_ust_cleanup(1);
861 * We exclude the worker threads across fork and clone (except
862 * CLONE_VM), because these system calls only keep the forking thread
863 * running in the child. Therefore, we don't want to call fork or clone
864 * in the middle of an tracepoint or ust tracing state modification.
865 * Holding this mutex protects these structures across fork and clone.
867 void ust_before_fork(ust_fork_info_t
*fork_info
)
870 * Disable signals. This is to avoid that the child intervenes
871 * before it is properly setup for tracing. It is safer to
872 * disable all signals, because then we know we are not breaking
873 * anything by restoring the original mask.
878 /* Disable signals */
879 sigfillset(&all_sigs
);
880 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, &fork_info
->orig_sigs
);
882 PERROR("sigprocmask");
885 rcu_bp_before_fork();
888 static void ust_after_fork_common(ust_fork_info_t
*fork_info
)
892 DBG("process %d", getpid());
894 /* Restore signals */
895 ret
= sigprocmask(SIG_SETMASK
, &fork_info
->orig_sigs
, NULL
);
897 PERROR("sigprocmask");
901 void ust_after_fork_parent(ust_fork_info_t
*fork_info
)
903 DBG("process %d", getpid());
904 rcu_bp_after_fork_parent();
905 /* Release mutexes and reenable signals */
906 ust_after_fork_common(fork_info
);
910 * After fork, in the child, we need to cleanup all the leftover state,
911 * except the worker thread which already magically disappeared thanks
912 * to the weird Linux fork semantics. After tyding up, we call
913 * lttng_ust_init() again to start over as a new PID.
915 * This is meant for forks() that have tracing in the child between the
916 * fork and following exec call (if there is any).
918 void ust_after_fork_child(ust_fork_info_t
*fork_info
)
920 DBG("process %d", getpid());
921 /* Release urcu mutexes */
922 rcu_bp_after_fork_child();
923 lttng_ust_cleanup(0);
924 /* Release mutexes and reenable signals */
925 ust_after_fork_common(fork_info
);