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 int lttng_get_notify_socket(void *owner
)
401 struct sock_info
*info
= owner
;
403 return info
->notify_socket
;
407 void print_cmd(int cmd
, int handle
)
409 const char *cmd_name
= "Unknown";
411 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
412 && cmd_name_mapping
[cmd
]) {
413 cmd_name
= cmd_name_mapping
[cmd
];
415 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
417 lttng_ust_obj_get_name(handle
), handle
);
421 int setup_local_apps(void)
423 const char *home_dir
;
428 * Disallow per-user tracing for setuid binaries.
430 if (uid
!= geteuid()) {
431 assert(local_apps
.allowed
== 0);
434 home_dir
= get_lttng_home_dir();
436 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
437 assert(local_apps
.allowed
== 0);
440 local_apps
.allowed
= 1;
441 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
443 LTTNG_DEFAULT_HOME_RUNDIR
,
444 LTTNG_UST_SOCK_FILENAME
);
445 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
446 LTTNG_UST_WAIT_FILENAME
,
452 * Get notify_sock timeout, in ms.
453 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
456 long get_timeout(void)
458 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
460 if (!got_timeout_env
) {
461 str_timeout
= getenv("LTTNG_UST_REGISTER_TIMEOUT");
465 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
466 /* All negative values are considered as "-1". */
467 if (constructor_delay_ms
< -1)
468 constructor_delay_ms
= -1;
469 return constructor_delay_ms
;
473 long get_notify_sock_timeout(void)
475 return get_timeout();
479 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
482 int get_constructor_timeout(struct timespec
*constructor_timeout
)
484 long constructor_delay_ms
;
487 constructor_delay_ms
= get_timeout();
489 switch (constructor_delay_ms
) {
490 case -1:/* fall-through */
492 return constructor_delay_ms
;
498 * If we are unable to find the current time, don't wait.
500 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
505 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
506 constructor_timeout
->tv_nsec
+=
507 (constructor_delay_ms
% 1000UL) * 1000000UL;
508 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
509 constructor_timeout
->tv_sec
++;
510 constructor_timeout
->tv_nsec
-= 1000000000UL;
512 /* Timeout wait (constructor_delay_ms). */
517 int register_to_sessiond(int socket
, enum ustctl_socket_type type
)
519 return ustcomm_send_reg_msg(socket
,
522 lttng_alignof(uint8_t) * CHAR_BIT
,
523 lttng_alignof(uint16_t) * CHAR_BIT
,
524 lttng_alignof(uint32_t) * CHAR_BIT
,
525 lttng_alignof(uint64_t) * CHAR_BIT
,
526 lttng_alignof(unsigned long) * CHAR_BIT
);
530 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
534 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
537 DBG("message successfully sent");
540 if (len
== -ECONNRESET
) {
541 DBG("remote end closed connection");
546 DBG("incorrect message size: %zd", len
);
552 int handle_register_done(struct sock_info
*sock_info
)
556 if (sock_info
->constructor_sem_posted
)
558 sock_info
->constructor_sem_posted
= 1;
559 if (uatomic_read(&sem_count
) <= 0) {
562 ret
= uatomic_add_return(&sem_count
, -1);
564 ret
= sem_post(&constructor_wait
);
571 * Only execute pending statedump after the constructor semaphore has
572 * been posted by each listener thread. This means statedump will only
573 * be performed after the "registration done" command is received from
574 * each session daemon the application is connected to.
576 * This ensures we don't run into deadlock issues with the dynamic
577 * loader mutex, which is held while the constructor is called and
578 * waiting on the constructor semaphore. All operations requiring this
579 * dynamic loader lock need to be postponed using this mechanism.
582 void handle_pending_statedump(struct sock_info
*sock_info
)
584 int ctor_passed
= sock_info
->constructor_sem_posted
;
586 if (ctor_passed
&& sock_info
->statedump_pending
) {
587 sock_info
->statedump_pending
= 0;
588 pthread_mutex_lock(&ust_fork_mutex
);
589 lttng_handle_pending_statedump(sock_info
);
590 pthread_mutex_unlock(&ust_fork_mutex
);
595 int handle_message(struct sock_info
*sock_info
,
596 int sock
, struct ustcomm_ust_msg
*lum
)
599 const struct lttng_ust_objd_ops
*ops
;
600 struct ustcomm_ust_reply lur
;
602 char ctxstr
[LTTNG_UST_SYM_NAME_LEN
]; /* App context string. */
605 memset(&lur
, 0, sizeof(lur
));
608 ret
= -LTTNG_UST_ERR_EXITING
;
612 ops
= objd_ops(lum
->handle
);
619 case LTTNG_UST_REGISTER_DONE
:
620 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
621 ret
= handle_register_done(sock_info
);
625 case LTTNG_UST_RELEASE
:
626 if (lum
->handle
== LTTNG_UST_ROOT_HANDLE
)
629 ret
= lttng_ust_objd_unref(lum
->handle
, 1);
631 case LTTNG_UST_FILTER
:
633 /* Receive filter data */
634 struct lttng_ust_filter_bytecode_node
*bytecode
;
636 if (lum
->u
.filter
.data_size
> FILTER_BYTECODE_MAX_LEN
) {
637 ERR("Filter data size is too large: %u bytes",
638 lum
->u
.filter
.data_size
);
643 if (lum
->u
.filter
.reloc_offset
> lum
->u
.filter
.data_size
) {
644 ERR("Filter reloc offset %u is not within data",
645 lum
->u
.filter
.reloc_offset
);
650 bytecode
= zmalloc(sizeof(*bytecode
) + lum
->u
.filter
.data_size
);
655 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
,
656 lum
->u
.filter
.data_size
);
658 case 0: /* orderly shutdown */
663 if (len
== lum
->u
.filter
.data_size
) {
664 DBG("filter data received");
666 } else if (len
< 0) {
667 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
668 if (len
== -ECONNRESET
) {
669 ERR("%s remote end closed connection", sock_info
->name
);
678 DBG("incorrect filter data message size: %zd", len
);
684 bytecode
->bc
.len
= lum
->u
.filter
.data_size
;
685 bytecode
->bc
.reloc_offset
= lum
->u
.filter
.reloc_offset
;
686 bytecode
->bc
.seqnum
= lum
->u
.filter
.seqnum
;
688 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
689 (unsigned long) bytecode
,
694 /* don't free bytecode if everything went fine. */
701 case LTTNG_UST_EXCLUSION
:
703 /* Receive exclusion names */
704 struct lttng_ust_excluder_node
*node
;
707 count
= lum
->u
.exclusion
.count
;
709 /* There are no names to read */
713 node
= zmalloc(sizeof(*node
) +
714 count
* LTTNG_UST_SYM_NAME_LEN
);
719 node
->excluder
.count
= count
;
720 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
721 count
* LTTNG_UST_SYM_NAME_LEN
);
723 case 0: /* orderly shutdown */
728 if (len
== count
* LTTNG_UST_SYM_NAME_LEN
) {
729 DBG("Exclusion data received");
731 } else if (len
< 0) {
732 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
733 if (len
== -ECONNRESET
) {
734 ERR("%s remote end closed connection", sock_info
->name
);
743 DBG("Incorrect exclusion data message size: %zd", len
);
750 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
751 (unsigned long) node
,
756 /* Don't free exclusion data if everything went fine. */
763 case LTTNG_UST_CHANNEL
:
768 len
= ustcomm_recv_channel_from_sessiond(sock
,
769 &chan_data
, lum
->u
.channel
.len
,
772 case 0: /* orderly shutdown */
776 if (len
== lum
->u
.channel
.len
) {
777 DBG("channel data received");
779 } else if (len
< 0) {
780 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
781 if (len
== -ECONNRESET
) {
782 ERR("%s remote end closed connection", sock_info
->name
);
789 DBG("incorrect channel data message size: %zd", len
);
794 args
.channel
.chan_data
= chan_data
;
795 args
.channel
.wakeup_fd
= wakeup_fd
;
797 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
798 (unsigned long) &lum
->u
,
804 case LTTNG_UST_STREAM
:
806 /* Receive shm_fd, wakeup_fd */
807 ret
= ustcomm_recv_stream_from_sessiond(sock
,
810 &args
.stream
.wakeup_fd
);
815 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
816 (unsigned long) &lum
->u
,
822 case LTTNG_UST_CONTEXT
:
823 switch (lum
->u
.context
.ctx
) {
824 case LTTNG_UST_CONTEXT_APP_CONTEXT
:
827 size_t ctxlen
, recvlen
;
829 ctxlen
= strlen("$app.") + lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1
830 + strlen(":") + lum
->u
.context
.u
.app_ctx
.ctx_name_len
;
831 if (ctxlen
>= LTTNG_UST_SYM_NAME_LEN
) {
832 ERR("Application context string length size is too large: %zu bytes",
837 strcpy(ctxstr
, "$app.");
838 p
= &ctxstr
[strlen("$app.")];
839 recvlen
= ctxlen
- strlen("$app.");
840 len
= ustcomm_recv_unix_sock(sock
, p
, recvlen
);
842 case 0: /* orderly shutdown */
846 if (len
== recvlen
) {
847 DBG("app context data received");
849 } else if (len
< 0) {
850 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
851 if (len
== -ECONNRESET
) {
852 ERR("%s remote end closed connection", sock_info
->name
);
859 DBG("incorrect app context data message size: %zd", len
);
864 /* Put : between provider and ctxname. */
865 p
[lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1] = ':';
866 args
.app_context
.ctxname
= ctxstr
;
873 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
874 (unsigned long) &lum
->u
,
882 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
883 (unsigned long) &lum
->u
,
890 lur
.handle
= lum
->handle
;
894 lur
.ret_code
= LTTNG_UST_OK
;
897 * Use -LTTNG_UST_ERR as wildcard for UST internal
898 * error that are not caused by the transport, except if
899 * we already have a more precise error message to
902 if (ret
> -LTTNG_UST_ERR
) {
903 /* Translate code to UST error. */
906 lur
.ret_code
= -LTTNG_UST_ERR_EXIST
;
909 lur
.ret_code
= -LTTNG_UST_ERR_INVAL
;
912 lur
.ret_code
= -LTTNG_UST_ERR_NOENT
;
915 lur
.ret_code
= -LTTNG_UST_ERR_PERM
;
918 lur
.ret_code
= -LTTNG_UST_ERR_NOSYS
;
921 lur
.ret_code
= -LTTNG_UST_ERR
;
930 case LTTNG_UST_TRACER_VERSION
:
931 lur
.u
.version
= lum
->u
.version
;
933 case LTTNG_UST_TRACEPOINT_LIST_GET
:
934 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
938 DBG("Return value: %d", lur
.ret_val
);
939 ret
= send_reply(sock
, &lur
);
941 DBG("error sending reply");
946 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
949 if (lur
.ret_code
== LTTNG_UST_OK
) {
951 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET
:
952 len
= ustcomm_send_unix_sock(sock
,
953 &args
.field_list
.entry
,
954 sizeof(args
.field_list
.entry
));
959 if (len
!= sizeof(args
.field_list
.entry
)) {
970 * Performed delayed statedump operations outside of the UST
971 * lock. We need to take the dynamic loader lock before we take
972 * the UST lock internally within handle_pending_statedump().
974 handle_pending_statedump(sock_info
);
980 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
984 if (sock_info
->root_handle
!= -1) {
985 ret
= lttng_ust_objd_unref(sock_info
->root_handle
, 1);
987 ERR("Error unref root handle");
989 sock_info
->root_handle
= -1;
991 sock_info
->constructor_sem_posted
= 0;
994 * wait_shm_mmap, socket and notify socket are used by listener
995 * threads outside of the ust lock, so we cannot tear them down
996 * ourselves, because we cannot join on these threads. Leave
997 * responsibility of cleaning up these resources to the OS
1003 if (sock_info
->socket
!= -1) {
1004 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1006 ERR("Error closing ust cmd socket");
1008 sock_info
->socket
= -1;
1010 if (sock_info
->notify_socket
!= -1) {
1011 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1013 ERR("Error closing ust notify socket");
1015 sock_info
->notify_socket
= -1;
1017 if (sock_info
->wait_shm_mmap
) {
1020 page_size
= sysconf(_SC_PAGE_SIZE
);
1021 if (page_size
<= 0) {
1025 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1027 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
1029 ERR("Error unmapping wait shm");
1032 sock_info
->wait_shm_mmap
= NULL
;
1037 * Using fork to set umask in the child process (not multi-thread safe).
1038 * We deal with the shm_open vs ftruncate race (happening when the
1039 * sessiond owns the shm and does not let everybody modify it, to ensure
1040 * safety against shm_unlink) by simply letting the mmap fail and
1041 * retrying after a few seconds.
1042 * For global shm, everybody has rw access to it until the sessiond
1046 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
1048 int wait_shm_fd
, ret
;
1052 * Try to open read-only.
1054 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1055 if (wait_shm_fd
>= 0) {
1058 size_t bytes_read
= 0;
1061 * Try to read the fd. If unable to do so, try opening
1065 len
= read(wait_shm_fd
,
1066 &((char *) &tmp_read
)[bytes_read
],
1067 sizeof(tmp_read
) - bytes_read
);
1071 } while ((len
< 0 && errno
== EINTR
)
1072 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
1073 if (bytes_read
!= sizeof(tmp_read
)) {
1074 ret
= close(wait_shm_fd
);
1076 ERR("close wait_shm_fd");
1081 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
1083 * Real-only open did not work, and it's not because the
1084 * entry was not present. It's a failure that prohibits
1087 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1093 * If the open failed because the file did not exist, or because
1094 * the file was not truncated yet, try creating it ourself.
1096 URCU_TLS(lttng_ust_nest_count
)++;
1098 URCU_TLS(lttng_ust_nest_count
)--;
1103 * Parent: wait for child to return, in which case the
1104 * shared memory map will have been created.
1106 pid
= wait(&status
);
1107 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
1112 * Try to open read-only again after creation.
1114 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1115 if (wait_shm_fd
< 0) {
1117 * Real-only open did not work. It's a failure
1118 * that prohibits using shm.
1120 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1124 } else if (pid
== 0) {
1128 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
1129 if (sock_info
->global
)
1130 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
1132 * We're alone in a child process, so we can modify the
1133 * process-wide umask.
1135 umask(~create_mode
);
1137 * Try creating shm (or get rw access).
1138 * We don't do an exclusive open, because we allow other
1139 * processes to create+ftruncate it concurrently.
1141 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
1142 O_RDWR
| O_CREAT
, create_mode
);
1143 if (wait_shm_fd
>= 0) {
1144 ret
= ftruncate(wait_shm_fd
, mmap_size
);
1146 PERROR("ftruncate");
1147 _exit(EXIT_FAILURE
);
1149 _exit(EXIT_SUCCESS
);
1152 * For local shm, we need to have rw access to accept
1153 * opening it: this means the local sessiond will be
1154 * able to wake us up. For global shm, we open it even
1155 * if rw access is not granted, because the root.root
1156 * sessiond will be able to override all rights and wake
1159 if (!sock_info
->global
&& errno
!= EACCES
) {
1160 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1161 _exit(EXIT_FAILURE
);
1164 * The shm exists, but we cannot open it RW. Report
1167 _exit(EXIT_SUCCESS
);
1172 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
1173 struct stat statbuf
;
1176 * Ensure that our user is the owner of the shm file for
1177 * local shm. If we do not own the file, it means our
1178 * sessiond will not have access to wake us up (there is
1179 * probably a rogue process trying to fake our
1180 * sessiond). Fallback to polling method in this case.
1182 ret
= fstat(wait_shm_fd
, &statbuf
);
1187 if (statbuf
.st_uid
!= getuid())
1193 ret
= close(wait_shm_fd
);
1195 PERROR("Error closing fd");
1201 char *get_map_shm(struct sock_info
*sock_info
)
1204 int wait_shm_fd
, ret
;
1205 char *wait_shm_mmap
;
1207 page_size
= sysconf(_SC_PAGE_SIZE
);
1208 if (page_size
<= 0) {
1212 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1216 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1217 if (wait_shm_fd
< 0) {
1220 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1221 MAP_SHARED
, wait_shm_fd
, 0);
1222 /* close shm fd immediately after taking the mmap reference */
1223 ret
= close(wait_shm_fd
);
1225 PERROR("Error closing fd");
1227 if (wait_shm_mmap
== MAP_FAILED
) {
1228 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1231 return wait_shm_mmap
;
1238 void wait_for_sessiond(struct sock_info
*sock_info
)
1243 if (wait_poll_fallback
) {
1246 if (!sock_info
->wait_shm_mmap
) {
1247 sock_info
->wait_shm_mmap
= get_map_shm(sock_info
);
1248 if (!sock_info
->wait_shm_mmap
)
1253 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1254 /* Wait for futex wakeup */
1255 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
))
1258 while (futex_async((int32_t *) sock_info
->wait_shm_mmap
,
1259 FUTEX_WAIT
, 0, NULL
, NULL
, 0)) {
1262 /* Value already changed. */
1265 /* Retry if interrupted by signal. */
1266 break; /* Get out of switch. */
1268 wait_poll_fallback
= 1;
1270 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1271 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1272 "Please upgrade your kernel "
1273 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1274 "mainline). LTTng-UST will use polling mode fallback.");
1293 * This thread does not allocate any resource, except within
1294 * handle_message, within mutex protection. This mutex protects against
1296 * The other moment it allocates resources is at socket connection, which
1297 * is also protected by the mutex.
1300 void *ust_listener_thread(void *arg
)
1302 struct sock_info
*sock_info
= arg
;
1303 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0;
1307 * If available, add '-ust' to the end of this thread's
1310 ret
= lttng_ust_setustprocname();
1312 ERR("Unable to set UST process name");
1315 /* Restart trying to connect to the session daemon */
1317 if (prev_connect_failed
) {
1318 /* Wait for sessiond availability with pipe */
1319 wait_for_sessiond(sock_info
);
1323 * Sleep for 5 seconds before retrying after a
1324 * sequence of failure / wait / failure. This
1325 * deals with a killed or broken session daemon.
1331 prev_connect_failed
= 0;
1334 if (sock_info
->socket
!= -1) {
1335 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1337 ERR("Error closing %s ust cmd socket",
1340 sock_info
->socket
= -1;
1342 if (sock_info
->notify_socket
!= -1) {
1343 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1345 ERR("Error closing %s ust notify socket",
1348 sock_info
->notify_socket
= -1;
1352 * Register. We need to perform both connect and sending
1353 * registration message before doing the next connect otherwise
1354 * we may reach unix socket connect queue max limits and block
1355 * on the 2nd connect while the session daemon is awaiting the
1356 * first connect registration message.
1358 /* Connect cmd socket */
1359 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1361 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1362 prev_connect_failed
= 1;
1369 * If we cannot find the sessiond daemon, don't delay
1370 * constructor execution.
1372 ret
= handle_register_done(sock_info
);
1377 sock_info
->socket
= ret
;
1384 * Create only one root handle per listener thread for the whole
1385 * process lifetime, so we ensure we get ID which is statically
1386 * assigned to the root handle.
1388 if (sock_info
->root_handle
== -1) {
1389 ret
= lttng_abi_create_root_handle();
1391 ERR("Error creating root handle");
1394 sock_info
->root_handle
= ret
;
1397 ret
= register_to_sessiond(sock_info
->socket
, USTCTL_SOCKET_CMD
);
1399 ERR("Error registering to %s ust cmd socket",
1401 prev_connect_failed
= 1;
1403 * If we cannot register to the sessiond daemon, don't
1404 * delay constructor execution.
1406 ret
= handle_register_done(sock_info
);
1414 /* Connect notify socket */
1415 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
);
1417 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1418 prev_connect_failed
= 1;
1425 * If we cannot find the sessiond daemon, don't delay
1426 * constructor execution.
1428 ret
= handle_register_done(sock_info
);
1433 sock_info
->notify_socket
= ret
;
1435 timeout
= get_notify_sock_timeout();
1438 * Give at least 10ms to sessiond to reply to
1443 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
1446 WARN("Error setting socket receive timeout");
1448 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
1451 WARN("Error setting socket send timeout");
1453 } else if (timeout
< -1) {
1454 WARN("Unsupported timeout value %ld", timeout
);
1461 ret
= register_to_sessiond(sock_info
->notify_socket
,
1462 USTCTL_SOCKET_NOTIFY
);
1464 ERR("Error registering to %s ust notify socket",
1466 prev_connect_failed
= 1;
1468 * If we cannot register to the sessiond daemon, don't
1469 * delay constructor execution.
1471 ret
= handle_register_done(sock_info
);
1476 sock
= sock_info
->socket
;
1482 struct ustcomm_ust_msg lum
;
1484 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
1486 case 0: /* orderly shutdown */
1487 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
1492 * Either sessiond has shutdown or refused us by closing the socket.
1493 * In either case, we don't want to delay construction execution,
1494 * and we need to wait before retry.
1496 prev_connect_failed
= 1;
1498 * If we cannot register to the sessiond daemon, don't
1499 * delay constructor execution.
1501 ret
= handle_register_done(sock_info
);
1506 print_cmd(lum
.cmd
, lum
.handle
);
1507 ret
= handle_message(sock_info
, sock
, &lum
);
1509 ERR("Error handling message for %s socket",
1512 * Close socket if protocol error is
1520 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1522 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
1524 if (len
== -ECONNRESET
) {
1525 DBG("%s remote end closed connection", sock_info
->name
);
1536 /* Cleanup socket handles before trying to reconnect */
1537 lttng_ust_objd_table_owner_cleanup(sock_info
);
1539 goto restart
; /* try to reconnect */
1544 pthread_mutex_lock(&ust_exit_mutex
);
1545 sock_info
->thread_active
= 0;
1546 pthread_mutex_unlock(&ust_exit_mutex
);
1551 * Weak symbol to call when the ust malloc wrapper is not loaded.
1553 __attribute__((weak
))
1554 void lttng_ust_malloc_wrapper_init(void)
1559 * sessiond monitoring thread: monitor presence of global and per-user
1560 * sessiond by polling the application common named pipe.
1562 void __attribute__((constructor
)) lttng_ust_init(void)
1564 struct timespec constructor_timeout
;
1565 sigset_t sig_all_blocked
, orig_parent_mask
;
1566 pthread_attr_t thread_attr
;
1570 if (uatomic_xchg(&initialized
, 1) == 1)
1574 * Fixup interdependency between TLS fixup mutex (which happens
1575 * to be the dynamic linker mutex) and ust_lock, taken within
1578 lttng_fixup_urcu_bp_tls();
1579 lttng_fixup_ringbuffer_tls();
1580 lttng_fixup_vtid_tls();
1581 lttng_fixup_nest_count_tls();
1582 lttng_fixup_procname_tls();
1583 lttng_fixup_ust_mutex_nest_tls();
1585 lttng_ust_loaded
= 1;
1588 * We want precise control over the order in which we construct
1589 * our sub-libraries vs starting to receive commands from
1590 * sessiond (otherwise leading to errors when trying to create
1591 * sessiond before the init functions are completed).
1595 lttng_ust_clock_init();
1596 lttng_ust_getcpu_init();
1597 lttng_ust_statedump_init();
1598 lttng_ring_buffer_metadata_client_init();
1599 lttng_ring_buffer_client_overwrite_init();
1600 lttng_ring_buffer_client_overwrite_rt_init();
1601 lttng_ring_buffer_client_discard_init();
1602 lttng_ring_buffer_client_discard_rt_init();
1603 lttng_perf_counter_init();
1605 * Invoke ust malloc wrapper init before starting other threads.
1607 lttng_ust_malloc_wrapper_init();
1609 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
1611 ret
= sem_init(&constructor_wait
, 0, 0);
1616 ret
= setup_local_apps();
1618 DBG("local apps setup returned %d", ret
);
1621 /* A new thread created by pthread_create inherits the signal mask
1622 * from the parent. To avoid any signal being received by the
1623 * listener thread, we block all signals temporarily in the parent,
1624 * while we create the listener thread.
1626 sigfillset(&sig_all_blocked
);
1627 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
1629 ERR("pthread_sigmask: %s", strerror(ret
));
1632 ret
= pthread_attr_init(&thread_attr
);
1634 ERR("pthread_attr_init: %s", strerror(ret
));
1636 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
1638 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
1641 pthread_mutex_lock(&ust_exit_mutex
);
1642 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
1643 ust_listener_thread
, &global_apps
);
1645 ERR("pthread_create global: %s", strerror(ret
));
1647 global_apps
.thread_active
= 1;
1648 pthread_mutex_unlock(&ust_exit_mutex
);
1650 if (local_apps
.allowed
) {
1651 pthread_mutex_lock(&ust_exit_mutex
);
1652 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
1653 ust_listener_thread
, &local_apps
);
1655 ERR("pthread_create local: %s", strerror(ret
));
1657 local_apps
.thread_active
= 1;
1658 pthread_mutex_unlock(&ust_exit_mutex
);
1660 handle_register_done(&local_apps
);
1662 ret
= pthread_attr_destroy(&thread_attr
);
1664 ERR("pthread_attr_destroy: %s", strerror(ret
));
1667 /* Restore original signal mask in parent */
1668 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
1670 ERR("pthread_sigmask: %s", strerror(ret
));
1673 switch (timeout_mode
) {
1674 case 1: /* timeout wait */
1676 ret
= sem_timedwait(&constructor_wait
,
1677 &constructor_timeout
);
1678 } while (ret
< 0 && errno
== EINTR
);
1682 ERR("Timed out waiting for lttng-sessiond");
1685 PERROR("sem_timedwait");
1688 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1693 case -1:/* wait forever */
1695 ret
= sem_wait(&constructor_wait
);
1696 } while (ret
< 0 && errno
== EINTR
);
1703 ERR("Unexpected error \"%s\" returned by sem_wait",
1708 case 0: /* no timeout */
1714 void lttng_ust_cleanup(int exiting
)
1716 cleanup_sock_info(&global_apps
, exiting
);
1717 cleanup_sock_info(&local_apps
, exiting
);
1718 local_apps
.allowed
= 0;
1720 * The teardown in this function all affect data structures
1721 * accessed under the UST lock by the listener thread. This
1722 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1723 * that none of these threads are accessing this data at this
1726 lttng_ust_abi_exit();
1727 lttng_ust_events_exit();
1728 lttng_perf_counter_exit();
1729 lttng_ring_buffer_client_discard_rt_exit();
1730 lttng_ring_buffer_client_discard_exit();
1731 lttng_ring_buffer_client_overwrite_rt_exit();
1732 lttng_ring_buffer_client_overwrite_exit();
1733 lttng_ring_buffer_metadata_client_exit();
1734 lttng_ust_statedump_destroy();
1737 /* Reinitialize values for fork */
1739 lttng_ust_comm_should_quit
= 0;
1744 void __attribute__((destructor
)) lttng_ust_exit(void)
1749 * Using pthread_cancel here because:
1750 * A) we don't want to hang application teardown.
1751 * B) the thread is not allocating any resource.
1755 * Require the communication thread to quit. Synchronize with
1756 * mutexes to ensure it is not in a mutex critical section when
1757 * pthread_cancel is later called.
1760 lttng_ust_comm_should_quit
= 1;
1763 pthread_mutex_lock(&ust_exit_mutex
);
1764 /* cancel threads */
1765 if (global_apps
.thread_active
) {
1766 ret
= pthread_cancel(global_apps
.ust_listener
);
1768 ERR("Error cancelling global ust listener thread: %s",
1771 global_apps
.thread_active
= 0;
1774 if (local_apps
.thread_active
) {
1775 ret
= pthread_cancel(local_apps
.ust_listener
);
1777 ERR("Error cancelling local ust listener thread: %s",
1780 local_apps
.thread_active
= 0;
1783 pthread_mutex_unlock(&ust_exit_mutex
);
1786 * Do NOT join threads: use of sys_futex makes it impossible to
1787 * join the threads without using async-cancel, but async-cancel
1788 * is delivered by a signal, which could hit the target thread
1789 * anywhere in its code path, including while the ust_lock() is
1790 * held, causing a deadlock for the other thread. Let the OS
1791 * cleanup the threads if there are stalled in a syscall.
1793 lttng_ust_cleanup(1);
1797 * We exclude the worker threads across fork and clone (except
1798 * CLONE_VM), because these system calls only keep the forking thread
1799 * running in the child. Therefore, we don't want to call fork or clone
1800 * in the middle of an tracepoint or ust tracing state modification.
1801 * Holding this mutex protects these structures across fork and clone.
1803 void ust_before_fork(sigset_t
*save_sigset
)
1806 * Disable signals. This is to avoid that the child intervenes
1807 * before it is properly setup for tracing. It is safer to
1808 * disable all signals, because then we know we are not breaking
1809 * anything by restoring the original mask.
1814 if (URCU_TLS(lttng_ust_nest_count
))
1816 /* Disable signals */
1817 sigfillset(&all_sigs
);
1818 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
1820 PERROR("sigprocmask");
1823 pthread_mutex_lock(&ust_fork_mutex
);
1826 rcu_bp_before_fork();
1829 static void ust_after_fork_common(sigset_t
*restore_sigset
)
1833 DBG("process %d", getpid());
1836 pthread_mutex_unlock(&ust_fork_mutex
);
1838 /* Restore signals */
1839 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
1841 PERROR("sigprocmask");
1845 void ust_after_fork_parent(sigset_t
*restore_sigset
)
1847 if (URCU_TLS(lttng_ust_nest_count
))
1849 DBG("process %d", getpid());
1850 rcu_bp_after_fork_parent();
1851 /* Release mutexes and reenable signals */
1852 ust_after_fork_common(restore_sigset
);
1856 * After fork, in the child, we need to cleanup all the leftover state,
1857 * except the worker thread which already magically disappeared thanks
1858 * to the weird Linux fork semantics. After tyding up, we call
1859 * lttng_ust_init() again to start over as a new PID.
1861 * This is meant for forks() that have tracing in the child between the
1862 * fork and following exec call (if there is any).
1864 void ust_after_fork_child(sigset_t
*restore_sigset
)
1866 if (URCU_TLS(lttng_ust_nest_count
))
1868 lttng_context_vtid_reset();
1869 DBG("process %d", getpid());
1870 /* Release urcu mutexes */
1871 rcu_bp_after_fork_child();
1872 lttng_ust_cleanup(0);
1873 /* Release mutexes and reenable signals */
1874 ust_after_fork_common(restore_sigset
);
1878 void lttng_ust_sockinfo_session_enabled(void *owner
)
1880 struct sock_info
*sock_info
= owner
;
1881 sock_info
->statedump_pending
= 1;