Use rseq for cpu_id in libringbuffer
[lttng-ust.git] / liblttng-ust / lttng-ust-comm.c
1 /*
2 * lttng-ust-comm.c
3 *
4 * Copyright (C) 2011 David Goulet <david.goulet@polymtl.ca>
5 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
6 *
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.
11 *
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.
16 *
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
20 */
21
22 #define _LGPL_SOURCE
23 #define _GNU_SOURCE
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <sys/mman.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <pthread.h>
34 #include <semaphore.h>
35 #include <time.h>
36 #include <assert.h>
37 #include <signal.h>
38 #include <urcu/uatomic.h>
39 #include <urcu/futex.h>
40 #include <urcu/compiler.h>
41
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>
48 #include <ust-comm.h>
49 #include <ust-fd.h>
50 #include <usterr-signal-safe.h>
51 #include <helper.h>
52 #include "tracepoint-internal.h"
53 #include "lttng-tracer-core.h"
54 #include "compat.h"
55 #include "../libringbuffer/tlsfixup.h"
56 #include "lttng-ust-statedump.h"
57 #include "clock.h"
58 #include "../libringbuffer/getcpu.h"
59 #include "../libringbuffer/rseq.h"
60 #include "getenv.h"
61
62 /*
63 * Has lttng ust comm constructor been called ?
64 */
65 static int initialized;
66
67 /*
68 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
69 * Held when handling a command, also held by fork() to deal with
70 * removal of threads, and by exit path.
71 *
72 * The UST lock is the centralized mutex across UST tracing control and
73 * probe registration.
74 *
75 * ust_exit_mutex must never nest in ust_mutex.
76 *
77 * ust_fork_mutex must never nest in ust_mutex.
78 *
79 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
80 * counter lazy initialization called by events within the statedump,
81 * which traces while the ust_mutex is held.
82 *
83 * ust_lock nests within the dynamic loader lock (within glibc) because
84 * it is taken within the library constructor.
85 */
86 static pthread_mutex_t ust_mutex = PTHREAD_MUTEX_INITIALIZER;
87
88 /* Allow nesting the ust_mutex within the same thread. */
89 static DEFINE_URCU_TLS(int, ust_mutex_nest);
90
91 /*
92 * ust_exit_mutex protects thread_active variable wrt thread exit. It
93 * cannot be done by ust_mutex because pthread_cancel(), which takes an
94 * internal libc lock, cannot nest within ust_mutex.
95 *
96 * It never nests within a ust_mutex.
97 */
98 static pthread_mutex_t ust_exit_mutex = PTHREAD_MUTEX_INITIALIZER;
99
100 /*
101 * ust_fork_mutex protects base address statedump tracing against forks. It
102 * prevents the dynamic loader lock to be taken (by base address statedump
103 * tracing) while a fork is happening, thus preventing deadlock issues with
104 * the dynamic loader lock.
105 */
106 static pthread_mutex_t ust_fork_mutex = PTHREAD_MUTEX_INITIALIZER;
107
108 /* Should the ust comm thread quit ? */
109 static int lttng_ust_comm_should_quit;
110
111 /*
112 * This variable can be tested by applications to check whether
113 * lttng-ust is loaded. They simply have to define their own
114 * "lttng_ust_loaded" weak symbol, and test it. It is set to 1 by the
115 * library constructor.
116 */
117 int lttng_ust_loaded __attribute__((weak));
118
119 /*
120 * Return 0 on success, -1 if should quit.
121 * The lock is taken in both cases.
122 * Signal-safe.
123 */
124 int ust_lock(void)
125 {
126 sigset_t sig_all_blocked, orig_mask;
127 int ret, oldstate;
128
129 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
130 if (ret) {
131 ERR("pthread_setcancelstate: %s", strerror(ret));
132 }
133 if (oldstate != PTHREAD_CANCEL_ENABLE) {
134 ERR("pthread_setcancelstate: unexpected oldstate");
135 }
136 sigfillset(&sig_all_blocked);
137 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
138 if (ret) {
139 ERR("pthread_sigmask: %s", strerror(ret));
140 }
141 if (!URCU_TLS(ust_mutex_nest)++)
142 pthread_mutex_lock(&ust_mutex);
143 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
144 if (ret) {
145 ERR("pthread_sigmask: %s", strerror(ret));
146 }
147 if (lttng_ust_comm_should_quit) {
148 return -1;
149 } else {
150 return 0;
151 }
152 }
153
154 /*
155 * ust_lock_nocheck() can be used in constructors/destructors, because
156 * they are already nested within the dynamic loader lock, and therefore
157 * have exclusive access against execution of liblttng-ust destructor.
158 * Signal-safe.
159 */
160 void ust_lock_nocheck(void)
161 {
162 sigset_t sig_all_blocked, orig_mask;
163 int ret, oldstate;
164
165 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
166 if (ret) {
167 ERR("pthread_setcancelstate: %s", strerror(ret));
168 }
169 if (oldstate != PTHREAD_CANCEL_ENABLE) {
170 ERR("pthread_setcancelstate: unexpected oldstate");
171 }
172 sigfillset(&sig_all_blocked);
173 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
174 if (ret) {
175 ERR("pthread_sigmask: %s", strerror(ret));
176 }
177 if (!URCU_TLS(ust_mutex_nest)++)
178 pthread_mutex_lock(&ust_mutex);
179 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
180 if (ret) {
181 ERR("pthread_sigmask: %s", strerror(ret));
182 }
183 }
184
185 /*
186 * Signal-safe.
187 */
188 void ust_unlock(void)
189 {
190 sigset_t sig_all_blocked, orig_mask;
191 int ret, oldstate;
192
193 sigfillset(&sig_all_blocked);
194 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
195 if (ret) {
196 ERR("pthread_sigmask: %s", strerror(ret));
197 }
198 if (!--URCU_TLS(ust_mutex_nest))
199 pthread_mutex_unlock(&ust_mutex);
200 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
201 if (ret) {
202 ERR("pthread_sigmask: %s", strerror(ret));
203 }
204 ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
205 if (ret) {
206 ERR("pthread_setcancelstate: %s", strerror(ret));
207 }
208 if (oldstate != PTHREAD_CANCEL_DISABLE) {
209 ERR("pthread_setcancelstate: unexpected oldstate");
210 }
211 }
212
213 /*
214 * Wait for either of these before continuing to the main
215 * program:
216 * - the register_done message from sessiond daemon
217 * (will let the sessiond daemon enable sessions before main
218 * starts.)
219 * - sessiond daemon is not reachable.
220 * - timeout (ensuring applications are resilient to session
221 * daemon problems).
222 */
223 static sem_t constructor_wait;
224 /*
225 * Doing this for both the global and local sessiond.
226 */
227 static int sem_count = { 2 };
228
229 /*
230 * Counting nesting within lttng-ust. Used to ensure that calling fork()
231 * from liblttng-ust does not execute the pre/post fork handlers.
232 */
233 static DEFINE_URCU_TLS(int, lttng_ust_nest_count);
234
235 /*
236 * Info about socket and associated listener thread.
237 */
238 struct sock_info {
239 const char *name;
240 pthread_t ust_listener; /* listener thread */
241 int root_handle;
242 int constructor_sem_posted;
243 int allowed;
244 int global;
245 int thread_active;
246
247 char sock_path[PATH_MAX];
248 int socket;
249 int notify_socket;
250
251 char wait_shm_path[PATH_MAX];
252 char *wait_shm_mmap;
253 /* Keep track of lazy state dump not performed yet. */
254 int statedump_pending;
255 };
256
257 /* Socket from app (connect) to session daemon (listen) for communication */
258 struct sock_info global_apps = {
259 .name = "global",
260 .global = 1,
261
262 .root_handle = -1,
263 .allowed = 1,
264 .thread_active = 0,
265
266 .sock_path = LTTNG_DEFAULT_RUNDIR "/" LTTNG_UST_SOCK_FILENAME,
267 .socket = -1,
268 .notify_socket = -1,
269
270 .wait_shm_path = "/" LTTNG_UST_WAIT_FILENAME,
271
272 .statedump_pending = 0,
273 };
274
275 /* TODO: allow global_apps_sock_path override */
276
277 struct sock_info local_apps = {
278 .name = "local",
279 .global = 0,
280 .root_handle = -1,
281 .allowed = 0, /* Check setuid bit first */
282 .thread_active = 0,
283
284 .socket = -1,
285 .notify_socket = -1,
286
287 .statedump_pending = 0,
288 };
289
290 static int wait_poll_fallback;
291
292 static const char *cmd_name_mapping[] = {
293 [ LTTNG_UST_RELEASE ] = "Release",
294 [ LTTNG_UST_SESSION ] = "Create Session",
295 [ LTTNG_UST_TRACER_VERSION ] = "Get Tracer Version",
296
297 [ LTTNG_UST_TRACEPOINT_LIST ] = "Create Tracepoint List",
298 [ LTTNG_UST_WAIT_QUIESCENT ] = "Wait for Quiescent State",
299 [ LTTNG_UST_REGISTER_DONE ] = "Registration Done",
300 [ LTTNG_UST_TRACEPOINT_FIELD_LIST ] = "Create Tracepoint Field List",
301
302 /* Session FD commands */
303 [ LTTNG_UST_CHANNEL ] = "Create Channel",
304 [ LTTNG_UST_SESSION_START ] = "Start Session",
305 [ LTTNG_UST_SESSION_STOP ] = "Stop Session",
306
307 /* Channel FD commands */
308 [ LTTNG_UST_STREAM ] = "Create Stream",
309 [ LTTNG_UST_EVENT ] = "Create Event",
310
311 /* Event and Channel FD commands */
312 [ LTTNG_UST_CONTEXT ] = "Create Context",
313 [ LTTNG_UST_FLUSH_BUFFER ] = "Flush Buffer",
314
315 /* Event, Channel and Session commands */
316 [ LTTNG_UST_ENABLE ] = "Enable",
317 [ LTTNG_UST_DISABLE ] = "Disable",
318
319 /* Tracepoint list commands */
320 [ LTTNG_UST_TRACEPOINT_LIST_GET ] = "List Next Tracepoint",
321 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET ] = "List Next Tracepoint Field",
322
323 /* Event FD commands */
324 [ LTTNG_UST_FILTER ] = "Create Filter",
325 [ LTTNG_UST_EXCLUSION ] = "Add exclusions to event",
326 };
327
328 static const char *str_timeout;
329 static int got_timeout_env;
330
331 extern void lttng_ring_buffer_client_overwrite_init(void);
332 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
333 extern void lttng_ring_buffer_client_discard_init(void);
334 extern void lttng_ring_buffer_client_discard_rt_init(void);
335 extern void lttng_ring_buffer_metadata_client_init(void);
336 extern void lttng_ring_buffer_client_overwrite_exit(void);
337 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
338 extern void lttng_ring_buffer_client_discard_exit(void);
339 extern void lttng_ring_buffer_client_discard_rt_exit(void);
340 extern void lttng_ring_buffer_metadata_client_exit(void);
341
342 ssize_t lttng_ust_read(int fd, void *buf, size_t len)
343 {
344 ssize_t ret;
345 size_t copied = 0, to_copy = len;
346
347 do {
348 ret = read(fd, buf + copied, to_copy);
349 if (ret > 0) {
350 copied += ret;
351 to_copy -= ret;
352 }
353 } while ((ret > 0 && to_copy > 0)
354 || (ret < 0 && errno == EINTR));
355 if (ret > 0) {
356 ret = copied;
357 }
358 return ret;
359 }
360 /*
361 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
362 * pointer.
363 */
364 static
365 const char *get_lttng_home_dir(void)
366 {
367 const char *val;
368
369 val = (const char *) lttng_secure_getenv("LTTNG_HOME");
370 if (val != NULL) {
371 return val;
372 }
373 return (const char *) lttng_secure_getenv("HOME");
374 }
375
376 /*
377 * Force a read (imply TLS fixup for dlopen) of TLS variables.
378 */
379 static
380 void lttng_fixup_nest_count_tls(void)
381 {
382 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count)));
383 }
384
385 static
386 void lttng_fixup_ust_mutex_nest_tls(void)
387 {
388 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest)));
389 }
390
391 /*
392 * Fixup urcu bp TLS.
393 */
394 static
395 void lttng_fixup_urcu_bp_tls(void)
396 {
397 rcu_read_lock();
398 rcu_read_unlock();
399 }
400
401 void lttng_ust_fixup_tls(void)
402 {
403 lttng_fixup_urcu_bp_tls();
404 lttng_fixup_ringbuffer_tls();
405 lttng_fixup_vtid_tls();
406 lttng_fixup_nest_count_tls();
407 lttng_fixup_procname_tls();
408 lttng_fixup_ust_mutex_nest_tls();
409 lttng_ust_fixup_fd_tracker_tls();
410 }
411
412 int lttng_get_notify_socket(void *owner)
413 {
414 struct sock_info *info = owner;
415
416 return info->notify_socket;
417 }
418
419 static
420 void print_cmd(int cmd, int handle)
421 {
422 const char *cmd_name = "Unknown";
423
424 if (cmd >= 0 && cmd < LTTNG_ARRAY_SIZE(cmd_name_mapping)
425 && cmd_name_mapping[cmd]) {
426 cmd_name = cmd_name_mapping[cmd];
427 }
428 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
429 cmd_name, cmd,
430 lttng_ust_obj_get_name(handle), handle);
431 }
432
433 static
434 int setup_local_apps(void)
435 {
436 const char *home_dir;
437 uid_t uid;
438
439 uid = getuid();
440 /*
441 * Disallow per-user tracing for setuid binaries.
442 */
443 if (uid != geteuid()) {
444 assert(local_apps.allowed == 0);
445 return 0;
446 }
447 home_dir = get_lttng_home_dir();
448 if (!home_dir) {
449 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
450 assert(local_apps.allowed == 0);
451 return -ENOENT;
452 }
453 local_apps.allowed = 1;
454 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
455 home_dir,
456 LTTNG_DEFAULT_HOME_RUNDIR,
457 LTTNG_UST_SOCK_FILENAME);
458 snprintf(local_apps.wait_shm_path, PATH_MAX, "/%s-%u",
459 LTTNG_UST_WAIT_FILENAME,
460 uid);
461 return 0;
462 }
463
464 /*
465 * Get socket timeout, in ms.
466 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
467 */
468 static
469 long get_timeout(void)
470 {
471 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
472
473 if (!got_timeout_env) {
474 str_timeout = getenv("LTTNG_UST_REGISTER_TIMEOUT");
475 got_timeout_env = 1;
476 }
477 if (str_timeout)
478 constructor_delay_ms = strtol(str_timeout, NULL, 10);
479 /* All negative values are considered as "-1". */
480 if (constructor_delay_ms < -1)
481 constructor_delay_ms = -1;
482 return constructor_delay_ms;
483 }
484
485 /* Timeout for notify socket send and recv. */
486 static
487 long get_notify_sock_timeout(void)
488 {
489 return get_timeout();
490 }
491
492 /* Timeout for connecting to cmd and notify sockets. */
493 static
494 long get_connect_sock_timeout(void)
495 {
496 return get_timeout();
497 }
498
499 /*
500 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
501 */
502 static
503 int get_constructor_timeout(struct timespec *constructor_timeout)
504 {
505 long constructor_delay_ms;
506 int ret;
507
508 constructor_delay_ms = get_timeout();
509
510 switch (constructor_delay_ms) {
511 case -1:/* fall-through */
512 case 0:
513 return constructor_delay_ms;
514 default:
515 break;
516 }
517
518 /*
519 * If we are unable to find the current time, don't wait.
520 */
521 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
522 if (ret) {
523 /* Don't wait. */
524 return 0;
525 }
526 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
527 constructor_timeout->tv_nsec +=
528 (constructor_delay_ms % 1000UL) * 1000000UL;
529 if (constructor_timeout->tv_nsec >= 1000000000UL) {
530 constructor_timeout->tv_sec++;
531 constructor_timeout->tv_nsec -= 1000000000UL;
532 }
533 /* Timeout wait (constructor_delay_ms). */
534 return 1;
535 }
536
537 static
538 int register_to_sessiond(int socket, enum ustctl_socket_type type)
539 {
540 return ustcomm_send_reg_msg(socket,
541 type,
542 CAA_BITS_PER_LONG,
543 lttng_alignof(uint8_t) * CHAR_BIT,
544 lttng_alignof(uint16_t) * CHAR_BIT,
545 lttng_alignof(uint32_t) * CHAR_BIT,
546 lttng_alignof(uint64_t) * CHAR_BIT,
547 lttng_alignof(unsigned long) * CHAR_BIT);
548 }
549
550 static
551 int send_reply(int sock, struct ustcomm_ust_reply *lur)
552 {
553 ssize_t len;
554
555 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
556 switch (len) {
557 case sizeof(*lur):
558 DBG("message successfully sent");
559 return 0;
560 default:
561 if (len == -ECONNRESET) {
562 DBG("remote end closed connection");
563 return 0;
564 }
565 if (len < 0)
566 return len;
567 DBG("incorrect message size: %zd", len);
568 return -EINVAL;
569 }
570 }
571
572 static
573 int handle_register_done(struct sock_info *sock_info)
574 {
575 int ret;
576
577 if (sock_info->constructor_sem_posted)
578 return 0;
579 sock_info->constructor_sem_posted = 1;
580 if (uatomic_read(&sem_count) <= 0) {
581 return 0;
582 }
583 ret = uatomic_add_return(&sem_count, -1);
584 if (ret == 0) {
585 ret = sem_post(&constructor_wait);
586 assert(!ret);
587 }
588 return 0;
589 }
590
591 /*
592 * Only execute pending statedump after the constructor semaphore has
593 * been posted by each listener thread. This means statedump will only
594 * be performed after the "registration done" command is received from
595 * each session daemon the application is connected to.
596 *
597 * This ensures we don't run into deadlock issues with the dynamic
598 * loader mutex, which is held while the constructor is called and
599 * waiting on the constructor semaphore. All operations requiring this
600 * dynamic loader lock need to be postponed using this mechanism.
601 */
602 static
603 void handle_pending_statedump(struct sock_info *sock_info)
604 {
605 int ctor_passed = sock_info->constructor_sem_posted;
606
607 if (ctor_passed && sock_info->statedump_pending) {
608 sock_info->statedump_pending = 0;
609 pthread_mutex_lock(&ust_fork_mutex);
610 lttng_handle_pending_statedump(sock_info);
611 pthread_mutex_unlock(&ust_fork_mutex);
612 }
613 }
614
615 static
616 int handle_message(struct sock_info *sock_info,
617 int sock, struct ustcomm_ust_msg *lum)
618 {
619 int ret = 0;
620 const struct lttng_ust_objd_ops *ops;
621 struct ustcomm_ust_reply lur;
622 union ust_args args;
623 char ctxstr[LTTNG_UST_SYM_NAME_LEN]; /* App context string. */
624 ssize_t len;
625
626 memset(&lur, 0, sizeof(lur));
627
628 if (ust_lock()) {
629 ret = -LTTNG_UST_ERR_EXITING;
630 goto error;
631 }
632
633 ops = objd_ops(lum->handle);
634 if (!ops) {
635 ret = -ENOENT;
636 goto error;
637 }
638
639 switch (lum->cmd) {
640 case LTTNG_UST_REGISTER_DONE:
641 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
642 ret = handle_register_done(sock_info);
643 else
644 ret = -EINVAL;
645 break;
646 case LTTNG_UST_RELEASE:
647 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
648 ret = -EPERM;
649 else
650 ret = lttng_ust_objd_unref(lum->handle, 1);
651 break;
652 case LTTNG_UST_FILTER:
653 {
654 /* Receive filter data */
655 struct lttng_ust_filter_bytecode_node *bytecode;
656
657 if (lum->u.filter.data_size > FILTER_BYTECODE_MAX_LEN) {
658 ERR("Filter data size is too large: %u bytes",
659 lum->u.filter.data_size);
660 ret = -EINVAL;
661 goto error;
662 }
663
664 if (lum->u.filter.reloc_offset > lum->u.filter.data_size) {
665 ERR("Filter reloc offset %u is not within data",
666 lum->u.filter.reloc_offset);
667 ret = -EINVAL;
668 goto error;
669 }
670
671 bytecode = zmalloc(sizeof(*bytecode) + lum->u.filter.data_size);
672 if (!bytecode) {
673 ret = -ENOMEM;
674 goto error;
675 }
676 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data,
677 lum->u.filter.data_size);
678 switch (len) {
679 case 0: /* orderly shutdown */
680 ret = 0;
681 free(bytecode);
682 goto error;
683 default:
684 if (len == lum->u.filter.data_size) {
685 DBG("filter data received");
686 break;
687 } else if (len < 0) {
688 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
689 if (len == -ECONNRESET) {
690 ERR("%s remote end closed connection", sock_info->name);
691 ret = len;
692 free(bytecode);
693 goto error;
694 }
695 ret = len;
696 free(bytecode);
697 goto error;
698 } else {
699 DBG("incorrect filter data message size: %zd", len);
700 ret = -EINVAL;
701 free(bytecode);
702 goto error;
703 }
704 }
705 bytecode->bc.len = lum->u.filter.data_size;
706 bytecode->bc.reloc_offset = lum->u.filter.reloc_offset;
707 bytecode->bc.seqnum = lum->u.filter.seqnum;
708 if (ops->cmd) {
709 ret = ops->cmd(lum->handle, lum->cmd,
710 (unsigned long) bytecode,
711 &args, sock_info);
712 if (ret) {
713 free(bytecode);
714 }
715 /* don't free bytecode if everything went fine. */
716 } else {
717 ret = -ENOSYS;
718 free(bytecode);
719 }
720 break;
721 }
722 case LTTNG_UST_EXCLUSION:
723 {
724 /* Receive exclusion names */
725 struct lttng_ust_excluder_node *node;
726 unsigned int count;
727
728 count = lum->u.exclusion.count;
729 if (count == 0) {
730 /* There are no names to read */
731 ret = 0;
732 goto error;
733 }
734 node = zmalloc(sizeof(*node) +
735 count * LTTNG_UST_SYM_NAME_LEN);
736 if (!node) {
737 ret = -ENOMEM;
738 goto error;
739 }
740 node->excluder.count = count;
741 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
742 count * LTTNG_UST_SYM_NAME_LEN);
743 switch (len) {
744 case 0: /* orderly shutdown */
745 ret = 0;
746 free(node);
747 goto error;
748 default:
749 if (len == count * LTTNG_UST_SYM_NAME_LEN) {
750 DBG("Exclusion data received");
751 break;
752 } else if (len < 0) {
753 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
754 if (len == -ECONNRESET) {
755 ERR("%s remote end closed connection", sock_info->name);
756 ret = len;
757 free(node);
758 goto error;
759 }
760 ret = len;
761 free(node);
762 goto error;
763 } else {
764 DBG("Incorrect exclusion data message size: %zd", len);
765 ret = -EINVAL;
766 free(node);
767 goto error;
768 }
769 }
770 if (ops->cmd) {
771 ret = ops->cmd(lum->handle, lum->cmd,
772 (unsigned long) node,
773 &args, sock_info);
774 if (ret) {
775 free(node);
776 }
777 /* Don't free exclusion data if everything went fine. */
778 } else {
779 ret = -ENOSYS;
780 free(node);
781 }
782 break;
783 }
784 case LTTNG_UST_CHANNEL:
785 {
786 void *chan_data;
787 int wakeup_fd;
788
789 len = ustcomm_recv_channel_from_sessiond(sock,
790 &chan_data, lum->u.channel.len,
791 &wakeup_fd);
792 switch (len) {
793 case 0: /* orderly shutdown */
794 ret = 0;
795 goto error;
796 default:
797 if (len == lum->u.channel.len) {
798 DBG("channel data received");
799 break;
800 } else if (len < 0) {
801 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
802 if (len == -ECONNRESET) {
803 ERR("%s remote end closed connection", sock_info->name);
804 ret = len;
805 goto error;
806 }
807 ret = len;
808 goto error;
809 } else {
810 DBG("incorrect channel data message size: %zd", len);
811 ret = -EINVAL;
812 goto error;
813 }
814 }
815 args.channel.chan_data = chan_data;
816 args.channel.wakeup_fd = wakeup_fd;
817 if (ops->cmd)
818 ret = ops->cmd(lum->handle, lum->cmd,
819 (unsigned long) &lum->u,
820 &args, sock_info);
821 else
822 ret = -ENOSYS;
823 break;
824 }
825 case LTTNG_UST_STREAM:
826 {
827 /* Receive shm_fd, wakeup_fd */
828 ret = ustcomm_recv_stream_from_sessiond(sock,
829 &lum->u.stream.len,
830 &args.stream.shm_fd,
831 &args.stream.wakeup_fd);
832 if (ret) {
833 goto error;
834 }
835 if (ops->cmd)
836 ret = ops->cmd(lum->handle, lum->cmd,
837 (unsigned long) &lum->u,
838 &args, sock_info);
839 else
840 ret = -ENOSYS;
841 break;
842 }
843 case LTTNG_UST_CONTEXT:
844 switch (lum->u.context.ctx) {
845 case LTTNG_UST_CONTEXT_APP_CONTEXT:
846 {
847 char *p;
848 size_t ctxlen, recvlen;
849
850 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
851 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
852 if (ctxlen >= LTTNG_UST_SYM_NAME_LEN) {
853 ERR("Application context string length size is too large: %zu bytes",
854 ctxlen);
855 ret = -EINVAL;
856 goto error;
857 }
858 strcpy(ctxstr, "$app.");
859 p = &ctxstr[strlen("$app.")];
860 recvlen = ctxlen - strlen("$app.");
861 len = ustcomm_recv_unix_sock(sock, p, recvlen);
862 switch (len) {
863 case 0: /* orderly shutdown */
864 ret = 0;
865 goto error;
866 default:
867 if (len == recvlen) {
868 DBG("app context data received");
869 break;
870 } else if (len < 0) {
871 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
872 if (len == -ECONNRESET) {
873 ERR("%s remote end closed connection", sock_info->name);
874 ret = len;
875 goto error;
876 }
877 ret = len;
878 goto error;
879 } else {
880 DBG("incorrect app context data message size: %zd", len);
881 ret = -EINVAL;
882 goto error;
883 }
884 }
885 /* Put : between provider and ctxname. */
886 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
887 args.app_context.ctxname = ctxstr;
888 break;
889 }
890 default:
891 break;
892 }
893 if (ops->cmd) {
894 ret = ops->cmd(lum->handle, lum->cmd,
895 (unsigned long) &lum->u,
896 &args, sock_info);
897 } else {
898 ret = -ENOSYS;
899 }
900 break;
901 default:
902 if (ops->cmd)
903 ret = ops->cmd(lum->handle, lum->cmd,
904 (unsigned long) &lum->u,
905 &args, sock_info);
906 else
907 ret = -ENOSYS;
908 break;
909 }
910
911 lur.handle = lum->handle;
912 lur.cmd = lum->cmd;
913 lur.ret_val = ret;
914 if (ret >= 0) {
915 lur.ret_code = LTTNG_UST_OK;
916 } else {
917 /*
918 * Use -LTTNG_UST_ERR as wildcard for UST internal
919 * error that are not caused by the transport, except if
920 * we already have a more precise error message to
921 * report.
922 */
923 if (ret > -LTTNG_UST_ERR) {
924 /* Translate code to UST error. */
925 switch (ret) {
926 case -EEXIST:
927 lur.ret_code = -LTTNG_UST_ERR_EXIST;
928 break;
929 case -EINVAL:
930 lur.ret_code = -LTTNG_UST_ERR_INVAL;
931 break;
932 case -ENOENT:
933 lur.ret_code = -LTTNG_UST_ERR_NOENT;
934 break;
935 case -EPERM:
936 lur.ret_code = -LTTNG_UST_ERR_PERM;
937 break;
938 case -ENOSYS:
939 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
940 break;
941 default:
942 lur.ret_code = -LTTNG_UST_ERR;
943 break;
944 }
945 } else {
946 lur.ret_code = ret;
947 }
948 }
949 if (ret >= 0) {
950 switch (lum->cmd) {
951 case LTTNG_UST_TRACER_VERSION:
952 lur.u.version = lum->u.version;
953 break;
954 case LTTNG_UST_TRACEPOINT_LIST_GET:
955 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
956 break;
957 }
958 }
959 DBG("Return value: %d", lur.ret_val);
960
961 ust_unlock();
962
963 /*
964 * Performed delayed statedump operations outside of the UST
965 * lock. We need to take the dynamic loader lock before we take
966 * the UST lock internally within handle_pending_statedump().
967 */
968 handle_pending_statedump(sock_info);
969
970 if (ust_lock()) {
971 ret = -LTTNG_UST_ERR_EXITING;
972 goto error;
973 }
974
975 ret = send_reply(sock, &lur);
976 if (ret < 0) {
977 DBG("error sending reply");
978 goto error;
979 }
980
981 /*
982 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
983 * after the reply.
984 */
985 if (lur.ret_code == LTTNG_UST_OK) {
986 switch (lum->cmd) {
987 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
988 len = ustcomm_send_unix_sock(sock,
989 &args.field_list.entry,
990 sizeof(args.field_list.entry));
991 if (len < 0) {
992 ret = len;
993 goto error;
994 }
995 if (len != sizeof(args.field_list.entry)) {
996 ret = -EINVAL;
997 goto error;
998 }
999 }
1000 }
1001
1002 error:
1003 ust_unlock();
1004
1005 return ret;
1006 }
1007
1008 static
1009 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
1010 {
1011 int ret;
1012
1013 if (sock_info->root_handle != -1) {
1014 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1015 if (ret) {
1016 ERR("Error unref root handle");
1017 }
1018 sock_info->root_handle = -1;
1019 }
1020 sock_info->constructor_sem_posted = 0;
1021
1022 /*
1023 * wait_shm_mmap, socket and notify socket are used by listener
1024 * threads outside of the ust lock, so we cannot tear them down
1025 * ourselves, because we cannot join on these threads. Leave
1026 * responsibility of cleaning up these resources to the OS
1027 * process exit.
1028 */
1029 if (exiting)
1030 return;
1031
1032 if (sock_info->socket != -1) {
1033 ret = ustcomm_close_unix_sock(sock_info->socket);
1034 if (ret) {
1035 ERR("Error closing ust cmd socket");
1036 }
1037 sock_info->socket = -1;
1038 }
1039 if (sock_info->notify_socket != -1) {
1040 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1041 if (ret) {
1042 ERR("Error closing ust notify socket");
1043 }
1044 sock_info->notify_socket = -1;
1045 }
1046 if (sock_info->wait_shm_mmap) {
1047 long page_size;
1048
1049 page_size = sysconf(_SC_PAGE_SIZE);
1050 if (page_size <= 0) {
1051 if (!page_size) {
1052 errno = EINVAL;
1053 }
1054 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1055 } else {
1056 ret = munmap(sock_info->wait_shm_mmap, page_size);
1057 if (ret) {
1058 ERR("Error unmapping wait shm");
1059 }
1060 }
1061 sock_info->wait_shm_mmap = NULL;
1062 }
1063 }
1064
1065 /*
1066 * Using fork to set umask in the child process (not multi-thread safe).
1067 * We deal with the shm_open vs ftruncate race (happening when the
1068 * sessiond owns the shm and does not let everybody modify it, to ensure
1069 * safety against shm_unlink) by simply letting the mmap fail and
1070 * retrying after a few seconds.
1071 * For global shm, everybody has rw access to it until the sessiond
1072 * starts.
1073 */
1074 static
1075 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
1076 {
1077 int wait_shm_fd, ret;
1078 pid_t pid;
1079
1080 /*
1081 * Try to open read-only.
1082 */
1083 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1084 if (wait_shm_fd >= 0) {
1085 int32_t tmp_read;
1086 ssize_t len;
1087 size_t bytes_read = 0;
1088
1089 /*
1090 * Try to read the fd. If unable to do so, try opening
1091 * it in write mode.
1092 */
1093 do {
1094 len = read(wait_shm_fd,
1095 &((char *) &tmp_read)[bytes_read],
1096 sizeof(tmp_read) - bytes_read);
1097 if (len > 0) {
1098 bytes_read += len;
1099 }
1100 } while ((len < 0 && errno == EINTR)
1101 || (len > 0 && bytes_read < sizeof(tmp_read)));
1102 if (bytes_read != sizeof(tmp_read)) {
1103 ret = close(wait_shm_fd);
1104 if (ret) {
1105 ERR("close wait_shm_fd");
1106 }
1107 goto open_write;
1108 }
1109 goto end;
1110 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1111 /*
1112 * Real-only open did not work, and it's not because the
1113 * entry was not present. It's a failure that prohibits
1114 * using shm.
1115 */
1116 ERR("Error opening shm %s", sock_info->wait_shm_path);
1117 goto end;
1118 }
1119
1120 open_write:
1121 /*
1122 * If the open failed because the file did not exist, or because
1123 * the file was not truncated yet, try creating it ourself.
1124 */
1125 URCU_TLS(lttng_ust_nest_count)++;
1126 pid = fork();
1127 URCU_TLS(lttng_ust_nest_count)--;
1128 if (pid > 0) {
1129 int status;
1130
1131 /*
1132 * Parent: wait for child to return, in which case the
1133 * shared memory map will have been created.
1134 */
1135 pid = wait(&status);
1136 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1137 wait_shm_fd = -1;
1138 goto end;
1139 }
1140 /*
1141 * Try to open read-only again after creation.
1142 */
1143 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1144 if (wait_shm_fd < 0) {
1145 /*
1146 * Real-only open did not work. It's a failure
1147 * that prohibits using shm.
1148 */
1149 ERR("Error opening shm %s", sock_info->wait_shm_path);
1150 goto end;
1151 }
1152 goto end;
1153 } else if (pid == 0) {
1154 int create_mode;
1155
1156 /* Child */
1157 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
1158 if (sock_info->global)
1159 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
1160 /*
1161 * We're alone in a child process, so we can modify the
1162 * process-wide umask.
1163 */
1164 umask(~create_mode);
1165 /*
1166 * Try creating shm (or get rw access).
1167 * We don't do an exclusive open, because we allow other
1168 * processes to create+ftruncate it concurrently.
1169 */
1170 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1171 O_RDWR | O_CREAT, create_mode);
1172 if (wait_shm_fd >= 0) {
1173 ret = ftruncate(wait_shm_fd, mmap_size);
1174 if (ret) {
1175 PERROR("ftruncate");
1176 _exit(EXIT_FAILURE);
1177 }
1178 _exit(EXIT_SUCCESS);
1179 }
1180 /*
1181 * For local shm, we need to have rw access to accept
1182 * opening it: this means the local sessiond will be
1183 * able to wake us up. For global shm, we open it even
1184 * if rw access is not granted, because the root.root
1185 * sessiond will be able to override all rights and wake
1186 * us up.
1187 */
1188 if (!sock_info->global && errno != EACCES) {
1189 ERR("Error opening shm %s", sock_info->wait_shm_path);
1190 _exit(EXIT_FAILURE);
1191 }
1192 /*
1193 * The shm exists, but we cannot open it RW. Report
1194 * success.
1195 */
1196 _exit(EXIT_SUCCESS);
1197 } else {
1198 return -1;
1199 }
1200 end:
1201 if (wait_shm_fd >= 0 && !sock_info->global) {
1202 struct stat statbuf;
1203
1204 /*
1205 * Ensure that our user is the owner of the shm file for
1206 * local shm. If we do not own the file, it means our
1207 * sessiond will not have access to wake us up (there is
1208 * probably a rogue process trying to fake our
1209 * sessiond). Fallback to polling method in this case.
1210 */
1211 ret = fstat(wait_shm_fd, &statbuf);
1212 if (ret) {
1213 PERROR("fstat");
1214 goto error_close;
1215 }
1216 if (statbuf.st_uid != getuid())
1217 goto error_close;
1218 }
1219 return wait_shm_fd;
1220
1221 error_close:
1222 ret = close(wait_shm_fd);
1223 if (ret) {
1224 PERROR("Error closing fd");
1225 }
1226 return -1;
1227 }
1228
1229 static
1230 char *get_map_shm(struct sock_info *sock_info)
1231 {
1232 long page_size;
1233 int wait_shm_fd, ret;
1234 char *wait_shm_mmap;
1235
1236 page_size = sysconf(_SC_PAGE_SIZE);
1237 if (page_size <= 0) {
1238 if (!page_size) {
1239 errno = EINVAL;
1240 }
1241 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1242 goto error;
1243 }
1244
1245 lttng_ust_lock_fd_tracker();
1246 wait_shm_fd = get_wait_shm(sock_info, page_size);
1247 if (wait_shm_fd < 0) {
1248 lttng_ust_unlock_fd_tracker();
1249 goto error;
1250 }
1251 lttng_ust_add_fd_to_tracker(wait_shm_fd);
1252 lttng_ust_unlock_fd_tracker();
1253
1254 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
1255 MAP_SHARED, wait_shm_fd, 0);
1256
1257 /* close shm fd immediately after taking the mmap reference */
1258 lttng_ust_lock_fd_tracker();
1259 ret = close(wait_shm_fd);
1260 if (!ret) {
1261 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1262 } else {
1263 PERROR("Error closing fd");
1264 }
1265 lttng_ust_unlock_fd_tracker();
1266
1267 if (wait_shm_mmap == MAP_FAILED) {
1268 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1269 goto error;
1270 }
1271 return wait_shm_mmap;
1272
1273 error:
1274 return NULL;
1275 }
1276
1277 static
1278 void wait_for_sessiond(struct sock_info *sock_info)
1279 {
1280 if (ust_lock()) {
1281 goto quit;
1282 }
1283 if (wait_poll_fallback) {
1284 goto error;
1285 }
1286 if (!sock_info->wait_shm_mmap) {
1287 sock_info->wait_shm_mmap = get_map_shm(sock_info);
1288 if (!sock_info->wait_shm_mmap)
1289 goto error;
1290 }
1291 ust_unlock();
1292
1293 DBG("Waiting for %s apps sessiond", sock_info->name);
1294 /* Wait for futex wakeup */
1295 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1296 goto end_wait;
1297
1298 while (futex_async((int32_t *) sock_info->wait_shm_mmap,
1299 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1300 switch (errno) {
1301 case EWOULDBLOCK:
1302 /* Value already changed. */
1303 goto end_wait;
1304 case EINTR:
1305 /* Retry if interrupted by signal. */
1306 break; /* Get out of switch. */
1307 case EFAULT:
1308 wait_poll_fallback = 1;
1309 DBG(
1310 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1311 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1312 "Please upgrade your kernel "
1313 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1314 "mainline). LTTng-UST will use polling mode fallback.");
1315 if (ust_debug())
1316 PERROR("futex");
1317 goto end_wait;
1318 }
1319 }
1320 end_wait:
1321 return;
1322
1323 quit:
1324 ust_unlock();
1325 return;
1326
1327 error:
1328 ust_unlock();
1329 return;
1330 }
1331
1332 /*
1333 * This thread does not allocate any resource, except within
1334 * handle_message, within mutex protection. This mutex protects against
1335 * fork and exit.
1336 * The other moment it allocates resources is at socket connection, which
1337 * is also protected by the mutex.
1338 */
1339 static
1340 void *ust_listener_thread(void *arg)
1341 {
1342 struct sock_info *sock_info = arg;
1343 int sock, ret, prev_connect_failed = 0, has_waited = 0;
1344 long timeout;
1345
1346 lttng_ust_fixup_tls();
1347 /*
1348 * If available, add '-ust' to the end of this thread's
1349 * process name
1350 */
1351 ret = lttng_ust_setustprocname();
1352 if (ret) {
1353 ERR("Unable to set UST process name");
1354 }
1355
1356 /* Restart trying to connect to the session daemon */
1357 restart:
1358 if (prev_connect_failed) {
1359 /* Wait for sessiond availability with pipe */
1360 wait_for_sessiond(sock_info);
1361 if (has_waited) {
1362 has_waited = 0;
1363 /*
1364 * Sleep for 5 seconds before retrying after a
1365 * sequence of failure / wait / failure. This
1366 * deals with a killed or broken session daemon.
1367 */
1368 sleep(5);
1369 } else {
1370 has_waited = 1;
1371 }
1372 prev_connect_failed = 0;
1373 }
1374
1375 if (sock_info->socket != -1) {
1376 /* FD tracker is updated by ustcomm_close_unix_sock() */
1377 ret = ustcomm_close_unix_sock(sock_info->socket);
1378 if (ret) {
1379 ERR("Error closing %s ust cmd socket",
1380 sock_info->name);
1381 }
1382 sock_info->socket = -1;
1383 }
1384 if (sock_info->notify_socket != -1) {
1385 /* FD tracker is updated by ustcomm_close_unix_sock() */
1386 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1387 if (ret) {
1388 ERR("Error closing %s ust notify socket",
1389 sock_info->name);
1390 }
1391 sock_info->notify_socket = -1;
1392 }
1393
1394 if (ust_lock()) {
1395 goto quit;
1396 }
1397
1398 /*
1399 * Register. We need to perform both connect and sending
1400 * registration message before doing the next connect otherwise
1401 * we may reach unix socket connect queue max limits and block
1402 * on the 2nd connect while the session daemon is awaiting the
1403 * first connect registration message.
1404 */
1405 /* Connect cmd socket */
1406 lttng_ust_lock_fd_tracker();
1407 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1408 get_connect_sock_timeout());
1409 if (ret < 0) {
1410 lttng_ust_unlock_fd_tracker();
1411 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1412 prev_connect_failed = 1;
1413
1414 /*
1415 * If we cannot find the sessiond daemon, don't delay
1416 * constructor execution.
1417 */
1418 ret = handle_register_done(sock_info);
1419 assert(!ret);
1420 ust_unlock();
1421 goto restart;
1422 }
1423 lttng_ust_add_fd_to_tracker(ret);
1424 lttng_ust_unlock_fd_tracker();
1425 sock_info->socket = ret;
1426
1427 ust_unlock();
1428 /*
1429 * Unlock/relock ust lock because connect is blocking (with
1430 * timeout). Don't delay constructors on the ust lock for too
1431 * long.
1432 */
1433 if (ust_lock()) {
1434 goto quit;
1435 }
1436
1437 /*
1438 * Create only one root handle per listener thread for the whole
1439 * process lifetime, so we ensure we get ID which is statically
1440 * assigned to the root handle.
1441 */
1442 if (sock_info->root_handle == -1) {
1443 ret = lttng_abi_create_root_handle();
1444 if (ret < 0) {
1445 ERR("Error creating root handle");
1446 goto quit;
1447 }
1448 sock_info->root_handle = ret;
1449 }
1450
1451 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
1452 if (ret < 0) {
1453 ERR("Error registering to %s ust cmd socket",
1454 sock_info->name);
1455 prev_connect_failed = 1;
1456 /*
1457 * If we cannot register to the sessiond daemon, don't
1458 * delay constructor execution.
1459 */
1460 ret = handle_register_done(sock_info);
1461 assert(!ret);
1462 ust_unlock();
1463 goto restart;
1464 }
1465
1466 ust_unlock();
1467 /*
1468 * Unlock/relock ust lock because connect is blocking (with
1469 * timeout). Don't delay constructors on the ust lock for too
1470 * long.
1471 */
1472 if (ust_lock()) {
1473 goto quit;
1474 }
1475
1476 /* Connect notify socket */
1477 lttng_ust_lock_fd_tracker();
1478 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1479 get_connect_sock_timeout());
1480 if (ret < 0) {
1481 lttng_ust_unlock_fd_tracker();
1482 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1483 prev_connect_failed = 1;
1484
1485 /*
1486 * If we cannot find the sessiond daemon, don't delay
1487 * constructor execution.
1488 */
1489 ret = handle_register_done(sock_info);
1490 assert(!ret);
1491 ust_unlock();
1492 goto restart;
1493 }
1494 lttng_ust_add_fd_to_tracker(ret);
1495 lttng_ust_unlock_fd_tracker();
1496 sock_info->notify_socket = ret;
1497
1498 ust_unlock();
1499 /*
1500 * Unlock/relock ust lock because connect is blocking (with
1501 * timeout). Don't delay constructors on the ust lock for too
1502 * long.
1503 */
1504 if (ust_lock()) {
1505 goto quit;
1506 }
1507
1508 timeout = get_notify_sock_timeout();
1509 if (timeout >= 0) {
1510 /*
1511 * Give at least 10ms to sessiond to reply to
1512 * notifications.
1513 */
1514 if (timeout < 10)
1515 timeout = 10;
1516 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1517 timeout);
1518 if (ret < 0) {
1519 WARN("Error setting socket receive timeout");
1520 }
1521 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1522 timeout);
1523 if (ret < 0) {
1524 WARN("Error setting socket send timeout");
1525 }
1526 } else if (timeout < -1) {
1527 WARN("Unsupported timeout value %ld", timeout);
1528 }
1529
1530 ret = register_to_sessiond(sock_info->notify_socket,
1531 USTCTL_SOCKET_NOTIFY);
1532 if (ret < 0) {
1533 ERR("Error registering to %s ust notify socket",
1534 sock_info->name);
1535 prev_connect_failed = 1;
1536 /*
1537 * If we cannot register to the sessiond daemon, don't
1538 * delay constructor execution.
1539 */
1540 ret = handle_register_done(sock_info);
1541 assert(!ret);
1542 ust_unlock();
1543 goto restart;
1544 }
1545 sock = sock_info->socket;
1546
1547 ust_unlock();
1548
1549 for (;;) {
1550 ssize_t len;
1551 struct ustcomm_ust_msg lum;
1552
1553 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1554 switch (len) {
1555 case 0: /* orderly shutdown */
1556 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
1557 if (ust_lock()) {
1558 goto quit;
1559 }
1560 /*
1561 * Either sessiond has shutdown or refused us by closing the socket.
1562 * In either case, we don't want to delay construction execution,
1563 * and we need to wait before retry.
1564 */
1565 prev_connect_failed = 1;
1566 /*
1567 * If we cannot register to the sessiond daemon, don't
1568 * delay constructor execution.
1569 */
1570 ret = handle_register_done(sock_info);
1571 assert(!ret);
1572 ust_unlock();
1573 goto end;
1574 case sizeof(lum):
1575 print_cmd(lum.cmd, lum.handle);
1576 ret = handle_message(sock_info, sock, &lum);
1577 if (ret) {
1578 ERR("Error handling message for %s socket",
1579 sock_info->name);
1580 /*
1581 * Close socket if protocol error is
1582 * detected.
1583 */
1584 goto end;
1585 }
1586 continue;
1587 default:
1588 if (len < 0) {
1589 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1590 } else {
1591 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1592 }
1593 if (len == -ECONNRESET) {
1594 DBG("%s remote end closed connection", sock_info->name);
1595 goto end;
1596 }
1597 goto end;
1598 }
1599
1600 }
1601 end:
1602 if (ust_lock()) {
1603 goto quit;
1604 }
1605 /* Cleanup socket handles before trying to reconnect */
1606 lttng_ust_objd_table_owner_cleanup(sock_info);
1607 ust_unlock();
1608 goto restart; /* try to reconnect */
1609
1610 quit:
1611 ust_unlock();
1612
1613 pthread_mutex_lock(&ust_exit_mutex);
1614 sock_info->thread_active = 0;
1615 pthread_mutex_unlock(&ust_exit_mutex);
1616 return NULL;
1617 }
1618
1619 /*
1620 * Weak symbol to call when the ust malloc wrapper is not loaded.
1621 */
1622 __attribute__((weak))
1623 void lttng_ust_malloc_wrapper_init(void)
1624 {
1625 }
1626
1627 /*
1628 * sessiond monitoring thread: monitor presence of global and per-user
1629 * sessiond by polling the application common named pipe.
1630 */
1631 void __attribute__((constructor)) lttng_ust_init(void)
1632 {
1633 struct timespec constructor_timeout;
1634 sigset_t sig_all_blocked, orig_parent_mask;
1635 pthread_attr_t thread_attr;
1636 int timeout_mode;
1637 int ret;
1638
1639 if (uatomic_xchg(&initialized, 1) == 1)
1640 return;
1641
1642 /*
1643 * Fixup interdependency between TLS fixup mutex (which happens
1644 * to be the dynamic linker mutex) and ust_lock, taken within
1645 * the ust lock.
1646 */
1647 lttng_ust_fixup_tls();
1648
1649 lttng_ust_loaded = 1;
1650
1651 /*
1652 * We want precise control over the order in which we construct
1653 * our sub-libraries vs starting to receive commands from
1654 * sessiond (otherwise leading to errors when trying to create
1655 * sessiond before the init functions are completed).
1656 */
1657 init_usterr();
1658 init_tracepoint();
1659 lttng_ust_init_fd_tracker();
1660 lttng_ust_clock_init();
1661 lttng_ust_getcpu_init();
1662 lttng_ust_statedump_init();
1663 rseq_init();
1664 lttng_ring_buffer_metadata_client_init();
1665 lttng_ring_buffer_client_overwrite_init();
1666 lttng_ring_buffer_client_overwrite_rt_init();
1667 lttng_ring_buffer_client_discard_init();
1668 lttng_ring_buffer_client_discard_rt_init();
1669 lttng_perf_counter_init();
1670 /*
1671 * Invoke ust malloc wrapper init before starting other threads.
1672 */
1673 lttng_ust_malloc_wrapper_init();
1674
1675 timeout_mode = get_constructor_timeout(&constructor_timeout);
1676
1677 ret = sem_init(&constructor_wait, 0, 0);
1678 if (ret) {
1679 PERROR("sem_init");
1680 }
1681
1682 ret = setup_local_apps();
1683 if (ret) {
1684 DBG("local apps setup returned %d", ret);
1685 }
1686
1687 /* A new thread created by pthread_create inherits the signal mask
1688 * from the parent. To avoid any signal being received by the
1689 * listener thread, we block all signals temporarily in the parent,
1690 * while we create the listener thread.
1691 */
1692 sigfillset(&sig_all_blocked);
1693 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1694 if (ret) {
1695 ERR("pthread_sigmask: %s", strerror(ret));
1696 }
1697
1698 ret = pthread_attr_init(&thread_attr);
1699 if (ret) {
1700 ERR("pthread_attr_init: %s", strerror(ret));
1701 }
1702 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1703 if (ret) {
1704 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1705 }
1706
1707 pthread_mutex_lock(&ust_exit_mutex);
1708 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1709 ust_listener_thread, &global_apps);
1710 if (ret) {
1711 ERR("pthread_create global: %s", strerror(ret));
1712 }
1713 global_apps.thread_active = 1;
1714 pthread_mutex_unlock(&ust_exit_mutex);
1715
1716 if (local_apps.allowed) {
1717 pthread_mutex_lock(&ust_exit_mutex);
1718 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
1719 ust_listener_thread, &local_apps);
1720 if (ret) {
1721 ERR("pthread_create local: %s", strerror(ret));
1722 }
1723 local_apps.thread_active = 1;
1724 pthread_mutex_unlock(&ust_exit_mutex);
1725 } else {
1726 handle_register_done(&local_apps);
1727 }
1728 ret = pthread_attr_destroy(&thread_attr);
1729 if (ret) {
1730 ERR("pthread_attr_destroy: %s", strerror(ret));
1731 }
1732
1733 /* Restore original signal mask in parent */
1734 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1735 if (ret) {
1736 ERR("pthread_sigmask: %s", strerror(ret));
1737 }
1738
1739 switch (timeout_mode) {
1740 case 1: /* timeout wait */
1741 do {
1742 ret = sem_timedwait(&constructor_wait,
1743 &constructor_timeout);
1744 } while (ret < 0 && errno == EINTR);
1745 if (ret < 0) {
1746 switch (errno) {
1747 case ETIMEDOUT:
1748 ERR("Timed out waiting for lttng-sessiond");
1749 break;
1750 case EINVAL:
1751 PERROR("sem_timedwait");
1752 break;
1753 default:
1754 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1755 strerror(errno));
1756 }
1757 }
1758 break;
1759 case -1:/* wait forever */
1760 do {
1761 ret = sem_wait(&constructor_wait);
1762 } while (ret < 0 && errno == EINTR);
1763 if (ret < 0) {
1764 switch (errno) {
1765 case EINVAL:
1766 PERROR("sem_wait");
1767 break;
1768 default:
1769 ERR("Unexpected error \"%s\" returned by sem_wait",
1770 strerror(errno));
1771 }
1772 }
1773 break;
1774 case 0: /* no timeout */
1775 break;
1776 }
1777 }
1778
1779 static
1780 void lttng_ust_cleanup(int exiting)
1781 {
1782 cleanup_sock_info(&global_apps, exiting);
1783 cleanup_sock_info(&local_apps, exiting);
1784 local_apps.allowed = 0;
1785 /*
1786 * The teardown in this function all affect data structures
1787 * accessed under the UST lock by the listener thread. This
1788 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1789 * that none of these threads are accessing this data at this
1790 * point.
1791 */
1792 lttng_ust_abi_exit();
1793 lttng_ust_events_exit();
1794 lttng_perf_counter_exit();
1795 lttng_ring_buffer_client_discard_rt_exit();
1796 lttng_ring_buffer_client_discard_exit();
1797 lttng_ring_buffer_client_overwrite_rt_exit();
1798 lttng_ring_buffer_client_overwrite_exit();
1799 lttng_ring_buffer_metadata_client_exit();
1800 rseq_destroy();
1801 lttng_ust_statedump_destroy();
1802 exit_tracepoint();
1803 if (!exiting) {
1804 /* Reinitialize values for fork */
1805 sem_count = 2;
1806 lttng_ust_comm_should_quit = 0;
1807 initialized = 0;
1808 }
1809 }
1810
1811 void __attribute__((destructor)) lttng_ust_exit(void)
1812 {
1813 int ret;
1814
1815 /*
1816 * Using pthread_cancel here because:
1817 * A) we don't want to hang application teardown.
1818 * B) the thread is not allocating any resource.
1819 */
1820
1821 /*
1822 * Require the communication thread to quit. Synchronize with
1823 * mutexes to ensure it is not in a mutex critical section when
1824 * pthread_cancel is later called.
1825 */
1826 ust_lock_nocheck();
1827 lttng_ust_comm_should_quit = 1;
1828 ust_unlock();
1829
1830 pthread_mutex_lock(&ust_exit_mutex);
1831 /* cancel threads */
1832 if (global_apps.thread_active) {
1833 ret = pthread_cancel(global_apps.ust_listener);
1834 if (ret) {
1835 ERR("Error cancelling global ust listener thread: %s",
1836 strerror(ret));
1837 } else {
1838 global_apps.thread_active = 0;
1839 }
1840 }
1841 if (local_apps.thread_active) {
1842 ret = pthread_cancel(local_apps.ust_listener);
1843 if (ret) {
1844 ERR("Error cancelling local ust listener thread: %s",
1845 strerror(ret));
1846 } else {
1847 local_apps.thread_active = 0;
1848 }
1849 }
1850 pthread_mutex_unlock(&ust_exit_mutex);
1851
1852 /*
1853 * Do NOT join threads: use of sys_futex makes it impossible to
1854 * join the threads without using async-cancel, but async-cancel
1855 * is delivered by a signal, which could hit the target thread
1856 * anywhere in its code path, including while the ust_lock() is
1857 * held, causing a deadlock for the other thread. Let the OS
1858 * cleanup the threads if there are stalled in a syscall.
1859 */
1860 lttng_ust_cleanup(1);
1861 }
1862
1863 /*
1864 * We exclude the worker threads across fork and clone (except
1865 * CLONE_VM), because these system calls only keep the forking thread
1866 * running in the child. Therefore, we don't want to call fork or clone
1867 * in the middle of an tracepoint or ust tracing state modification.
1868 * Holding this mutex protects these structures across fork and clone.
1869 */
1870 void ust_before_fork(sigset_t *save_sigset)
1871 {
1872 /*
1873 * Disable signals. This is to avoid that the child intervenes
1874 * before it is properly setup for tracing. It is safer to
1875 * disable all signals, because then we know we are not breaking
1876 * anything by restoring the original mask.
1877 */
1878 sigset_t all_sigs;
1879 int ret;
1880
1881 /* Fixup lttng-ust TLS. */
1882 lttng_ust_fixup_tls();
1883
1884 if (URCU_TLS(lttng_ust_nest_count))
1885 return;
1886 /* Disable signals */
1887 sigfillset(&all_sigs);
1888 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
1889 if (ret == -1) {
1890 PERROR("sigprocmask");
1891 }
1892
1893 pthread_mutex_lock(&ust_fork_mutex);
1894
1895 ust_lock_nocheck();
1896 rcu_bp_before_fork();
1897 }
1898
1899 static void ust_after_fork_common(sigset_t *restore_sigset)
1900 {
1901 int ret;
1902
1903 DBG("process %d", getpid());
1904 ust_unlock();
1905
1906 pthread_mutex_unlock(&ust_fork_mutex);
1907
1908 /* Restore signals */
1909 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
1910 if (ret == -1) {
1911 PERROR("sigprocmask");
1912 }
1913 }
1914
1915 void ust_after_fork_parent(sigset_t *restore_sigset)
1916 {
1917 if (URCU_TLS(lttng_ust_nest_count))
1918 return;
1919 DBG("process %d", getpid());
1920 rcu_bp_after_fork_parent();
1921 /* Release mutexes and reenable signals */
1922 ust_after_fork_common(restore_sigset);
1923 }
1924
1925 /*
1926 * After fork, in the child, we need to cleanup all the leftover state,
1927 * except the worker thread which already magically disappeared thanks
1928 * to the weird Linux fork semantics. After tyding up, we call
1929 * lttng_ust_init() again to start over as a new PID.
1930 *
1931 * This is meant for forks() that have tracing in the child between the
1932 * fork and following exec call (if there is any).
1933 */
1934 void ust_after_fork_child(sigset_t *restore_sigset)
1935 {
1936 if (URCU_TLS(lttng_ust_nest_count))
1937 return;
1938 lttng_context_vtid_reset();
1939 DBG("process %d", getpid());
1940 /* Release urcu mutexes */
1941 rcu_bp_after_fork_child();
1942 lttng_ust_cleanup(0);
1943 /* Release mutexes and reenable signals */
1944 ust_after_fork_common(restore_sigset);
1945 lttng_ust_init();
1946 }
1947
1948 void lttng_ust_sockinfo_session_enabled(void *owner)
1949 {
1950 struct sock_info *sock_info = owner;
1951 sock_info->statedump_pending = 1;
1952 }
This page took 0.071368 seconds and 5 git commands to generate.