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
24 #include <sys/types.h>
25 #include <sys/socket.h>
28 #include <sys/types.h>
34 #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-statedump.h"
57 #include "../libringbuffer/getcpu.h"
61 * Has lttng ust comm constructor been called ?
63 static int initialized
;
66 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
67 * Held when handling a command, also held by fork() to deal with
68 * removal of threads, and by exit path.
70 * The UST lock is the centralized mutex across UST tracing control and
73 * ust_exit_mutex must never nest in ust_mutex.
75 * ust_fork_mutex must never nest in ust_mutex.
77 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
78 * counter lazy initialization called by events within the statedump,
79 * which traces while the ust_mutex is held.
81 * ust_lock nests within the dynamic loader lock (within glibc) because
82 * it is taken within the library constructor.
84 static pthread_mutex_t ust_mutex
= PTHREAD_MUTEX_INITIALIZER
;
86 /* Allow nesting the ust_mutex within the same thread. */
87 static DEFINE_URCU_TLS(int, ust_mutex_nest
);
90 * ust_exit_mutex protects thread_active variable wrt thread exit. It
91 * cannot be done by ust_mutex because pthread_cancel(), which takes an
92 * internal libc lock, cannot nest within ust_mutex.
94 * It never nests within a ust_mutex.
96 static pthread_mutex_t ust_exit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
99 * ust_fork_mutex protects base address statedump tracing against forks. It
100 * prevents the dynamic loader lock to be taken (by base address statedump
101 * tracing) while a fork is happening, thus preventing deadlock issues with
102 * the dynamic loader lock.
104 static pthread_mutex_t ust_fork_mutex
= PTHREAD_MUTEX_INITIALIZER
;
106 /* Should the ust comm thread quit ? */
107 static int lttng_ust_comm_should_quit
;
110 * This variable can be tested by applications to check whether
111 * lttng-ust is loaded. They simply have to define their own
112 * "lttng_ust_loaded" weak symbol, and test it. It is set to 1 by the
113 * library constructor.
115 int lttng_ust_loaded
__attribute__((weak
));
118 * Return 0 on success, -1 if should quit.
119 * The lock is taken in both cases.
124 sigset_t sig_all_blocked
, orig_mask
;
127 ret
= pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &oldstate
);
129 ERR("pthread_setcancelstate: %s", strerror(ret
));
131 if (oldstate
!= PTHREAD_CANCEL_ENABLE
) {
132 ERR("pthread_setcancelstate: unexpected oldstate");
134 sigfillset(&sig_all_blocked
);
135 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
137 ERR("pthread_sigmask: %s", strerror(ret
));
139 if (!URCU_TLS(ust_mutex_nest
)++)
140 pthread_mutex_lock(&ust_mutex
);
141 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
143 ERR("pthread_sigmask: %s", strerror(ret
));
145 if (lttng_ust_comm_should_quit
) {
153 * ust_lock_nocheck() can be used in constructors/destructors, because
154 * they are already nested within the dynamic loader lock, and therefore
155 * have exclusive access against execution of liblttng-ust destructor.
158 void ust_lock_nocheck(void)
160 sigset_t sig_all_blocked
, orig_mask
;
163 ret
= pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &oldstate
);
165 ERR("pthread_setcancelstate: %s", strerror(ret
));
167 if (oldstate
!= PTHREAD_CANCEL_ENABLE
) {
168 ERR("pthread_setcancelstate: unexpected oldstate");
170 sigfillset(&sig_all_blocked
);
171 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
173 ERR("pthread_sigmask: %s", strerror(ret
));
175 if (!URCU_TLS(ust_mutex_nest
)++)
176 pthread_mutex_lock(&ust_mutex
);
177 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
179 ERR("pthread_sigmask: %s", strerror(ret
));
186 void ust_unlock(void)
188 sigset_t sig_all_blocked
, orig_mask
;
191 sigfillset(&sig_all_blocked
);
192 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
194 ERR("pthread_sigmask: %s", strerror(ret
));
196 if (!--URCU_TLS(ust_mutex_nest
))
197 pthread_mutex_unlock(&ust_mutex
);
198 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
200 ERR("pthread_sigmask: %s", strerror(ret
));
202 ret
= pthread_setcancelstate(PTHREAD_CANCEL_ENABLE
, &oldstate
);
204 ERR("pthread_setcancelstate: %s", strerror(ret
));
206 if (oldstate
!= PTHREAD_CANCEL_DISABLE
) {
207 ERR("pthread_setcancelstate: unexpected oldstate");
212 * Wait for either of these before continuing to the main
214 * - the register_done message from sessiond daemon
215 * (will let the sessiond daemon enable sessions before main
217 * - sessiond daemon is not reachable.
218 * - timeout (ensuring applications are resilient to session
221 static sem_t constructor_wait
;
223 * Doing this for both the global and local sessiond.
225 static int sem_count
= { 2 };
228 * Counting nesting within lttng-ust. Used to ensure that calling fork()
229 * from liblttng-ust does not execute the pre/post fork handlers.
231 static DEFINE_URCU_TLS(int, lttng_ust_nest_count
);
234 * Info about socket and associated listener thread.
238 pthread_t ust_listener
; /* listener thread */
240 int constructor_sem_posted
;
245 char sock_path
[PATH_MAX
];
249 char wait_shm_path
[PATH_MAX
];
251 /* Keep track of lazy state dump not performed yet. */
252 int statedump_pending
;
255 /* Socket from app (connect) to session daemon (listen) for communication */
256 struct sock_info global_apps
= {
264 .sock_path
= LTTNG_DEFAULT_RUNDIR
"/" LTTNG_UST_SOCK_FILENAME
,
268 .wait_shm_path
= "/" LTTNG_UST_WAIT_FILENAME
,
270 .statedump_pending
= 0,
273 /* TODO: allow global_apps_sock_path override */
275 struct sock_info local_apps
= {
279 .allowed
= 0, /* Check setuid bit first */
285 .statedump_pending
= 0,
288 static int wait_poll_fallback
;
290 static const char *cmd_name_mapping
[] = {
291 [ LTTNG_UST_RELEASE
] = "Release",
292 [ LTTNG_UST_SESSION
] = "Create Session",
293 [ LTTNG_UST_TRACER_VERSION
] = "Get Tracer Version",
295 [ LTTNG_UST_TRACEPOINT_LIST
] = "Create Tracepoint List",
296 [ LTTNG_UST_WAIT_QUIESCENT
] = "Wait for Quiescent State",
297 [ LTTNG_UST_REGISTER_DONE
] = "Registration Done",
298 [ LTTNG_UST_TRACEPOINT_FIELD_LIST
] = "Create Tracepoint Field List",
300 /* Session FD commands */
301 [ LTTNG_UST_CHANNEL
] = "Create Channel",
302 [ LTTNG_UST_SESSION_START
] = "Start Session",
303 [ LTTNG_UST_SESSION_STOP
] = "Stop Session",
305 /* Channel FD commands */
306 [ LTTNG_UST_STREAM
] = "Create Stream",
307 [ LTTNG_UST_EVENT
] = "Create Event",
309 /* Event and Channel FD commands */
310 [ LTTNG_UST_CONTEXT
] = "Create Context",
311 [ LTTNG_UST_FLUSH_BUFFER
] = "Flush Buffer",
313 /* Event, Channel and Session commands */
314 [ LTTNG_UST_ENABLE
] = "Enable",
315 [ LTTNG_UST_DISABLE
] = "Disable",
317 /* Tracepoint list commands */
318 [ LTTNG_UST_TRACEPOINT_LIST_GET
] = "List Next Tracepoint",
319 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
] = "List Next Tracepoint Field",
321 /* Event FD commands */
322 [ LTTNG_UST_FILTER
] = "Create Filter",
323 [ LTTNG_UST_EXCLUSION
] = "Add exclusions to event",
326 static const char *str_timeout
;
327 static int got_timeout_env
;
329 extern void lttng_ring_buffer_client_overwrite_init(void);
330 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
331 extern void lttng_ring_buffer_client_discard_init(void);
332 extern void lttng_ring_buffer_client_discard_rt_init(void);
333 extern void lttng_ring_buffer_metadata_client_init(void);
334 extern void lttng_ring_buffer_client_overwrite_exit(void);
335 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
336 extern void lttng_ring_buffer_client_discard_exit(void);
337 extern void lttng_ring_buffer_client_discard_rt_exit(void);
338 extern void lttng_ring_buffer_metadata_client_exit(void);
340 ssize_t
lttng_ust_read(int fd
, void *buf
, size_t len
)
343 size_t copied
= 0, to_copy
= len
;
346 ret
= read(fd
, buf
+ copied
, to_copy
);
351 } while ((ret
> 0 && to_copy
> 0)
352 || (ret
< 0 && errno
== EINTR
));
359 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
363 const char *get_lttng_home_dir(void)
367 val
= (const char *) lttng_secure_getenv("LTTNG_HOME");
371 return (const char *) lttng_secure_getenv("HOME");
375 * Force a read (imply TLS fixup for dlopen) of TLS variables.
378 void lttng_fixup_nest_count_tls(void)
380 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count
)));
384 void lttng_fixup_ust_mutex_nest_tls(void)
386 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest
)));
393 void lttng_fixup_urcu_bp_tls(void)
399 void lttng_ust_fixup_tls(void)
401 lttng_fixup_urcu_bp_tls();
402 lttng_fixup_ringbuffer_tls();
403 lttng_fixup_vtid_tls();
404 lttng_fixup_nest_count_tls();
405 lttng_fixup_procname_tls();
406 lttng_fixup_ust_mutex_nest_tls();
409 int lttng_get_notify_socket(void *owner
)
411 struct sock_info
*info
= owner
;
413 return info
->notify_socket
;
417 void print_cmd(int cmd
, int handle
)
419 const char *cmd_name
= "Unknown";
421 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
422 && cmd_name_mapping
[cmd
]) {
423 cmd_name
= cmd_name_mapping
[cmd
];
425 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
427 lttng_ust_obj_get_name(handle
), handle
);
431 int setup_local_apps(void)
433 const char *home_dir
;
438 * Disallow per-user tracing for setuid binaries.
440 if (uid
!= geteuid()) {
441 assert(local_apps
.allowed
== 0);
444 home_dir
= get_lttng_home_dir();
446 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
447 assert(local_apps
.allowed
== 0);
450 local_apps
.allowed
= 1;
451 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
453 LTTNG_DEFAULT_HOME_RUNDIR
,
454 LTTNG_UST_SOCK_FILENAME
);
455 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
456 LTTNG_UST_WAIT_FILENAME
,
462 * Get socket timeout, in ms.
463 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
466 long get_timeout(void)
468 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
470 if (!got_timeout_env
) {
471 str_timeout
= getenv("LTTNG_UST_REGISTER_TIMEOUT");
475 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
476 /* All negative values are considered as "-1". */
477 if (constructor_delay_ms
< -1)
478 constructor_delay_ms
= -1;
479 return constructor_delay_ms
;
482 /* Timeout for notify socket send and recv. */
484 long get_notify_sock_timeout(void)
486 return get_timeout();
489 /* Timeout for connecting to cmd and notify sockets. */
491 long get_connect_sock_timeout(void)
493 return get_timeout();
497 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
500 int get_constructor_timeout(struct timespec
*constructor_timeout
)
502 long constructor_delay_ms
;
505 constructor_delay_ms
= get_timeout();
507 switch (constructor_delay_ms
) {
508 case -1:/* fall-through */
510 return constructor_delay_ms
;
516 * If we are unable to find the current time, don't wait.
518 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
523 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
524 constructor_timeout
->tv_nsec
+=
525 (constructor_delay_ms
% 1000UL) * 1000000UL;
526 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
527 constructor_timeout
->tv_sec
++;
528 constructor_timeout
->tv_nsec
-= 1000000000UL;
530 /* Timeout wait (constructor_delay_ms). */
535 int register_to_sessiond(int socket
, enum ustctl_socket_type type
)
537 return ustcomm_send_reg_msg(socket
,
540 lttng_alignof(uint8_t) * CHAR_BIT
,
541 lttng_alignof(uint16_t) * CHAR_BIT
,
542 lttng_alignof(uint32_t) * CHAR_BIT
,
543 lttng_alignof(uint64_t) * CHAR_BIT
,
544 lttng_alignof(unsigned long) * CHAR_BIT
);
548 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
552 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
555 DBG("message successfully sent");
558 if (len
== -ECONNRESET
) {
559 DBG("remote end closed connection");
564 DBG("incorrect message size: %zd", len
);
570 int handle_register_done(struct sock_info
*sock_info
)
574 if (sock_info
->constructor_sem_posted
)
576 sock_info
->constructor_sem_posted
= 1;
577 if (uatomic_read(&sem_count
) <= 0) {
580 ret
= uatomic_add_return(&sem_count
, -1);
582 ret
= sem_post(&constructor_wait
);
589 * Only execute pending statedump after the constructor semaphore has
590 * been posted by each listener thread. This means statedump will only
591 * be performed after the "registration done" command is received from
592 * each session daemon the application is connected to.
594 * This ensures we don't run into deadlock issues with the dynamic
595 * loader mutex, which is held while the constructor is called and
596 * waiting on the constructor semaphore. All operations requiring this
597 * dynamic loader lock need to be postponed using this mechanism.
600 void handle_pending_statedump(struct sock_info
*sock_info
)
602 int ctor_passed
= sock_info
->constructor_sem_posted
;
604 if (ctor_passed
&& sock_info
->statedump_pending
) {
605 sock_info
->statedump_pending
= 0;
606 pthread_mutex_lock(&ust_fork_mutex
);
607 lttng_handle_pending_statedump(sock_info
);
608 pthread_mutex_unlock(&ust_fork_mutex
);
613 int handle_message(struct sock_info
*sock_info
,
614 int sock
, struct ustcomm_ust_msg
*lum
)
617 const struct lttng_ust_objd_ops
*ops
;
618 struct ustcomm_ust_reply lur
;
620 char ctxstr
[LTTNG_UST_SYM_NAME_LEN
]; /* App context string. */
623 memset(&lur
, 0, sizeof(lur
));
626 ret
= -LTTNG_UST_ERR_EXITING
;
630 ops
= objd_ops(lum
->handle
);
637 case LTTNG_UST_REGISTER_DONE
:
638 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
639 ret
= handle_register_done(sock_info
);
643 case LTTNG_UST_RELEASE
:
644 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
647 ret
= lttng_ust_objd_unref(lum
->handle
, 1);
649 case LTTNG_UST_FILTER
:
651 /* Receive filter data */
652 struct lttng_ust_filter_bytecode_node
*bytecode
;
654 if (lum
->u
.filter
.data_size
> FILTER_BYTECODE_MAX_LEN
) {
655 ERR("Filter data size is too large: %u bytes",
656 lum
->u
.filter
.data_size
);
661 if (lum
->u
.filter
.reloc_offset
> lum
->u
.filter
.data_size
) {
662 ERR("Filter reloc offset %u is not within data",
663 lum
->u
.filter
.reloc_offset
);
668 bytecode
= zmalloc(sizeof(*bytecode
) + lum
->u
.filter
.data_size
);
673 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
,
674 lum
->u
.filter
.data_size
);
676 case 0: /* orderly shutdown */
681 if (len
== lum
->u
.filter
.data_size
) {
682 DBG("filter data received");
684 } else if (len
< 0) {
685 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
686 if (len
== -ECONNRESET
) {
687 ERR("%s remote end closed connection", sock_info
->name
);
696 DBG("incorrect filter data message size: %zd", len
);
702 bytecode
->bc
.len
= lum
->u
.filter
.data_size
;
703 bytecode
->bc
.reloc_offset
= lum
->u
.filter
.reloc_offset
;
704 bytecode
->bc
.seqnum
= lum
->u
.filter
.seqnum
;
706 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
707 (unsigned long) bytecode
,
712 /* don't free bytecode if everything went fine. */
719 case LTTNG_UST_EXCLUSION
:
721 /* Receive exclusion names */
722 struct lttng_ust_excluder_node
*node
;
725 count
= lum
->u
.exclusion
.count
;
727 /* There are no names to read */
731 node
= zmalloc(sizeof(*node
) +
732 count
* LTTNG_UST_SYM_NAME_LEN
);
737 node
->excluder
.count
= count
;
738 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
739 count
* LTTNG_UST_SYM_NAME_LEN
);
741 case 0: /* orderly shutdown */
746 if (len
== count
* LTTNG_UST_SYM_NAME_LEN
) {
747 DBG("Exclusion data received");
749 } else if (len
< 0) {
750 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
751 if (len
== -ECONNRESET
) {
752 ERR("%s remote end closed connection", sock_info
->name
);
761 DBG("Incorrect exclusion data message size: %zd", len
);
768 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
769 (unsigned long) node
,
774 /* Don't free exclusion data if everything went fine. */
781 case LTTNG_UST_CHANNEL
:
786 len
= ustcomm_recv_channel_from_sessiond(sock
,
787 &chan_data
, lum
->u
.channel
.len
,
790 case 0: /* orderly shutdown */
794 if (len
== lum
->u
.channel
.len
) {
795 DBG("channel data received");
797 } else if (len
< 0) {
798 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
799 if (len
== -ECONNRESET
) {
800 ERR("%s remote end closed connection", sock_info
->name
);
807 DBG("incorrect channel data message size: %zd", len
);
812 args
.channel
.chan_data
= chan_data
;
813 args
.channel
.wakeup_fd
= wakeup_fd
;
815 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
816 (unsigned long) &lum
->u
,
822 case LTTNG_UST_STREAM
:
824 /* Receive shm_fd, wakeup_fd */
825 ret
= ustcomm_recv_stream_from_sessiond(sock
,
828 &args
.stream
.wakeup_fd
);
833 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
834 (unsigned long) &lum
->u
,
840 case LTTNG_UST_CONTEXT
:
841 switch (lum
->u
.context
.ctx
) {
842 case LTTNG_UST_CONTEXT_APP_CONTEXT
:
845 size_t ctxlen
, recvlen
;
847 ctxlen
= strlen("$app.") + lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1
848 + strlen(":") + lum
->u
.context
.u
.app_ctx
.ctx_name_len
;
849 if (ctxlen
>= LTTNG_UST_SYM_NAME_LEN
) {
850 ERR("Application context string length size is too large: %zu bytes",
855 strcpy(ctxstr
, "$app.");
856 p
= &ctxstr
[strlen("$app.")];
857 recvlen
= ctxlen
- strlen("$app.");
858 len
= ustcomm_recv_unix_sock(sock
, p
, recvlen
);
860 case 0: /* orderly shutdown */
864 if (len
== recvlen
) {
865 DBG("app context data received");
867 } else if (len
< 0) {
868 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
869 if (len
== -ECONNRESET
) {
870 ERR("%s remote end closed connection", sock_info
->name
);
877 DBG("incorrect app context data message size: %zd", len
);
882 /* Put : between provider and ctxname. */
883 p
[lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1] = ':';
884 args
.app_context
.ctxname
= ctxstr
;
891 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
892 (unsigned long) &lum
->u
,
900 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
901 (unsigned long) &lum
->u
,
908 lur
.handle
= lum
->handle
;
912 lur
.ret_code
= LTTNG_UST_OK
;
915 * Use -LTTNG_UST_ERR as wildcard for UST internal
916 * error that are not caused by the transport, except if
917 * we already have a more precise error message to
920 if (ret
> -LTTNG_UST_ERR
) {
921 /* Translate code to UST error. */
924 lur
.ret_code
= -LTTNG_UST_ERR_EXIST
;
927 lur
.ret_code
= -LTTNG_UST_ERR_INVAL
;
930 lur
.ret_code
= -LTTNG_UST_ERR_NOENT
;
933 lur
.ret_code
= -LTTNG_UST_ERR_PERM
;
936 lur
.ret_code
= -LTTNG_UST_ERR_NOSYS
;
939 lur
.ret_code
= -LTTNG_UST_ERR
;
948 case LTTNG_UST_TRACER_VERSION
:
949 lur
.u
.version
= lum
->u
.version
;
951 case LTTNG_UST_TRACEPOINT_LIST_GET
:
952 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
956 DBG("Return value: %d", lur
.ret_val
);
957 ret
= send_reply(sock
, &lur
);
959 DBG("error sending reply");
964 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
967 if (lur
.ret_code
== LTTNG_UST_OK
) {
969 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
:
970 len
= ustcomm_send_unix_sock(sock
,
971 &args
.field_list
.entry
,
972 sizeof(args
.field_list
.entry
));
977 if (len
!= sizeof(args
.field_list
.entry
)) {
988 * Performed delayed statedump operations outside of the UST
989 * lock. We need to take the dynamic loader lock before we take
990 * the UST lock internally within handle_pending_statedump().
992 handle_pending_statedump(sock_info
);
998 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
1002 if (sock_info
->root_handle
!= -1) {
1003 ret
= lttng_ust_objd_unref(sock_info
->root_handle
, 1);
1005 ERR("Error unref root handle");
1007 sock_info
->root_handle
= -1;
1009 sock_info
->constructor_sem_posted
= 0;
1012 * wait_shm_mmap, socket and notify socket are used by listener
1013 * threads outside of the ust lock, so we cannot tear them down
1014 * ourselves, because we cannot join on these threads. Leave
1015 * responsibility of cleaning up these resources to the OS
1021 if (sock_info
->socket
!= -1) {
1022 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1024 ERR("Error closing ust cmd socket");
1026 sock_info
->socket
= -1;
1028 if (sock_info
->notify_socket
!= -1) {
1029 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1031 ERR("Error closing ust notify socket");
1033 sock_info
->notify_socket
= -1;
1035 if (sock_info
->wait_shm_mmap
) {
1038 page_size
= sysconf(_SC_PAGE_SIZE
);
1039 if (page_size
<= 0) {
1043 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1045 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
1047 ERR("Error unmapping wait shm");
1050 sock_info
->wait_shm_mmap
= NULL
;
1055 * Using fork to set umask in the child process (not multi-thread safe).
1056 * We deal with the shm_open vs ftruncate race (happening when the
1057 * sessiond owns the shm and does not let everybody modify it, to ensure
1058 * safety against shm_unlink) by simply letting the mmap fail and
1059 * retrying after a few seconds.
1060 * For global shm, everybody has rw access to it until the sessiond
1064 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
1066 int wait_shm_fd
, ret
;
1070 * Try to open read-only.
1072 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1073 if (wait_shm_fd
>= 0) {
1076 size_t bytes_read
= 0;
1079 * Try to read the fd. If unable to do so, try opening
1083 len
= read(wait_shm_fd
,
1084 &((char *) &tmp_read
)[bytes_read
],
1085 sizeof(tmp_read
) - bytes_read
);
1089 } while ((len
< 0 && errno
== EINTR
)
1090 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
1091 if (bytes_read
!= sizeof(tmp_read
)) {
1092 ret
= close(wait_shm_fd
);
1094 ERR("close wait_shm_fd");
1099 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
1101 * Real-only open did not work, and it's not because the
1102 * entry was not present. It's a failure that prohibits
1105 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1111 * If the open failed because the file did not exist, or because
1112 * the file was not truncated yet, try creating it ourself.
1114 URCU_TLS(lttng_ust_nest_count
)++;
1116 URCU_TLS(lttng_ust_nest_count
)--;
1121 * Parent: wait for child to return, in which case the
1122 * shared memory map will have been created.
1124 pid
= wait(&status
);
1125 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
1130 * Try to open read-only again after creation.
1132 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1133 if (wait_shm_fd
< 0) {
1135 * Real-only open did not work. It's a failure
1136 * that prohibits using shm.
1138 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1142 } else if (pid
== 0) {
1146 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
1147 if (sock_info
->global
)
1148 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
1150 * We're alone in a child process, so we can modify the
1151 * process-wide umask.
1153 umask(~create_mode
);
1155 * Try creating shm (or get rw access).
1156 * We don't do an exclusive open, because we allow other
1157 * processes to create+ftruncate it concurrently.
1159 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
1160 O_RDWR
| O_CREAT
, create_mode
);
1161 if (wait_shm_fd
>= 0) {
1162 ret
= ftruncate(wait_shm_fd
, mmap_size
);
1164 PERROR("ftruncate");
1165 _exit(EXIT_FAILURE
);
1167 _exit(EXIT_SUCCESS
);
1170 * For local shm, we need to have rw access to accept
1171 * opening it: this means the local sessiond will be
1172 * able to wake us up. For global shm, we open it even
1173 * if rw access is not granted, because the root.root
1174 * sessiond will be able to override all rights and wake
1177 if (!sock_info
->global
&& errno
!= EACCES
) {
1178 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1179 _exit(EXIT_FAILURE
);
1182 * The shm exists, but we cannot open it RW. Report
1185 _exit(EXIT_SUCCESS
);
1190 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
1191 struct stat statbuf
;
1194 * Ensure that our user is the owner of the shm file for
1195 * local shm. If we do not own the file, it means our
1196 * sessiond will not have access to wake us up (there is
1197 * probably a rogue process trying to fake our
1198 * sessiond). Fallback to polling method in this case.
1200 ret
= fstat(wait_shm_fd
, &statbuf
);
1205 if (statbuf
.st_uid
!= getuid())
1211 ret
= close(wait_shm_fd
);
1213 PERROR("Error closing fd");
1219 char *get_map_shm(struct sock_info
*sock_info
)
1222 int wait_shm_fd
, ret
;
1223 char *wait_shm_mmap
;
1225 page_size
= sysconf(_SC_PAGE_SIZE
);
1226 if (page_size
<= 0) {
1230 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1234 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1235 if (wait_shm_fd
< 0) {
1238 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1239 MAP_SHARED
, wait_shm_fd
, 0);
1240 /* close shm fd immediately after taking the mmap reference */
1241 ret
= close(wait_shm_fd
);
1243 PERROR("Error closing fd");
1245 if (wait_shm_mmap
== MAP_FAILED
) {
1246 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1249 return wait_shm_mmap
;
1256 void wait_for_sessiond(struct sock_info
*sock_info
)
1261 if (wait_poll_fallback
) {
1264 if (!sock_info
->wait_shm_mmap
) {
1265 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
1266 if (!sock_info
->wait_shm_mmap
)
1271 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1272 /* Wait for futex wakeup */
1273 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
))
1276 while (futex_async((int32_t *) sock_info
->wait_shm_mmap
,
1277 FUTEX_WAIT
, 0, NULL
, NULL
, 0)) {
1280 /* Value already changed. */
1283 /* Retry if interrupted by signal. */
1284 break; /* Get out of switch. */
1286 wait_poll_fallback
= 1;
1288 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1289 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1290 "Please upgrade your kernel "
1291 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1292 "mainline). LTTng-UST will use polling mode fallback.");
1311 * This thread does not allocate any resource, except within
1312 * handle_message, within mutex protection. This mutex protects against
1314 * The other moment it allocates resources is at socket connection, which
1315 * is also protected by the mutex.
1318 void *ust_listener_thread(void *arg
)
1320 struct sock_info
*sock_info
= arg
;
1321 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
1324 lttng_ust_fixup_tls();
1326 * If available, add '-ust' to the end of this thread's
1329 ret
= lttng_ust_setustprocname();
1331 ERR("Unable to set UST process name");
1334 /* Restart trying to connect to the session daemon */
1336 if (prev_connect_failed
) {
1337 /* Wait for sessiond availability with pipe */
1338 wait_for_sessiond(sock_info
);
1342 * Sleep for 5 seconds before retrying after a
1343 * sequence of failure / wait / failure. This
1344 * deals with a killed or broken session daemon.
1350 prev_connect_failed
= 0;
1353 if (sock_info
->socket
!= -1) {
1354 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1356 ERR("Error closing %s ust cmd socket",
1359 sock_info
->socket
= -1;
1361 if (sock_info
->notify_socket
!= -1) {
1362 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1364 ERR("Error closing %s ust notify socket",
1367 sock_info
->notify_socket
= -1;
1371 * Register. We need to perform both connect and sending
1372 * registration message before doing the next connect otherwise
1373 * we may reach unix socket connect queue max limits and block
1374 * on the 2nd connect while the session daemon is awaiting the
1375 * first connect registration message.
1377 /* Connect cmd socket */
1378 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
,
1379 get_connect_sock_timeout());
1381 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1382 prev_connect_failed
= 1;
1389 * If we cannot find the sessiond daemon, don't delay
1390 * constructor execution.
1392 ret
= handle_register_done(sock_info
);
1397 sock_info
->socket
= ret
;
1404 * Create only one root handle per listener thread for the whole
1405 * process lifetime, so we ensure we get ID which is statically
1406 * assigned to the root handle.
1408 if (sock_info
->root_handle
== -1) {
1409 ret
= lttng_abi_create_root_handle();
1411 ERR("Error creating root handle");
1414 sock_info
->root_handle
= ret
;
1417 ret
= register_to_sessiond(sock_info
->socket
, USTCTL_SOCKET_CMD
);
1419 ERR("Error registering to %s ust cmd socket",
1421 prev_connect_failed
= 1;
1423 * If we cannot register to the sessiond daemon, don't
1424 * delay constructor execution.
1426 ret
= handle_register_done(sock_info
);
1434 /* Connect notify socket */
1435 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
,
1436 get_connect_sock_timeout());
1438 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1439 prev_connect_failed
= 1;
1446 * If we cannot find the sessiond daemon, don't delay
1447 * constructor execution.
1449 ret
= handle_register_done(sock_info
);
1454 sock_info
->notify_socket
= ret
;
1456 timeout
= get_notify_sock_timeout();
1459 * Give at least 10ms to sessiond to reply to
1464 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
1467 WARN("Error setting socket receive timeout");
1469 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
1472 WARN("Error setting socket send timeout");
1474 } else if (timeout
< -1) {
1475 WARN("Unsupported timeout value %ld", timeout
);
1482 ret
= register_to_sessiond(sock_info
->notify_socket
,
1483 USTCTL_SOCKET_NOTIFY
);
1485 ERR("Error registering to %s ust notify socket",
1487 prev_connect_failed
= 1;
1489 * If we cannot register to the sessiond daemon, don't
1490 * delay constructor execution.
1492 ret
= handle_register_done(sock_info
);
1497 sock
= sock_info
->socket
;
1503 struct ustcomm_ust_msg lum
;
1505 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
1507 case 0: /* orderly shutdown */
1508 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
1513 * Either sessiond has shutdown or refused us by closing the socket.
1514 * In either case, we don't want to delay construction execution,
1515 * and we need to wait before retry.
1517 prev_connect_failed
= 1;
1519 * If we cannot register to the sessiond daemon, don't
1520 * delay constructor execution.
1522 ret
= handle_register_done(sock_info
);
1527 print_cmd(lum
.cmd
, lum
.handle
);
1528 ret
= handle_message(sock_info
, sock
, &lum
);
1530 ERR("Error handling message for %s socket",
1533 * Close socket if protocol error is
1541 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1543 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
1545 if (len
== -ECONNRESET
) {
1546 DBG("%s remote end closed connection", sock_info
->name
);
1557 /* Cleanup socket handles before trying to reconnect */
1558 lttng_ust_objd_table_owner_cleanup(sock_info
);
1560 goto restart
; /* try to reconnect */
1565 pthread_mutex_lock(&ust_exit_mutex
);
1566 sock_info
->thread_active
= 0;
1567 pthread_mutex_unlock(&ust_exit_mutex
);
1572 * Weak symbol to call when the ust malloc wrapper is not loaded.
1574 __attribute__((weak
))
1575 void lttng_ust_malloc_wrapper_init(void)
1580 * sessiond monitoring thread: monitor presence of global and per-user
1581 * sessiond by polling the application common named pipe.
1583 void __attribute__((constructor
)) lttng_ust_init(void)
1585 struct timespec constructor_timeout
;
1586 sigset_t sig_all_blocked
, orig_parent_mask
;
1587 pthread_attr_t thread_attr
;
1591 if (uatomic_xchg(&initialized
, 1) == 1)
1595 * Fixup interdependency between TLS fixup mutex (which happens
1596 * to be the dynamic linker mutex) and ust_lock, taken within
1599 lttng_ust_fixup_tls();
1601 lttng_ust_loaded
= 1;
1604 * We want precise control over the order in which we construct
1605 * our sub-libraries vs starting to receive commands from
1606 * sessiond (otherwise leading to errors when trying to create
1607 * sessiond before the init functions are completed).
1611 lttng_ust_clock_init();
1612 lttng_ust_getcpu_init();
1613 lttng_ust_statedump_init();
1614 lttng_ring_buffer_metadata_client_init();
1615 lttng_ring_buffer_client_overwrite_init();
1616 lttng_ring_buffer_client_overwrite_rt_init();
1617 lttng_ring_buffer_client_discard_init();
1618 lttng_ring_buffer_client_discard_rt_init();
1619 lttng_perf_counter_init();
1621 * Invoke ust malloc wrapper init before starting other threads.
1623 lttng_ust_malloc_wrapper_init();
1625 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
1627 ret
= sem_init(&constructor_wait
, 0, 0);
1632 ret
= setup_local_apps();
1634 DBG("local apps setup returned %d", ret
);
1637 /* A new thread created by pthread_create inherits the signal mask
1638 * from the parent. To avoid any signal being received by the
1639 * listener thread, we block all signals temporarily in the parent,
1640 * while we create the listener thread.
1642 sigfillset(&sig_all_blocked
);
1643 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
1645 ERR("pthread_sigmask: %s", strerror(ret
));
1648 ret
= pthread_attr_init(&thread_attr
);
1650 ERR("pthread_attr_init: %s", strerror(ret
));
1652 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
1654 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
1657 pthread_mutex_lock(&ust_exit_mutex
);
1658 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
1659 ust_listener_thread
, &global_apps
);
1661 ERR("pthread_create global: %s", strerror(ret
));
1663 global_apps
.thread_active
= 1;
1664 pthread_mutex_unlock(&ust_exit_mutex
);
1666 if (local_apps
.allowed
) {
1667 pthread_mutex_lock(&ust_exit_mutex
);
1668 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
1669 ust_listener_thread
, &local_apps
);
1671 ERR("pthread_create local: %s", strerror(ret
));
1673 local_apps
.thread_active
= 1;
1674 pthread_mutex_unlock(&ust_exit_mutex
);
1676 handle_register_done(&local_apps
);
1678 ret
= pthread_attr_destroy(&thread_attr
);
1680 ERR("pthread_attr_destroy: %s", strerror(ret
));
1683 /* Restore original signal mask in parent */
1684 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
1686 ERR("pthread_sigmask: %s", strerror(ret
));
1689 switch (timeout_mode
) {
1690 case 1: /* timeout wait */
1692 ret
= sem_timedwait(&constructor_wait
,
1693 &constructor_timeout
);
1694 } while (ret
< 0 && errno
== EINTR
);
1698 ERR("Timed out waiting for lttng-sessiond");
1701 PERROR("sem_timedwait");
1704 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1709 case -1:/* wait forever */
1711 ret
= sem_wait(&constructor_wait
);
1712 } while (ret
< 0 && errno
== EINTR
);
1719 ERR("Unexpected error \"%s\" returned by sem_wait",
1724 case 0: /* no timeout */
1730 void lttng_ust_cleanup(int exiting
)
1732 cleanup_sock_info(&global_apps
, exiting
);
1733 cleanup_sock_info(&local_apps
, exiting
);
1734 local_apps
.allowed
= 0;
1736 * The teardown in this function all affect data structures
1737 * accessed under the UST lock by the listener thread. This
1738 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1739 * that none of these threads are accessing this data at this
1742 lttng_ust_abi_exit();
1743 lttng_ust_events_exit();
1744 lttng_perf_counter_exit();
1745 lttng_ring_buffer_client_discard_rt_exit();
1746 lttng_ring_buffer_client_discard_exit();
1747 lttng_ring_buffer_client_overwrite_rt_exit();
1748 lttng_ring_buffer_client_overwrite_exit();
1749 lttng_ring_buffer_metadata_client_exit();
1750 lttng_ust_statedump_destroy();
1753 /* Reinitialize values for fork */
1755 lttng_ust_comm_should_quit
= 0;
1760 void __attribute__((destructor
)) lttng_ust_exit(void)
1765 * Using pthread_cancel here because:
1766 * A) we don't want to hang application teardown.
1767 * B) the thread is not allocating any resource.
1771 * Require the communication thread to quit. Synchronize with
1772 * mutexes to ensure it is not in a mutex critical section when
1773 * pthread_cancel is later called.
1776 lttng_ust_comm_should_quit
= 1;
1779 pthread_mutex_lock(&ust_exit_mutex
);
1780 /* cancel threads */
1781 if (global_apps
.thread_active
) {
1782 ret
= pthread_cancel(global_apps
.ust_listener
);
1784 ERR("Error cancelling global ust listener thread: %s",
1787 global_apps
.thread_active
= 0;
1790 if (local_apps
.thread_active
) {
1791 ret
= pthread_cancel(local_apps
.ust_listener
);
1793 ERR("Error cancelling local ust listener thread: %s",
1796 local_apps
.thread_active
= 0;
1799 pthread_mutex_unlock(&ust_exit_mutex
);
1802 * Do NOT join threads: use of sys_futex makes it impossible to
1803 * join the threads without using async-cancel, but async-cancel
1804 * is delivered by a signal, which could hit the target thread
1805 * anywhere in its code path, including while the ust_lock() is
1806 * held, causing a deadlock for the other thread. Let the OS
1807 * cleanup the threads if there are stalled in a syscall.
1809 lttng_ust_cleanup(1);
1813 * We exclude the worker threads across fork and clone (except
1814 * CLONE_VM), because these system calls only keep the forking thread
1815 * running in the child. Therefore, we don't want to call fork or clone
1816 * in the middle of an tracepoint or ust tracing state modification.
1817 * Holding this mutex protects these structures across fork and clone.
1819 void ust_before_fork(sigset_t
*save_sigset
)
1822 * Disable signals. This is to avoid that the child intervenes
1823 * before it is properly setup for tracing. It is safer to
1824 * disable all signals, because then we know we are not breaking
1825 * anything by restoring the original mask.
1830 /* Fixup lttng-ust TLS. */
1831 lttng_ust_fixup_tls();
1833 if (URCU_TLS(lttng_ust_nest_count
))
1835 /* Disable signals */
1836 sigfillset(&all_sigs
);
1837 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
1839 PERROR("sigprocmask");
1842 pthread_mutex_lock(&ust_fork_mutex
);
1845 rcu_bp_before_fork();
1848 static void ust_after_fork_common(sigset_t
*restore_sigset
)
1852 DBG("process %d", getpid());
1855 pthread_mutex_unlock(&ust_fork_mutex
);
1857 /* Restore signals */
1858 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
1860 PERROR("sigprocmask");
1864 void ust_after_fork_parent(sigset_t
*restore_sigset
)
1866 if (URCU_TLS(lttng_ust_nest_count
))
1868 DBG("process %d", getpid());
1869 rcu_bp_after_fork_parent();
1870 /* Release mutexes and reenable signals */
1871 ust_after_fork_common(restore_sigset
);
1875 * After fork, in the child, we need to cleanup all the leftover state,
1876 * except the worker thread which already magically disappeared thanks
1877 * to the weird Linux fork semantics. After tyding up, we call
1878 * lttng_ust_init() again to start over as a new PID.
1880 * This is meant for forks() that have tracing in the child between the
1881 * fork and following exec call (if there is any).
1883 void ust_after_fork_child(sigset_t
*restore_sigset
)
1885 if (URCU_TLS(lttng_ust_nest_count
))
1887 lttng_context_vtid_reset();
1888 DBG("process %d", getpid());
1889 /* Release urcu mutexes */
1890 rcu_bp_after_fork_child();
1891 lttng_ust_cleanup(0);
1892 /* Release mutexes and reenable signals */
1893 ust_after_fork_common(restore_sigset
);
1897 void lttng_ust_sockinfo_session_enabled(void *owner
)
1899 struct sock_info
*sock_info
= owner
;
1900 sock_info
->statedump_pending
= 1;