Hide new 'lttng_counter_client_percpu_*' private symbols
[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 #include <stddef.h>
24 #include <stdint.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/mman.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <dlfcn.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <errno.h>
35 #include <pthread.h>
36 #include <semaphore.h>
37 #include <time.h>
38 #include <assert.h>
39 #include <signal.h>
40 #include <limits.h>
41 #include <urcu/uatomic.h>
42 #include "futex.h"
43 #include <urcu/compiler.h>
44 #include <lttng/urcu/urcu-ust.h>
45
46 #include <lttng/align.h>
47 #include <lttng/ust-events.h>
48 #include <lttng/ust-abi.h>
49 #include <lttng/ust.h>
50 #include <lttng/ust-error.h>
51 #include <lttng/ust-ctl.h>
52 #include <urcu/tls-compat.h>
53 #include <ust-comm.h>
54 #include <ust-fd.h>
55 #include <usterr-signal-safe.h>
56 #include <helper.h>
57 #include "tracepoint-internal.h"
58 #include "lttng-tracer-core.h"
59 #include "compat.h"
60 #include "../libringbuffer/rb-init.h"
61 #include "lttng-ust-statedump.h"
62 #include "clock.h"
63 #include "../libringbuffer/getcpu.h"
64 #include "getenv.h"
65 #include "ust-events-internal.h"
66
67 /* Concatenate lttng ust shared library name with its major version number. */
68 #define LTTNG_UST_LIB_SO_NAME "liblttng-ust.so." __ust_stringify(CONFIG_LTTNG_UST_LIBRARY_VERSION_MAJOR)
69
70 /*
71 * Has lttng ust comm constructor been called ?
72 */
73 static int initialized;
74
75 /*
76 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
77 * Held when handling a command, also held by fork() to deal with
78 * removal of threads, and by exit path.
79 *
80 * The UST lock is the centralized mutex across UST tracing control and
81 * probe registration.
82 *
83 * ust_exit_mutex must never nest in ust_mutex.
84 *
85 * ust_fork_mutex must never nest in ust_mutex.
86 *
87 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
88 * counter lazy initialization called by events within the statedump,
89 * which traces while the ust_mutex is held.
90 *
91 * ust_lock nests within the dynamic loader lock (within glibc) because
92 * it is taken within the library constructor.
93 *
94 * The ust fd tracker lock nests within the ust_mutex.
95 */
96 static pthread_mutex_t ust_mutex = PTHREAD_MUTEX_INITIALIZER;
97
98 /* Allow nesting the ust_mutex within the same thread. */
99 static DEFINE_URCU_TLS(int, ust_mutex_nest);
100
101 /*
102 * ust_exit_mutex protects thread_active variable wrt thread exit. It
103 * cannot be done by ust_mutex because pthread_cancel(), which takes an
104 * internal libc lock, cannot nest within ust_mutex.
105 *
106 * It never nests within a ust_mutex.
107 */
108 static pthread_mutex_t ust_exit_mutex = PTHREAD_MUTEX_INITIALIZER;
109
110 /*
111 * ust_fork_mutex protects base address statedump tracing against forks. It
112 * prevents the dynamic loader lock to be taken (by base address statedump
113 * tracing) while a fork is happening, thus preventing deadlock issues with
114 * the dynamic loader lock.
115 */
116 static pthread_mutex_t ust_fork_mutex = PTHREAD_MUTEX_INITIALIZER;
117
118 /* Should the ust comm thread quit ? */
119 static int lttng_ust_comm_should_quit;
120
121 /*
122 * This variable can be tested by applications to check whether
123 * lttng-ust is loaded. They simply have to define their own
124 * "lttng_ust_loaded" weak symbol, and test it. It is set to 1 by the
125 * library constructor.
126 */
127 int lttng_ust_loaded __attribute__((weak));
128
129 /*
130 * Return 0 on success, -1 if should quit.
131 * The lock is taken in both cases.
132 * Signal-safe.
133 */
134 int ust_lock(void)
135 {
136 sigset_t sig_all_blocked, orig_mask;
137 int ret, oldstate;
138
139 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
140 if (ret) {
141 ERR("pthread_setcancelstate: %s", strerror(ret));
142 }
143 if (oldstate != PTHREAD_CANCEL_ENABLE) {
144 ERR("pthread_setcancelstate: unexpected oldstate");
145 }
146 sigfillset(&sig_all_blocked);
147 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
148 if (ret) {
149 ERR("pthread_sigmask: %s", strerror(ret));
150 }
151 if (!URCU_TLS(ust_mutex_nest)++)
152 pthread_mutex_lock(&ust_mutex);
153 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
154 if (ret) {
155 ERR("pthread_sigmask: %s", strerror(ret));
156 }
157 if (lttng_ust_comm_should_quit) {
158 return -1;
159 } else {
160 return 0;
161 }
162 }
163
164 /*
165 * ust_lock_nocheck() can be used in constructors/destructors, because
166 * they are already nested within the dynamic loader lock, and therefore
167 * have exclusive access against execution of liblttng-ust destructor.
168 * Signal-safe.
169 */
170 void ust_lock_nocheck(void)
171 {
172 sigset_t sig_all_blocked, orig_mask;
173 int ret, oldstate;
174
175 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
176 if (ret) {
177 ERR("pthread_setcancelstate: %s", strerror(ret));
178 }
179 if (oldstate != PTHREAD_CANCEL_ENABLE) {
180 ERR("pthread_setcancelstate: unexpected oldstate");
181 }
182 sigfillset(&sig_all_blocked);
183 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
184 if (ret) {
185 ERR("pthread_sigmask: %s", strerror(ret));
186 }
187 if (!URCU_TLS(ust_mutex_nest)++)
188 pthread_mutex_lock(&ust_mutex);
189 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
190 if (ret) {
191 ERR("pthread_sigmask: %s", strerror(ret));
192 }
193 }
194
195 /*
196 * Signal-safe.
197 */
198 void ust_unlock(void)
199 {
200 sigset_t sig_all_blocked, orig_mask;
201 int ret, oldstate;
202
203 sigfillset(&sig_all_blocked);
204 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
205 if (ret) {
206 ERR("pthread_sigmask: %s", strerror(ret));
207 }
208 if (!--URCU_TLS(ust_mutex_nest))
209 pthread_mutex_unlock(&ust_mutex);
210 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
211 if (ret) {
212 ERR("pthread_sigmask: %s", strerror(ret));
213 }
214 ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
215 if (ret) {
216 ERR("pthread_setcancelstate: %s", strerror(ret));
217 }
218 if (oldstate != PTHREAD_CANCEL_DISABLE) {
219 ERR("pthread_setcancelstate: unexpected oldstate");
220 }
221 }
222
223 /*
224 * Wait for either of these before continuing to the main
225 * program:
226 * - the register_done message from sessiond daemon
227 * (will let the sessiond daemon enable sessions before main
228 * starts.)
229 * - sessiond daemon is not reachable.
230 * - timeout (ensuring applications are resilient to session
231 * daemon problems).
232 */
233 static sem_t constructor_wait;
234 /*
235 * Doing this for both the global and local sessiond.
236 */
237 enum {
238 sem_count_initial_value = 4,
239 };
240
241 static int sem_count = sem_count_initial_value;
242
243 /*
244 * Counting nesting within lttng-ust. Used to ensure that calling fork()
245 * from liblttng-ust does not execute the pre/post fork handlers.
246 */
247 static DEFINE_URCU_TLS(int, lttng_ust_nest_count);
248
249 /*
250 * Info about socket and associated listener thread.
251 */
252 struct sock_info {
253 const char *name;
254 pthread_t ust_listener; /* listener thread */
255 int root_handle;
256 int registration_done;
257 int allowed;
258 int global;
259 int thread_active;
260
261 char sock_path[PATH_MAX];
262 int socket;
263 int notify_socket;
264
265 char wait_shm_path[PATH_MAX];
266 char *wait_shm_mmap;
267 /* Keep track of lazy state dump not performed yet. */
268 int statedump_pending;
269 int initial_statedump_done;
270 /* Keep procname for statedump */
271 char procname[LTTNG_UST_ABI_PROCNAME_LEN];
272 };
273
274 /* Socket from app (connect) to session daemon (listen) for communication */
275 struct sock_info global_apps = {
276 .name = "global",
277 .global = 1,
278
279 .root_handle = -1,
280 .registration_done = 0,
281 .allowed = 0,
282 .thread_active = 0,
283
284 .sock_path = LTTNG_DEFAULT_RUNDIR "/" LTTNG_UST_SOCK_FILENAME,
285 .socket = -1,
286 .notify_socket = -1,
287
288 .wait_shm_path = "/" LTTNG_UST_WAIT_FILENAME,
289
290 .statedump_pending = 0,
291 .initial_statedump_done = 0,
292 .procname[0] = '\0'
293 };
294
295 /* TODO: allow global_apps_sock_path override */
296
297 struct sock_info local_apps = {
298 .name = "local",
299 .global = 0,
300 .root_handle = -1,
301 .registration_done = 0,
302 .allowed = 0, /* Check setuid bit first */
303 .thread_active = 0,
304
305 .socket = -1,
306 .notify_socket = -1,
307
308 .statedump_pending = 0,
309 .initial_statedump_done = 0,
310 .procname[0] = '\0'
311 };
312
313 static int wait_poll_fallback;
314
315 static const char *cmd_name_mapping[] = {
316 [ LTTNG_UST_RELEASE ] = "Release",
317 [ LTTNG_UST_SESSION ] = "Create Session",
318 [ LTTNG_UST_TRACER_VERSION ] = "Get Tracer Version",
319
320 [ LTTNG_UST_TRACEPOINT_LIST ] = "Create Tracepoint List",
321 [ LTTNG_UST_WAIT_QUIESCENT ] = "Wait for Quiescent State",
322 [ LTTNG_UST_REGISTER_DONE ] = "Registration Done",
323 [ LTTNG_UST_TRACEPOINT_FIELD_LIST ] = "Create Tracepoint Field List",
324
325 [ LTTNG_UST_EVENT_NOTIFIER_GROUP_CREATE ] = "Create event notifier group",
326
327 /* Session FD commands */
328 [ LTTNG_UST_CHANNEL ] = "Create Channel",
329 [ LTTNG_UST_SESSION_START ] = "Start Session",
330 [ LTTNG_UST_SESSION_STOP ] = "Stop Session",
331
332 /* Channel FD commands */
333 [ LTTNG_UST_STREAM ] = "Create Stream",
334 [ LTTNG_UST_EVENT ] = "Create Event",
335
336 /* Event and Channel FD commands */
337 [ LTTNG_UST_CONTEXT ] = "Create Context",
338 [ LTTNG_UST_FLUSH_BUFFER ] = "Flush Buffer",
339
340 /* Event, Channel and Session commands */
341 [ LTTNG_UST_ENABLE ] = "Enable",
342 [ LTTNG_UST_DISABLE ] = "Disable",
343
344 /* Tracepoint list commands */
345 [ LTTNG_UST_TRACEPOINT_LIST_GET ] = "List Next Tracepoint",
346 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET ] = "List Next Tracepoint Field",
347
348 /* Event FD commands */
349 [ LTTNG_UST_FILTER ] = "Create Filter",
350 [ LTTNG_UST_EXCLUSION ] = "Add exclusions to event",
351
352 /* Event notifier group commands */
353 [ LTTNG_UST_EVENT_NOTIFIER_CREATE ] = "Create event notifier",
354
355 /* Session and event notifier group commands */
356 [ LTTNG_UST_COUNTER ] = "Create Counter",
357
358 /* Counter commands */
359 [ LTTNG_UST_COUNTER_GLOBAL ] = "Create Counter Global",
360 [ LTTNG_UST_COUNTER_CPU ] = "Create Counter CPU",
361 };
362
363 static const char *str_timeout;
364 static int got_timeout_env;
365
366 extern void lttng_ring_buffer_client_overwrite_init(void);
367 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
368 extern void lttng_ring_buffer_client_discard_init(void);
369 extern void lttng_ring_buffer_client_discard_rt_init(void);
370 extern void lttng_ring_buffer_metadata_client_init(void);
371 extern void lttng_ring_buffer_client_overwrite_exit(void);
372 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
373 extern void lttng_ring_buffer_client_discard_exit(void);
374 extern void lttng_ring_buffer_client_discard_rt_exit(void);
375 extern void lttng_ring_buffer_metadata_client_exit(void);
376 LTTNG_HIDDEN
377 extern void lttng_counter_client_percpu_32_modular_init(void);
378 LTTNG_HIDDEN
379 extern void lttng_counter_client_percpu_32_modular_exit(void);
380 LTTNG_HIDDEN
381 extern void lttng_counter_client_percpu_64_modular_init(void);
382 LTTNG_HIDDEN
383 extern void lttng_counter_client_percpu_64_modular_exit(void);
384
385 static char *get_map_shm(struct sock_info *sock_info);
386
387 ssize_t lttng_ust_read(int fd, void *buf, size_t len)
388 {
389 ssize_t ret;
390 size_t copied = 0, to_copy = len;
391
392 do {
393 ret = read(fd, buf + copied, to_copy);
394 if (ret > 0) {
395 copied += ret;
396 to_copy -= ret;
397 }
398 } while ((ret > 0 && to_copy > 0)
399 || (ret < 0 && errno == EINTR));
400 if (ret > 0) {
401 ret = copied;
402 }
403 return ret;
404 }
405 /*
406 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
407 * pointer.
408 */
409 static
410 const char *get_lttng_home_dir(void)
411 {
412 const char *val;
413
414 val = (const char *) lttng_getenv("LTTNG_HOME");
415 if (val != NULL) {
416 return val;
417 }
418 return (const char *) lttng_getenv("HOME");
419 }
420
421 /*
422 * Force a read (imply TLS fixup for dlopen) of TLS variables.
423 */
424 static
425 void lttng_fixup_nest_count_tls(void)
426 {
427 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count)));
428 }
429
430 static
431 void lttng_fixup_ust_mutex_nest_tls(void)
432 {
433 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest)));
434 }
435
436 /*
437 * Fixup lttng-ust urcu TLS.
438 */
439 static
440 void lttng_fixup_lttng_ust_urcu_tls(void)
441 {
442 (void) lttng_ust_urcu_read_ongoing();
443 }
444
445 void lttng_ust_fixup_tls(void)
446 {
447 lttng_fixup_lttng_ust_urcu_tls();
448 lttng_fixup_ringbuffer_tls();
449 lttng_fixup_vtid_tls();
450 lttng_fixup_nest_count_tls();
451 lttng_fixup_procname_tls();
452 lttng_fixup_ust_mutex_nest_tls();
453 lttng_ust_fixup_perf_counter_tls();
454 lttng_ust_fixup_fd_tracker_tls();
455 lttng_fixup_cgroup_ns_tls();
456 lttng_fixup_ipc_ns_tls();
457 lttng_fixup_net_ns_tls();
458 lttng_fixup_time_ns_tls();
459 lttng_fixup_uts_ns_tls();
460 }
461
462 int lttng_get_notify_socket(void *owner)
463 {
464 struct sock_info *info = owner;
465
466 return info->notify_socket;
467 }
468
469
470 LTTNG_HIDDEN
471 char* lttng_ust_sockinfo_get_procname(void *owner)
472 {
473 struct sock_info *info = owner;
474
475 return info->procname;
476 }
477
478 static
479 void print_cmd(int cmd, int handle)
480 {
481 const char *cmd_name = "Unknown";
482
483 if (cmd >= 0 && cmd < LTTNG_ARRAY_SIZE(cmd_name_mapping)
484 && cmd_name_mapping[cmd]) {
485 cmd_name = cmd_name_mapping[cmd];
486 }
487 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
488 cmd_name, cmd,
489 lttng_ust_obj_get_name(handle), handle);
490 }
491
492 static
493 int setup_global_apps(void)
494 {
495 int ret = 0;
496 assert(!global_apps.wait_shm_mmap);
497
498 global_apps.wait_shm_mmap = get_map_shm(&global_apps);
499 if (!global_apps.wait_shm_mmap) {
500 WARN("Unable to get map shm for global apps. Disabling LTTng-UST global tracing.");
501 global_apps.allowed = 0;
502 ret = -EIO;
503 goto error;
504 }
505
506 global_apps.allowed = 1;
507 lttng_pthread_getname_np(global_apps.procname, LTTNG_UST_ABI_PROCNAME_LEN);
508 error:
509 return ret;
510 }
511 static
512 int setup_local_apps(void)
513 {
514 int ret = 0;
515 const char *home_dir;
516 uid_t uid;
517
518 assert(!local_apps.wait_shm_mmap);
519
520 uid = getuid();
521 /*
522 * Disallow per-user tracing for setuid binaries.
523 */
524 if (uid != geteuid()) {
525 assert(local_apps.allowed == 0);
526 ret = 0;
527 goto end;
528 }
529 home_dir = get_lttng_home_dir();
530 if (!home_dir) {
531 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
532 assert(local_apps.allowed == 0);
533 ret = -ENOENT;
534 goto end;
535 }
536 local_apps.allowed = 1;
537 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
538 home_dir,
539 LTTNG_DEFAULT_HOME_RUNDIR,
540 LTTNG_UST_SOCK_FILENAME);
541 snprintf(local_apps.wait_shm_path, PATH_MAX, "/%s-%u",
542 LTTNG_UST_WAIT_FILENAME,
543 uid);
544
545 local_apps.wait_shm_mmap = get_map_shm(&local_apps);
546 if (!local_apps.wait_shm_mmap) {
547 WARN("Unable to get map shm for local apps. Disabling LTTng-UST per-user tracing.");
548 local_apps.allowed = 0;
549 ret = -EIO;
550 goto end;
551 }
552
553 lttng_pthread_getname_np(local_apps.procname, LTTNG_UST_ABI_PROCNAME_LEN);
554 end:
555 return ret;
556 }
557
558 /*
559 * Get socket timeout, in ms.
560 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
561 */
562 static
563 long get_timeout(void)
564 {
565 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
566
567 if (!got_timeout_env) {
568 str_timeout = lttng_getenv("LTTNG_UST_REGISTER_TIMEOUT");
569 got_timeout_env = 1;
570 }
571 if (str_timeout)
572 constructor_delay_ms = strtol(str_timeout, NULL, 10);
573 /* All negative values are considered as "-1". */
574 if (constructor_delay_ms < -1)
575 constructor_delay_ms = -1;
576 return constructor_delay_ms;
577 }
578
579 /* Timeout for notify socket send and recv. */
580 static
581 long get_notify_sock_timeout(void)
582 {
583 return get_timeout();
584 }
585
586 /* Timeout for connecting to cmd and notify sockets. */
587 static
588 long get_connect_sock_timeout(void)
589 {
590 return get_timeout();
591 }
592
593 /*
594 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
595 */
596 static
597 int get_constructor_timeout(struct timespec *constructor_timeout)
598 {
599 long constructor_delay_ms;
600 int ret;
601
602 constructor_delay_ms = get_timeout();
603
604 switch (constructor_delay_ms) {
605 case -1:/* fall-through */
606 case 0:
607 return constructor_delay_ms;
608 default:
609 break;
610 }
611
612 /*
613 * If we are unable to find the current time, don't wait.
614 */
615 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
616 if (ret) {
617 /* Don't wait. */
618 return 0;
619 }
620 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
621 constructor_timeout->tv_nsec +=
622 (constructor_delay_ms % 1000UL) * 1000000UL;
623 if (constructor_timeout->tv_nsec >= 1000000000UL) {
624 constructor_timeout->tv_sec++;
625 constructor_timeout->tv_nsec -= 1000000000UL;
626 }
627 /* Timeout wait (constructor_delay_ms). */
628 return 1;
629 }
630
631 static
632 void get_allow_blocking(void)
633 {
634 const char *str_allow_blocking =
635 lttng_getenv("LTTNG_UST_ALLOW_BLOCKING");
636
637 if (str_allow_blocking) {
638 DBG("%s environment variable is set",
639 "LTTNG_UST_ALLOW_BLOCKING");
640 lttng_ust_ringbuffer_set_allow_blocking();
641 }
642 }
643
644 static
645 int register_to_sessiond(int socket, enum ustctl_socket_type type)
646 {
647 return ustcomm_send_reg_msg(socket,
648 type,
649 CAA_BITS_PER_LONG,
650 lttng_alignof(uint8_t) * CHAR_BIT,
651 lttng_alignof(uint16_t) * CHAR_BIT,
652 lttng_alignof(uint32_t) * CHAR_BIT,
653 lttng_alignof(uint64_t) * CHAR_BIT,
654 lttng_alignof(unsigned long) * CHAR_BIT);
655 }
656
657 static
658 int send_reply(int sock, struct ustcomm_ust_reply *lur)
659 {
660 ssize_t len;
661
662 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
663 switch (len) {
664 case sizeof(*lur):
665 DBG("message successfully sent");
666 return 0;
667 default:
668 if (len == -ECONNRESET) {
669 DBG("remote end closed connection");
670 return 0;
671 }
672 if (len < 0)
673 return len;
674 DBG("incorrect message size: %zd", len);
675 return -EINVAL;
676 }
677 }
678
679 static
680 void decrement_sem_count(unsigned int count)
681 {
682 int ret;
683
684 assert(uatomic_read(&sem_count) >= count);
685
686 if (uatomic_read(&sem_count) <= 0) {
687 return;
688 }
689
690 ret = uatomic_add_return(&sem_count, -count);
691 if (ret == 0) {
692 ret = sem_post(&constructor_wait);
693 assert(!ret);
694 }
695 }
696
697 static
698 int handle_register_done(struct sock_info *sock_info)
699 {
700 if (sock_info->registration_done)
701 return 0;
702 sock_info->registration_done = 1;
703
704 decrement_sem_count(1);
705 if (!sock_info->statedump_pending) {
706 sock_info->initial_statedump_done = 1;
707 decrement_sem_count(1);
708 }
709
710 return 0;
711 }
712
713 static
714 int handle_register_failed(struct sock_info *sock_info)
715 {
716 if (sock_info->registration_done)
717 return 0;
718 sock_info->registration_done = 1;
719 sock_info->initial_statedump_done = 1;
720
721 decrement_sem_count(2);
722
723 return 0;
724 }
725
726 /*
727 * Only execute pending statedump after the constructor semaphore has
728 * been posted by the current listener thread. This means statedump will
729 * only be performed after the "registration done" command is received
730 * from this thread's session daemon.
731 *
732 * This ensures we don't run into deadlock issues with the dynamic
733 * loader mutex, which is held while the constructor is called and
734 * waiting on the constructor semaphore. All operations requiring this
735 * dynamic loader lock need to be postponed using this mechanism.
736 *
737 * In a scenario with two session daemons connected to the application,
738 * it is possible that the first listener thread which receives the
739 * registration done command issues its statedump while the dynamic
740 * loader lock is still held by the application constructor waiting on
741 * the semaphore. It will however be allowed to proceed when the
742 * second session daemon sends the registration done command to the
743 * second listener thread. This situation therefore does not produce
744 * a deadlock.
745 */
746 static
747 void handle_pending_statedump(struct sock_info *sock_info)
748 {
749 if (sock_info->registration_done && sock_info->statedump_pending) {
750 sock_info->statedump_pending = 0;
751 pthread_mutex_lock(&ust_fork_mutex);
752 lttng_handle_pending_statedump(sock_info);
753 pthread_mutex_unlock(&ust_fork_mutex);
754
755 if (!sock_info->initial_statedump_done) {
756 sock_info->initial_statedump_done = 1;
757 decrement_sem_count(1);
758 }
759 }
760 }
761
762 static inline
763 const char *bytecode_type_str(uint32_t cmd)
764 {
765 switch (cmd) {
766 case LTTNG_UST_CAPTURE:
767 return "capture";
768 case LTTNG_UST_FILTER:
769 return "filter";
770 default:
771 abort();
772 }
773 }
774
775 static
776 int handle_bytecode_recv(struct sock_info *sock_info,
777 int sock, struct ustcomm_ust_msg *lum)
778 {
779 struct lttng_ust_bytecode_node *bytecode = NULL;
780 enum lttng_ust_bytecode_node_type type;
781 const struct lttng_ust_objd_ops *ops;
782 uint32_t data_size, data_size_max, reloc_offset;
783 uint64_t seqnum;
784 ssize_t len;
785 int ret = 0;
786
787 switch (lum->cmd) {
788 case LTTNG_UST_FILTER:
789 type = LTTNG_UST_BYTECODE_NODE_TYPE_FILTER;
790 data_size = lum->u.filter.data_size;
791 data_size_max = FILTER_BYTECODE_MAX_LEN;
792 reloc_offset = lum->u.filter.reloc_offset;
793 seqnum = lum->u.filter.seqnum;
794 break;
795 case LTTNG_UST_CAPTURE:
796 type = LTTNG_UST_BYTECODE_NODE_TYPE_CAPTURE;
797 data_size = lum->u.capture.data_size;
798 data_size_max = CAPTURE_BYTECODE_MAX_LEN;
799 reloc_offset = lum->u.capture.reloc_offset;
800 seqnum = lum->u.capture.seqnum;
801 break;
802 default:
803 abort();
804 }
805
806 if (data_size > data_size_max) {
807 ERR("Bytecode %s data size is too large: %u bytes",
808 bytecode_type_str(lum->cmd), data_size);
809 ret = -EINVAL;
810 goto end;
811 }
812
813 if (reloc_offset > data_size) {
814 ERR("Bytecode %s reloc offset %u is not within data",
815 bytecode_type_str(lum->cmd), reloc_offset);
816 ret = -EINVAL;
817 goto end;
818 }
819
820 /* Allocate the structure AND the `data[]` field. */
821 bytecode = zmalloc(sizeof(*bytecode) + data_size);
822 if (!bytecode) {
823 ret = -ENOMEM;
824 goto end;
825 }
826
827 bytecode->bc.len = data_size;
828 bytecode->bc.reloc_offset = reloc_offset;
829 bytecode->bc.seqnum = seqnum;
830 bytecode->type = type;
831
832 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data, bytecode->bc.len);
833 switch (len) {
834 case 0: /* orderly shutdown */
835 ret = 0;
836 goto end;
837 default:
838 if (len == bytecode->bc.len) {
839 DBG("Bytecode %s data received",
840 bytecode_type_str(lum->cmd));
841 break;
842 } else if (len < 0) {
843 DBG("Receive failed from lttng-sessiond with errno %d",
844 (int) -len);
845 if (len == -ECONNRESET) {
846 ERR("%s remote end closed connection",
847 sock_info->name);
848 ret = len;
849 goto end;
850 }
851 ret = len;
852 goto end;
853 } else {
854 DBG("Incorrect %s bytecode data message size: %zd",
855 bytecode_type_str(lum->cmd), len);
856 ret = -EINVAL;
857 goto end;
858 }
859 }
860
861 ops = objd_ops(lum->handle);
862 if (!ops) {
863 ret = -ENOENT;
864 goto end;
865 }
866
867 if (ops->cmd)
868 ret = ops->cmd(lum->handle, lum->cmd,
869 (unsigned long) &bytecode,
870 NULL, sock_info);
871 else
872 ret = -ENOSYS;
873
874 end:
875 free(bytecode);
876 return ret;
877 }
878
879 static
880 int handle_message(struct sock_info *sock_info,
881 int sock, struct ustcomm_ust_msg *lum)
882 {
883 int ret = 0;
884 const struct lttng_ust_objd_ops *ops;
885 struct ustcomm_ust_reply lur;
886 union ust_args args;
887 char ctxstr[LTTNG_UST_SYM_NAME_LEN]; /* App context string. */
888 ssize_t len;
889
890 memset(&lur, 0, sizeof(lur));
891
892 if (ust_lock()) {
893 ret = -LTTNG_UST_ERR_EXITING;
894 goto error;
895 }
896
897 ops = objd_ops(lum->handle);
898 if (!ops) {
899 ret = -ENOENT;
900 goto error;
901 }
902
903 switch (lum->cmd) {
904 case LTTNG_UST_REGISTER_DONE:
905 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
906 ret = handle_register_done(sock_info);
907 else
908 ret = -EINVAL;
909 break;
910 case LTTNG_UST_RELEASE:
911 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
912 ret = -EPERM;
913 else
914 ret = lttng_ust_objd_unref(lum->handle, 1);
915 break;
916 case LTTNG_UST_CAPTURE:
917 case LTTNG_UST_FILTER:
918 ret = handle_bytecode_recv(sock_info, sock, lum);
919 if (ret)
920 goto error;
921 break;
922 case LTTNG_UST_EXCLUSION:
923 {
924 /* Receive exclusion names */
925 struct lttng_ust_excluder_node *node;
926 unsigned int count;
927
928 count = lum->u.exclusion.count;
929 if (count == 0) {
930 /* There are no names to read */
931 ret = 0;
932 goto error;
933 }
934 node = zmalloc(sizeof(*node) +
935 count * LTTNG_UST_SYM_NAME_LEN);
936 if (!node) {
937 ret = -ENOMEM;
938 goto error;
939 }
940 node->excluder.count = count;
941 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
942 count * LTTNG_UST_SYM_NAME_LEN);
943 switch (len) {
944 case 0: /* orderly shutdown */
945 ret = 0;
946 free(node);
947 goto error;
948 default:
949 if (len == count * LTTNG_UST_SYM_NAME_LEN) {
950 DBG("Exclusion data received");
951 break;
952 } else if (len < 0) {
953 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
954 if (len == -ECONNRESET) {
955 ERR("%s remote end closed connection", sock_info->name);
956 ret = len;
957 free(node);
958 goto error;
959 }
960 ret = len;
961 free(node);
962 goto error;
963 } else {
964 DBG("Incorrect exclusion data message size: %zd", len);
965 ret = -EINVAL;
966 free(node);
967 goto error;
968 }
969 }
970 if (ops->cmd)
971 ret = ops->cmd(lum->handle, lum->cmd,
972 (unsigned long) &node,
973 &args, sock_info);
974 else
975 ret = -ENOSYS;
976 free(node);
977 break;
978 }
979 case LTTNG_UST_EVENT_NOTIFIER_GROUP_CREATE:
980 {
981 int event_notifier_notif_fd, close_ret;
982
983 len = ustcomm_recv_event_notifier_notif_fd_from_sessiond(sock,
984 &event_notifier_notif_fd);
985 switch (len) {
986 case 0: /* orderly shutdown */
987 ret = 0;
988 goto error;
989 case 1:
990 break;
991 default:
992 if (len < 0) {
993 DBG("Receive failed from lttng-sessiond with errno %d",
994 (int) -len);
995 if (len == -ECONNRESET) {
996 ERR("%s remote end closed connection",
997 sock_info->name);
998 ret = len;
999 goto error;
1000 }
1001 ret = len;
1002 goto error;
1003 } else {
1004 DBG("Incorrect event notifier fd message size: %zd",
1005 len);
1006 ret = -EINVAL;
1007 goto error;
1008 }
1009 }
1010 args.event_notifier_handle.event_notifier_notif_fd =
1011 event_notifier_notif_fd;
1012 if (ops->cmd)
1013 ret = ops->cmd(lum->handle, lum->cmd,
1014 (unsigned long) &lum->u,
1015 &args, sock_info);
1016 else
1017 ret = -ENOSYS;
1018 if (args.event_notifier_handle.event_notifier_notif_fd >= 0) {
1019 lttng_ust_lock_fd_tracker();
1020 close_ret = close(args.event_notifier_handle.event_notifier_notif_fd);
1021 lttng_ust_unlock_fd_tracker();
1022 if (close_ret)
1023 PERROR("close");
1024 }
1025 break;
1026 }
1027 case LTTNG_UST_CHANNEL:
1028 {
1029 void *chan_data;
1030 int wakeup_fd;
1031
1032 len = ustcomm_recv_channel_from_sessiond(sock,
1033 &chan_data, lum->u.channel.len,
1034 &wakeup_fd);
1035 switch (len) {
1036 case 0: /* orderly shutdown */
1037 ret = 0;
1038 goto error;
1039 default:
1040 if (len == lum->u.channel.len) {
1041 DBG("channel data received");
1042 break;
1043 } else if (len < 0) {
1044 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1045 if (len == -ECONNRESET) {
1046 ERR("%s remote end closed connection", sock_info->name);
1047 ret = len;
1048 goto error;
1049 }
1050 ret = len;
1051 goto error;
1052 } else {
1053 DBG("incorrect channel data message size: %zd", len);
1054 ret = -EINVAL;
1055 goto error;
1056 }
1057 }
1058 args.channel.chan_data = chan_data;
1059 args.channel.wakeup_fd = wakeup_fd;
1060 if (ops->cmd)
1061 ret = ops->cmd(lum->handle, lum->cmd,
1062 (unsigned long) &lum->u,
1063 &args, sock_info);
1064 else
1065 ret = -ENOSYS;
1066 if (args.channel.wakeup_fd >= 0) {
1067 int close_ret;
1068
1069 lttng_ust_lock_fd_tracker();
1070 close_ret = close(args.channel.wakeup_fd);
1071 lttng_ust_unlock_fd_tracker();
1072 args.channel.wakeup_fd = -1;
1073 if (close_ret)
1074 PERROR("close");
1075 }
1076 free(args.channel.chan_data);
1077 break;
1078 }
1079 case LTTNG_UST_STREAM:
1080 {
1081 int close_ret;
1082
1083 /* Receive shm_fd, wakeup_fd */
1084 ret = ustcomm_recv_stream_from_sessiond(sock,
1085 NULL,
1086 &args.stream.shm_fd,
1087 &args.stream.wakeup_fd);
1088 if (ret) {
1089 goto error;
1090 }
1091
1092 if (ops->cmd)
1093 ret = ops->cmd(lum->handle, lum->cmd,
1094 (unsigned long) &lum->u,
1095 &args, sock_info);
1096 else
1097 ret = -ENOSYS;
1098 if (args.stream.shm_fd >= 0) {
1099 lttng_ust_lock_fd_tracker();
1100 close_ret = close(args.stream.shm_fd);
1101 lttng_ust_unlock_fd_tracker();
1102 args.stream.shm_fd = -1;
1103 if (close_ret)
1104 PERROR("close");
1105 }
1106 if (args.stream.wakeup_fd >= 0) {
1107 lttng_ust_lock_fd_tracker();
1108 close_ret = close(args.stream.wakeup_fd);
1109 lttng_ust_unlock_fd_tracker();
1110 args.stream.wakeup_fd = -1;
1111 if (close_ret)
1112 PERROR("close");
1113 }
1114 break;
1115 }
1116 case LTTNG_UST_CONTEXT:
1117 switch (lum->u.context.ctx) {
1118 case LTTNG_UST_CONTEXT_APP_CONTEXT:
1119 {
1120 char *p;
1121 size_t ctxlen, recvlen;
1122
1123 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
1124 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
1125 if (ctxlen >= LTTNG_UST_SYM_NAME_LEN) {
1126 ERR("Application context string length size is too large: %zu bytes",
1127 ctxlen);
1128 ret = -EINVAL;
1129 goto error;
1130 }
1131 strcpy(ctxstr, "$app.");
1132 p = &ctxstr[strlen("$app.")];
1133 recvlen = ctxlen - strlen("$app.");
1134 len = ustcomm_recv_unix_sock(sock, p, recvlen);
1135 switch (len) {
1136 case 0: /* orderly shutdown */
1137 ret = 0;
1138 goto error;
1139 default:
1140 if (len == recvlen) {
1141 DBG("app context data received");
1142 break;
1143 } else if (len < 0) {
1144 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1145 if (len == -ECONNRESET) {
1146 ERR("%s remote end closed connection", sock_info->name);
1147 ret = len;
1148 goto error;
1149 }
1150 ret = len;
1151 goto error;
1152 } else {
1153 DBG("incorrect app context data message size: %zd", len);
1154 ret = -EINVAL;
1155 goto error;
1156 }
1157 }
1158 /* Put : between provider and ctxname. */
1159 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
1160 args.app_context.ctxname = ctxstr;
1161 break;
1162 }
1163 default:
1164 break;
1165 }
1166 if (ops->cmd) {
1167 ret = ops->cmd(lum->handle, lum->cmd,
1168 (unsigned long) &lum->u,
1169 &args, sock_info);
1170 } else {
1171 ret = -ENOSYS;
1172 }
1173 break;
1174 case LTTNG_UST_COUNTER:
1175 {
1176 void *counter_data;
1177
1178 len = ustcomm_recv_counter_from_sessiond(sock,
1179 &counter_data, lum->u.counter.len);
1180 switch (len) {
1181 case 0: /* orderly shutdown */
1182 ret = 0;
1183 goto error;
1184 default:
1185 if (len == lum->u.counter.len) {
1186 DBG("counter data received");
1187 break;
1188 } else if (len < 0) {
1189 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1190 if (len == -ECONNRESET) {
1191 ERR("%s remote end closed connection", sock_info->name);
1192 ret = len;
1193 goto error;
1194 }
1195 ret = len;
1196 goto error;
1197 } else {
1198 DBG("incorrect counter data message size: %zd", len);
1199 ret = -EINVAL;
1200 goto error;
1201 }
1202 }
1203 args.counter.counter_data = counter_data;
1204 if (ops->cmd)
1205 ret = ops->cmd(lum->handle, lum->cmd,
1206 (unsigned long) &lum->u,
1207 &args, sock_info);
1208 else
1209 ret = -ENOSYS;
1210 free(args.counter.counter_data);
1211 break;
1212 }
1213 case LTTNG_UST_COUNTER_GLOBAL:
1214 {
1215 /* Receive shm_fd */
1216 ret = ustcomm_recv_counter_shm_from_sessiond(sock,
1217 &args.counter_shm.shm_fd);
1218 if (ret) {
1219 goto error;
1220 }
1221
1222 if (ops->cmd)
1223 ret = ops->cmd(lum->handle, lum->cmd,
1224 (unsigned long) &lum->u,
1225 &args, sock_info);
1226 else
1227 ret = -ENOSYS;
1228 if (args.counter_shm.shm_fd >= 0) {
1229 int close_ret;
1230
1231 lttng_ust_lock_fd_tracker();
1232 close_ret = close(args.counter_shm.shm_fd);
1233 lttng_ust_unlock_fd_tracker();
1234 args.counter_shm.shm_fd = -1;
1235 if (close_ret)
1236 PERROR("close");
1237 }
1238 break;
1239 }
1240 case LTTNG_UST_COUNTER_CPU:
1241 {
1242 /* Receive shm_fd */
1243 ret = ustcomm_recv_counter_shm_from_sessiond(sock,
1244 &args.counter_shm.shm_fd);
1245 if (ret) {
1246 goto error;
1247 }
1248
1249 if (ops->cmd)
1250 ret = ops->cmd(lum->handle, lum->cmd,
1251 (unsigned long) &lum->u,
1252 &args, sock_info);
1253 else
1254 ret = -ENOSYS;
1255 if (args.counter_shm.shm_fd >= 0) {
1256 int close_ret;
1257
1258 lttng_ust_lock_fd_tracker();
1259 close_ret = close(args.counter_shm.shm_fd);
1260 lttng_ust_unlock_fd_tracker();
1261 args.counter_shm.shm_fd = -1;
1262 if (close_ret)
1263 PERROR("close");
1264 }
1265 break;
1266 }
1267 case LTTNG_UST_EVENT_NOTIFIER_CREATE:
1268 {
1269 /* Receive struct lttng_ust_event_notifier */
1270 struct lttng_ust_event_notifier event_notifier;
1271
1272 if (sizeof(event_notifier) != lum->u.event_notifier.len) {
1273 DBG("incorrect event notifier data message size: %u", lum->u.event_notifier.len);
1274 ret = -EINVAL;
1275 goto error;
1276 }
1277 len = ustcomm_recv_unix_sock(sock, &event_notifier, sizeof(event_notifier));
1278 switch (len) {
1279 case 0: /* orderly shutdown */
1280 ret = 0;
1281 goto error;
1282 default:
1283 if (len == sizeof(event_notifier)) {
1284 DBG("event notifier data received");
1285 break;
1286 } else if (len < 0) {
1287 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1288 if (len == -ECONNRESET) {
1289 ERR("%s remote end closed connection", sock_info->name);
1290 ret = len;
1291 goto error;
1292 }
1293 ret = len;
1294 goto error;
1295 } else {
1296 DBG("incorrect event notifier data message size: %zd", len);
1297 ret = -EINVAL;
1298 goto error;
1299 }
1300 }
1301 if (ops->cmd)
1302 ret = ops->cmd(lum->handle, lum->cmd,
1303 (unsigned long) &event_notifier,
1304 &args, sock_info);
1305 else
1306 ret = -ENOSYS;
1307 break;
1308 }
1309
1310 default:
1311 if (ops->cmd)
1312 ret = ops->cmd(lum->handle, lum->cmd,
1313 (unsigned long) &lum->u,
1314 &args, sock_info);
1315 else
1316 ret = -ENOSYS;
1317 break;
1318 }
1319
1320 lur.handle = lum->handle;
1321 lur.cmd = lum->cmd;
1322 lur.ret_val = ret;
1323 if (ret >= 0) {
1324 lur.ret_code = LTTNG_UST_OK;
1325 } else {
1326 /*
1327 * Use -LTTNG_UST_ERR as wildcard for UST internal
1328 * error that are not caused by the transport, except if
1329 * we already have a more precise error message to
1330 * report.
1331 */
1332 if (ret > -LTTNG_UST_ERR) {
1333 /* Translate code to UST error. */
1334 switch (ret) {
1335 case -EEXIST:
1336 lur.ret_code = -LTTNG_UST_ERR_EXIST;
1337 break;
1338 case -EINVAL:
1339 lur.ret_code = -LTTNG_UST_ERR_INVAL;
1340 break;
1341 case -ENOENT:
1342 lur.ret_code = -LTTNG_UST_ERR_NOENT;
1343 break;
1344 case -EPERM:
1345 lur.ret_code = -LTTNG_UST_ERR_PERM;
1346 break;
1347 case -ENOSYS:
1348 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
1349 break;
1350 default:
1351 lur.ret_code = -LTTNG_UST_ERR;
1352 break;
1353 }
1354 } else {
1355 lur.ret_code = ret;
1356 }
1357 }
1358 if (ret >= 0) {
1359 switch (lum->cmd) {
1360 case LTTNG_UST_TRACER_VERSION:
1361 lur.u.version = lum->u.version;
1362 break;
1363 case LTTNG_UST_TRACEPOINT_LIST_GET:
1364 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1365 break;
1366 }
1367 }
1368 DBG("Return value: %d", lur.ret_val);
1369
1370 ust_unlock();
1371
1372 /*
1373 * Performed delayed statedump operations outside of the UST
1374 * lock. We need to take the dynamic loader lock before we take
1375 * the UST lock internally within handle_pending_statedump().
1376 */
1377 handle_pending_statedump(sock_info);
1378
1379 if (ust_lock()) {
1380 ret = -LTTNG_UST_ERR_EXITING;
1381 goto error;
1382 }
1383
1384 ret = send_reply(sock, &lur);
1385 if (ret < 0) {
1386 DBG("error sending reply");
1387 goto error;
1388 }
1389
1390 /*
1391 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1392 * after the reply.
1393 */
1394 if (lur.ret_code == LTTNG_UST_OK) {
1395 switch (lum->cmd) {
1396 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
1397 len = ustcomm_send_unix_sock(sock,
1398 &args.field_list.entry,
1399 sizeof(args.field_list.entry));
1400 if (len < 0) {
1401 ret = len;
1402 goto error;
1403 }
1404 if (len != sizeof(args.field_list.entry)) {
1405 ret = -EINVAL;
1406 goto error;
1407 }
1408 }
1409 }
1410
1411 error:
1412 ust_unlock();
1413
1414 return ret;
1415 }
1416
1417 static
1418 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
1419 {
1420 int ret;
1421
1422 if (sock_info->root_handle != -1) {
1423 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1424 if (ret) {
1425 ERR("Error unref root handle");
1426 }
1427 sock_info->root_handle = -1;
1428 }
1429 sock_info->registration_done = 0;
1430 sock_info->initial_statedump_done = 0;
1431
1432 /*
1433 * wait_shm_mmap, socket and notify socket are used by listener
1434 * threads outside of the ust lock, so we cannot tear them down
1435 * ourselves, because we cannot join on these threads. Leave
1436 * responsibility of cleaning up these resources to the OS
1437 * process exit.
1438 */
1439 if (exiting)
1440 return;
1441
1442 if (sock_info->socket != -1) {
1443 ret = ustcomm_close_unix_sock(sock_info->socket);
1444 if (ret) {
1445 ERR("Error closing ust cmd socket");
1446 }
1447 sock_info->socket = -1;
1448 }
1449 if (sock_info->notify_socket != -1) {
1450 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1451 if (ret) {
1452 ERR("Error closing ust notify socket");
1453 }
1454 sock_info->notify_socket = -1;
1455 }
1456 if (sock_info->wait_shm_mmap) {
1457 long page_size;
1458
1459 page_size = LTTNG_UST_PAGE_SIZE;
1460 if (page_size <= 0) {
1461 if (!page_size) {
1462 errno = EINVAL;
1463 }
1464 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1465 } else {
1466 ret = munmap(sock_info->wait_shm_mmap, page_size);
1467 if (ret) {
1468 ERR("Error unmapping wait shm");
1469 }
1470 }
1471 sock_info->wait_shm_mmap = NULL;
1472 }
1473 }
1474
1475 /*
1476 * Using fork to set umask in the child process (not multi-thread safe).
1477 * We deal with the shm_open vs ftruncate race (happening when the
1478 * sessiond owns the shm and does not let everybody modify it, to ensure
1479 * safety against shm_unlink) by simply letting the mmap fail and
1480 * retrying after a few seconds.
1481 * For global shm, everybody has rw access to it until the sessiond
1482 * starts.
1483 */
1484 static
1485 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
1486 {
1487 int wait_shm_fd, ret;
1488 pid_t pid;
1489
1490 /*
1491 * Try to open read-only.
1492 */
1493 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1494 if (wait_shm_fd >= 0) {
1495 int32_t tmp_read;
1496 ssize_t len;
1497 size_t bytes_read = 0;
1498
1499 /*
1500 * Try to read the fd. If unable to do so, try opening
1501 * it in write mode.
1502 */
1503 do {
1504 len = read(wait_shm_fd,
1505 &((char *) &tmp_read)[bytes_read],
1506 sizeof(tmp_read) - bytes_read);
1507 if (len > 0) {
1508 bytes_read += len;
1509 }
1510 } while ((len < 0 && errno == EINTR)
1511 || (len > 0 && bytes_read < sizeof(tmp_read)));
1512 if (bytes_read != sizeof(tmp_read)) {
1513 ret = close(wait_shm_fd);
1514 if (ret) {
1515 ERR("close wait_shm_fd");
1516 }
1517 goto open_write;
1518 }
1519 goto end;
1520 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1521 /*
1522 * Real-only open did not work, and it's not because the
1523 * entry was not present. It's a failure that prohibits
1524 * using shm.
1525 */
1526 ERR("Error opening shm %s", sock_info->wait_shm_path);
1527 goto end;
1528 }
1529
1530 open_write:
1531 /*
1532 * If the open failed because the file did not exist, or because
1533 * the file was not truncated yet, try creating it ourself.
1534 */
1535 URCU_TLS(lttng_ust_nest_count)++;
1536 pid = fork();
1537 URCU_TLS(lttng_ust_nest_count)--;
1538 if (pid > 0) {
1539 int status;
1540
1541 /*
1542 * Parent: wait for child to return, in which case the
1543 * shared memory map will have been created.
1544 */
1545 pid = wait(&status);
1546 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1547 wait_shm_fd = -1;
1548 goto end;
1549 }
1550 /*
1551 * Try to open read-only again after creation.
1552 */
1553 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1554 if (wait_shm_fd < 0) {
1555 /*
1556 * Real-only open did not work. It's a failure
1557 * that prohibits using shm.
1558 */
1559 ERR("Error opening shm %s", sock_info->wait_shm_path);
1560 goto end;
1561 }
1562 goto end;
1563 } else if (pid == 0) {
1564 int create_mode;
1565
1566 /* Child */
1567 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
1568 if (sock_info->global)
1569 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
1570 /*
1571 * We're alone in a child process, so we can modify the
1572 * process-wide umask.
1573 */
1574 umask(~create_mode);
1575 /*
1576 * Try creating shm (or get rw access).
1577 * We don't do an exclusive open, because we allow other
1578 * processes to create+ftruncate it concurrently.
1579 */
1580 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1581 O_RDWR | O_CREAT, create_mode);
1582 if (wait_shm_fd >= 0) {
1583 ret = ftruncate(wait_shm_fd, mmap_size);
1584 if (ret) {
1585 PERROR("ftruncate");
1586 _exit(EXIT_FAILURE);
1587 }
1588 _exit(EXIT_SUCCESS);
1589 }
1590 /*
1591 * For local shm, we need to have rw access to accept
1592 * opening it: this means the local sessiond will be
1593 * able to wake us up. For global shm, we open it even
1594 * if rw access is not granted, because the root.root
1595 * sessiond will be able to override all rights and wake
1596 * us up.
1597 */
1598 if (!sock_info->global && errno != EACCES) {
1599 ERR("Error opening shm %s", sock_info->wait_shm_path);
1600 _exit(EXIT_FAILURE);
1601 }
1602 /*
1603 * The shm exists, but we cannot open it RW. Report
1604 * success.
1605 */
1606 _exit(EXIT_SUCCESS);
1607 } else {
1608 return -1;
1609 }
1610 end:
1611 if (wait_shm_fd >= 0 && !sock_info->global) {
1612 struct stat statbuf;
1613
1614 /*
1615 * Ensure that our user is the owner of the shm file for
1616 * local shm. If we do not own the file, it means our
1617 * sessiond will not have access to wake us up (there is
1618 * probably a rogue process trying to fake our
1619 * sessiond). Fallback to polling method in this case.
1620 */
1621 ret = fstat(wait_shm_fd, &statbuf);
1622 if (ret) {
1623 PERROR("fstat");
1624 goto error_close;
1625 }
1626 if (statbuf.st_uid != getuid())
1627 goto error_close;
1628 }
1629 return wait_shm_fd;
1630
1631 error_close:
1632 ret = close(wait_shm_fd);
1633 if (ret) {
1634 PERROR("Error closing fd");
1635 }
1636 return -1;
1637 }
1638
1639 static
1640 char *get_map_shm(struct sock_info *sock_info)
1641 {
1642 long page_size;
1643 int wait_shm_fd, ret;
1644 char *wait_shm_mmap;
1645
1646 page_size = sysconf(_SC_PAGE_SIZE);
1647 if (page_size <= 0) {
1648 if (!page_size) {
1649 errno = EINVAL;
1650 }
1651 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1652 goto error;
1653 }
1654
1655 lttng_ust_lock_fd_tracker();
1656 wait_shm_fd = get_wait_shm(sock_info, page_size);
1657 if (wait_shm_fd < 0) {
1658 lttng_ust_unlock_fd_tracker();
1659 goto error;
1660 }
1661
1662 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1663 if (ret < 0) {
1664 ret = close(wait_shm_fd);
1665 if (!ret) {
1666 PERROR("Error closing fd");
1667 }
1668 lttng_ust_unlock_fd_tracker();
1669 goto error;
1670 }
1671
1672 wait_shm_fd = ret;
1673 lttng_ust_unlock_fd_tracker();
1674
1675 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
1676 MAP_SHARED, wait_shm_fd, 0);
1677
1678 /* close shm fd immediately after taking the mmap reference */
1679 lttng_ust_lock_fd_tracker();
1680 ret = close(wait_shm_fd);
1681 if (!ret) {
1682 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1683 } else {
1684 PERROR("Error closing fd");
1685 }
1686 lttng_ust_unlock_fd_tracker();
1687
1688 if (wait_shm_mmap == MAP_FAILED) {
1689 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1690 goto error;
1691 }
1692 return wait_shm_mmap;
1693
1694 error:
1695 return NULL;
1696 }
1697
1698 static
1699 void wait_for_sessiond(struct sock_info *sock_info)
1700 {
1701 /* Use ust_lock to check if we should quit. */
1702 if (ust_lock()) {
1703 goto quit;
1704 }
1705 if (wait_poll_fallback) {
1706 goto error;
1707 }
1708 ust_unlock();
1709
1710 assert(sock_info->wait_shm_mmap);
1711
1712 DBG("Waiting for %s apps sessiond", sock_info->name);
1713 /* Wait for futex wakeup */
1714 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1715 goto end_wait;
1716
1717 while (lttng_ust_futex_async((int32_t *) sock_info->wait_shm_mmap,
1718 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1719 switch (errno) {
1720 case EWOULDBLOCK:
1721 /* Value already changed. */
1722 goto end_wait;
1723 case EINTR:
1724 /* Retry if interrupted by signal. */
1725 break; /* Get out of switch. */
1726 case EFAULT:
1727 wait_poll_fallback = 1;
1728 DBG(
1729 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1730 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1731 "Please upgrade your kernel "
1732 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1733 "mainline). LTTng-UST will use polling mode fallback.");
1734 if (ust_debug())
1735 PERROR("futex");
1736 goto end_wait;
1737 }
1738 }
1739 end_wait:
1740 return;
1741
1742 quit:
1743 ust_unlock();
1744 return;
1745
1746 error:
1747 ust_unlock();
1748 return;
1749 }
1750
1751 /*
1752 * This thread does not allocate any resource, except within
1753 * handle_message, within mutex protection. This mutex protects against
1754 * fork and exit.
1755 * The other moment it allocates resources is at socket connection, which
1756 * is also protected by the mutex.
1757 */
1758 static
1759 void *ust_listener_thread(void *arg)
1760 {
1761 struct sock_info *sock_info = arg;
1762 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
1763 long timeout;
1764
1765 lttng_ust_fixup_tls();
1766 /*
1767 * If available, add '-ust' to the end of this thread's
1768 * process name
1769 */
1770 ret = lttng_ust_setustprocname();
1771 if (ret) {
1772 ERR("Unable to set UST process name");
1773 }
1774
1775 /* Restart trying to connect to the session daemon */
1776 restart:
1777 if (prev_connect_failed) {
1778 /* Wait for sessiond availability with pipe */
1779 wait_for_sessiond(sock_info);
1780 if (has_waited) {
1781 has_waited = 0;
1782 /*
1783 * Sleep for 5 seconds before retrying after a
1784 * sequence of failure / wait / failure. This
1785 * deals with a killed or broken session daemon.
1786 */
1787 sleep(5);
1788 } else {
1789 has_waited = 1;
1790 }
1791 prev_connect_failed = 0;
1792 }
1793
1794 if (ust_lock()) {
1795 goto quit;
1796 }
1797
1798 if (sock_info->socket != -1) {
1799 /* FD tracker is updated by ustcomm_close_unix_sock() */
1800 ret = ustcomm_close_unix_sock(sock_info->socket);
1801 if (ret) {
1802 ERR("Error closing %s ust cmd socket",
1803 sock_info->name);
1804 }
1805 sock_info->socket = -1;
1806 }
1807 if (sock_info->notify_socket != -1) {
1808 /* FD tracker is updated by ustcomm_close_unix_sock() */
1809 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1810 if (ret) {
1811 ERR("Error closing %s ust notify socket",
1812 sock_info->name);
1813 }
1814 sock_info->notify_socket = -1;
1815 }
1816
1817
1818 /*
1819 * Register. We need to perform both connect and sending
1820 * registration message before doing the next connect otherwise
1821 * we may reach unix socket connect queue max limits and block
1822 * on the 2nd connect while the session daemon is awaiting the
1823 * first connect registration message.
1824 */
1825 /* Connect cmd socket */
1826 lttng_ust_lock_fd_tracker();
1827 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1828 get_connect_sock_timeout());
1829 if (ret < 0) {
1830 lttng_ust_unlock_fd_tracker();
1831 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1832 prev_connect_failed = 1;
1833
1834 /*
1835 * If we cannot find the sessiond daemon, don't delay
1836 * constructor execution.
1837 */
1838 ret = handle_register_failed(sock_info);
1839 assert(!ret);
1840 ust_unlock();
1841 goto restart;
1842 }
1843 fd = ret;
1844 ret = lttng_ust_add_fd_to_tracker(fd);
1845 if (ret < 0) {
1846 ret = close(fd);
1847 if (ret) {
1848 PERROR("close on sock_info->socket");
1849 }
1850 ret = -1;
1851 lttng_ust_unlock_fd_tracker();
1852 ust_unlock();
1853 goto quit;
1854 }
1855
1856 sock_info->socket = ret;
1857 lttng_ust_unlock_fd_tracker();
1858
1859 ust_unlock();
1860 /*
1861 * Unlock/relock ust lock because connect is blocking (with
1862 * timeout). Don't delay constructors on the ust lock for too
1863 * long.
1864 */
1865 if (ust_lock()) {
1866 goto quit;
1867 }
1868
1869 /*
1870 * Create only one root handle per listener thread for the whole
1871 * process lifetime, so we ensure we get ID which is statically
1872 * assigned to the root handle.
1873 */
1874 if (sock_info->root_handle == -1) {
1875 ret = lttng_abi_create_root_handle();
1876 if (ret < 0) {
1877 ERR("Error creating root handle");
1878 goto quit;
1879 }
1880 sock_info->root_handle = ret;
1881 }
1882
1883 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
1884 if (ret < 0) {
1885 ERR("Error registering to %s ust cmd socket",
1886 sock_info->name);
1887 prev_connect_failed = 1;
1888 /*
1889 * If we cannot register to the sessiond daemon, don't
1890 * delay constructor execution.
1891 */
1892 ret = handle_register_failed(sock_info);
1893 assert(!ret);
1894 ust_unlock();
1895 goto restart;
1896 }
1897
1898 ust_unlock();
1899 /*
1900 * Unlock/relock ust lock because connect is blocking (with
1901 * timeout). Don't delay constructors on the ust lock for too
1902 * long.
1903 */
1904 if (ust_lock()) {
1905 goto quit;
1906 }
1907
1908 /* Connect notify socket */
1909 lttng_ust_lock_fd_tracker();
1910 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1911 get_connect_sock_timeout());
1912 if (ret < 0) {
1913 lttng_ust_unlock_fd_tracker();
1914 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1915 prev_connect_failed = 1;
1916
1917 /*
1918 * If we cannot find the sessiond daemon, don't delay
1919 * constructor execution.
1920 */
1921 ret = handle_register_failed(sock_info);
1922 assert(!ret);
1923 ust_unlock();
1924 goto restart;
1925 }
1926
1927 fd = ret;
1928 ret = lttng_ust_add_fd_to_tracker(fd);
1929 if (ret < 0) {
1930 ret = close(fd);
1931 if (ret) {
1932 PERROR("close on sock_info->notify_socket");
1933 }
1934 ret = -1;
1935 lttng_ust_unlock_fd_tracker();
1936 ust_unlock();
1937 goto quit;
1938 }
1939
1940 sock_info->notify_socket = ret;
1941 lttng_ust_unlock_fd_tracker();
1942
1943 ust_unlock();
1944 /*
1945 * Unlock/relock ust lock because connect is blocking (with
1946 * timeout). Don't delay constructors on the ust lock for too
1947 * long.
1948 */
1949 if (ust_lock()) {
1950 goto quit;
1951 }
1952
1953 timeout = get_notify_sock_timeout();
1954 if (timeout >= 0) {
1955 /*
1956 * Give at least 10ms to sessiond to reply to
1957 * notifications.
1958 */
1959 if (timeout < 10)
1960 timeout = 10;
1961 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1962 timeout);
1963 if (ret < 0) {
1964 WARN("Error setting socket receive timeout");
1965 }
1966 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1967 timeout);
1968 if (ret < 0) {
1969 WARN("Error setting socket send timeout");
1970 }
1971 } else if (timeout < -1) {
1972 WARN("Unsupported timeout value %ld", timeout);
1973 }
1974
1975 ret = register_to_sessiond(sock_info->notify_socket,
1976 USTCTL_SOCKET_NOTIFY);
1977 if (ret < 0) {
1978 ERR("Error registering to %s ust notify socket",
1979 sock_info->name);
1980 prev_connect_failed = 1;
1981 /*
1982 * If we cannot register to the sessiond daemon, don't
1983 * delay constructor execution.
1984 */
1985 ret = handle_register_failed(sock_info);
1986 assert(!ret);
1987 ust_unlock();
1988 goto restart;
1989 }
1990 sock = sock_info->socket;
1991
1992 ust_unlock();
1993
1994 for (;;) {
1995 ssize_t len;
1996 struct ustcomm_ust_msg lum;
1997
1998 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1999 switch (len) {
2000 case 0: /* orderly shutdown */
2001 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
2002 if (ust_lock()) {
2003 goto quit;
2004 }
2005 /*
2006 * Either sessiond has shutdown or refused us by closing the socket.
2007 * In either case, we don't want to delay construction execution,
2008 * and we need to wait before retry.
2009 */
2010 prev_connect_failed = 1;
2011 /*
2012 * If we cannot register to the sessiond daemon, don't
2013 * delay constructor execution.
2014 */
2015 ret = handle_register_failed(sock_info);
2016 assert(!ret);
2017 ust_unlock();
2018 goto end;
2019 case sizeof(lum):
2020 print_cmd(lum.cmd, lum.handle);
2021 ret = handle_message(sock_info, sock, &lum);
2022 if (ret) {
2023 ERR("Error handling message for %s socket",
2024 sock_info->name);
2025 /*
2026 * Close socket if protocol error is
2027 * detected.
2028 */
2029 goto end;
2030 }
2031 continue;
2032 default:
2033 if (len < 0) {
2034 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
2035 } else {
2036 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
2037 }
2038 if (len == -ECONNRESET) {
2039 DBG("%s remote end closed connection", sock_info->name);
2040 goto end;
2041 }
2042 goto end;
2043 }
2044
2045 }
2046 end:
2047 if (ust_lock()) {
2048 goto quit;
2049 }
2050 /* Cleanup socket handles before trying to reconnect */
2051 lttng_ust_objd_table_owner_cleanup(sock_info);
2052 ust_unlock();
2053 goto restart; /* try to reconnect */
2054
2055 quit:
2056 ust_unlock();
2057
2058 pthread_mutex_lock(&ust_exit_mutex);
2059 sock_info->thread_active = 0;
2060 pthread_mutex_unlock(&ust_exit_mutex);
2061 return NULL;
2062 }
2063
2064 /*
2065 * Weak symbol to call when the ust malloc wrapper is not loaded.
2066 */
2067 __attribute__((weak))
2068 void lttng_ust_malloc_wrapper_init(void)
2069 {
2070 }
2071
2072 /*
2073 * sessiond monitoring thread: monitor presence of global and per-user
2074 * sessiond by polling the application common named pipe.
2075 */
2076 void __attribute__((constructor)) lttng_ust_init(void)
2077 {
2078 struct timespec constructor_timeout;
2079 sigset_t sig_all_blocked, orig_parent_mask;
2080 pthread_attr_t thread_attr;
2081 int timeout_mode;
2082 int ret;
2083 void *handle;
2084
2085 if (uatomic_xchg(&initialized, 1) == 1)
2086 return;
2087
2088 /*
2089 * Fixup interdependency between TLS fixup mutex (which happens
2090 * to be the dynamic linker mutex) and ust_lock, taken within
2091 * the ust lock.
2092 */
2093 lttng_ust_fixup_tls();
2094
2095 lttng_ust_loaded = 1;
2096
2097 /*
2098 * We need to ensure that the liblttng-ust library is not unloaded to avoid
2099 * the unloading of code used by the ust_listener_threads as we can not
2100 * reliably know when they exited. To do that, manually load
2101 * liblttng-ust.so to increment the dynamic loader's internal refcount for
2102 * this library so it never becomes zero, thus never gets unloaded from the
2103 * address space of the process. Since we are already running in the
2104 * constructor of the LTTNG_UST_LIB_SO_NAME library, calling dlopen will
2105 * simply increment the refcount and no additionnal work is needed by the
2106 * dynamic loader as the shared library is already loaded in the address
2107 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
2108 * unloading of the UST library if its refcount becomes zero (which should
2109 * never happen). Do the return value check but discard the handle at the
2110 * end of the function as it's not needed.
2111 */
2112 handle = dlopen(LTTNG_UST_LIB_SO_NAME, RTLD_LAZY | RTLD_NODELETE);
2113 if (!handle) {
2114 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SO_NAME);
2115 }
2116
2117 /*
2118 * We want precise control over the order in which we construct
2119 * our sub-libraries vs starting to receive commands from
2120 * sessiond (otherwise leading to errors when trying to create
2121 * sessiond before the init functions are completed).
2122 */
2123 init_usterr();
2124 lttng_ust_getenv_init(); /* Needs init_usterr() to be completed. */
2125 init_tracepoint();
2126 lttng_ust_init_fd_tracker();
2127 lttng_ust_clock_init();
2128 lttng_ust_getcpu_init();
2129 lttng_ust_statedump_init();
2130 lttng_ring_buffer_metadata_client_init();
2131 lttng_ring_buffer_client_overwrite_init();
2132 lttng_ring_buffer_client_overwrite_rt_init();
2133 lttng_ring_buffer_client_discard_init();
2134 lttng_ring_buffer_client_discard_rt_init();
2135 lttng_counter_client_percpu_32_modular_init();
2136 lttng_counter_client_percpu_64_modular_init();
2137 lttng_perf_counter_init();
2138 /*
2139 * Invoke ust malloc wrapper init before starting other threads.
2140 */
2141 lttng_ust_malloc_wrapper_init();
2142
2143 timeout_mode = get_constructor_timeout(&constructor_timeout);
2144
2145 get_allow_blocking();
2146
2147 ret = sem_init(&constructor_wait, 0, 0);
2148 if (ret) {
2149 PERROR("sem_init");
2150 }
2151
2152 ret = setup_global_apps();
2153 if (ret) {
2154 assert(global_apps.allowed == 0);
2155 DBG("global apps setup returned %d", ret);
2156 }
2157
2158 ret = setup_local_apps();
2159 if (ret) {
2160 assert(local_apps.allowed == 0);
2161 DBG("local apps setup returned %d", ret);
2162 }
2163
2164 /* A new thread created by pthread_create inherits the signal mask
2165 * from the parent. To avoid any signal being received by the
2166 * listener thread, we block all signals temporarily in the parent,
2167 * while we create the listener thread.
2168 */
2169 sigfillset(&sig_all_blocked);
2170 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
2171 if (ret) {
2172 ERR("pthread_sigmask: %s", strerror(ret));
2173 }
2174
2175 ret = pthread_attr_init(&thread_attr);
2176 if (ret) {
2177 ERR("pthread_attr_init: %s", strerror(ret));
2178 }
2179 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
2180 if (ret) {
2181 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
2182 }
2183
2184 if (global_apps.allowed) {
2185 pthread_mutex_lock(&ust_exit_mutex);
2186 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
2187 ust_listener_thread, &global_apps);
2188 if (ret) {
2189 ERR("pthread_create global: %s", strerror(ret));
2190 }
2191 global_apps.thread_active = 1;
2192 pthread_mutex_unlock(&ust_exit_mutex);
2193 } else {
2194 handle_register_done(&global_apps);
2195 }
2196
2197 if (local_apps.allowed) {
2198 pthread_mutex_lock(&ust_exit_mutex);
2199 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
2200 ust_listener_thread, &local_apps);
2201 if (ret) {
2202 ERR("pthread_create local: %s", strerror(ret));
2203 }
2204 local_apps.thread_active = 1;
2205 pthread_mutex_unlock(&ust_exit_mutex);
2206 } else {
2207 handle_register_done(&local_apps);
2208 }
2209 ret = pthread_attr_destroy(&thread_attr);
2210 if (ret) {
2211 ERR("pthread_attr_destroy: %s", strerror(ret));
2212 }
2213
2214 /* Restore original signal mask in parent */
2215 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
2216 if (ret) {
2217 ERR("pthread_sigmask: %s", strerror(ret));
2218 }
2219
2220 switch (timeout_mode) {
2221 case 1: /* timeout wait */
2222 do {
2223 ret = sem_timedwait(&constructor_wait,
2224 &constructor_timeout);
2225 } while (ret < 0 && errno == EINTR);
2226 if (ret < 0) {
2227 switch (errno) {
2228 case ETIMEDOUT:
2229 ERR("Timed out waiting for lttng-sessiond");
2230 break;
2231 case EINVAL:
2232 PERROR("sem_timedwait");
2233 break;
2234 default:
2235 ERR("Unexpected error \"%s\" returned by sem_timedwait",
2236 strerror(errno));
2237 }
2238 }
2239 break;
2240 case -1:/* wait forever */
2241 do {
2242 ret = sem_wait(&constructor_wait);
2243 } while (ret < 0 && errno == EINTR);
2244 if (ret < 0) {
2245 switch (errno) {
2246 case EINVAL:
2247 PERROR("sem_wait");
2248 break;
2249 default:
2250 ERR("Unexpected error \"%s\" returned by sem_wait",
2251 strerror(errno));
2252 }
2253 }
2254 break;
2255 case 0: /* no timeout */
2256 break;
2257 }
2258 }
2259
2260 static
2261 void lttng_ust_cleanup(int exiting)
2262 {
2263 cleanup_sock_info(&global_apps, exiting);
2264 cleanup_sock_info(&local_apps, exiting);
2265 local_apps.allowed = 0;
2266 global_apps.allowed = 0;
2267 /*
2268 * The teardown in this function all affect data structures
2269 * accessed under the UST lock by the listener thread. This
2270 * lock, along with the lttng_ust_comm_should_quit flag, ensure
2271 * that none of these threads are accessing this data at this
2272 * point.
2273 */
2274 lttng_ust_abi_exit();
2275 lttng_ust_events_exit();
2276 lttng_perf_counter_exit();
2277 lttng_ring_buffer_client_discard_rt_exit();
2278 lttng_ring_buffer_client_discard_exit();
2279 lttng_ring_buffer_client_overwrite_rt_exit();
2280 lttng_ring_buffer_client_overwrite_exit();
2281 lttng_ring_buffer_metadata_client_exit();
2282 lttng_counter_client_percpu_32_modular_exit();
2283 lttng_counter_client_percpu_64_modular_exit();
2284 lttng_ust_statedump_destroy();
2285 exit_tracepoint();
2286 if (!exiting) {
2287 /* Reinitialize values for fork */
2288 sem_count = sem_count_initial_value;
2289 lttng_ust_comm_should_quit = 0;
2290 initialized = 0;
2291 }
2292 }
2293
2294 void __attribute__((destructor)) lttng_ust_exit(void)
2295 {
2296 int ret;
2297
2298 /*
2299 * Using pthread_cancel here because:
2300 * A) we don't want to hang application teardown.
2301 * B) the thread is not allocating any resource.
2302 */
2303
2304 /*
2305 * Require the communication thread to quit. Synchronize with
2306 * mutexes to ensure it is not in a mutex critical section when
2307 * pthread_cancel is later called.
2308 */
2309 ust_lock_nocheck();
2310 lttng_ust_comm_should_quit = 1;
2311 ust_unlock();
2312
2313 pthread_mutex_lock(&ust_exit_mutex);
2314 /* cancel threads */
2315 if (global_apps.thread_active) {
2316 ret = pthread_cancel(global_apps.ust_listener);
2317 if (ret) {
2318 ERR("Error cancelling global ust listener thread: %s",
2319 strerror(ret));
2320 } else {
2321 global_apps.thread_active = 0;
2322 }
2323 }
2324 if (local_apps.thread_active) {
2325 ret = pthread_cancel(local_apps.ust_listener);
2326 if (ret) {
2327 ERR("Error cancelling local ust listener thread: %s",
2328 strerror(ret));
2329 } else {
2330 local_apps.thread_active = 0;
2331 }
2332 }
2333 pthread_mutex_unlock(&ust_exit_mutex);
2334
2335 /*
2336 * Do NOT join threads: use of sys_futex makes it impossible to
2337 * join the threads without using async-cancel, but async-cancel
2338 * is delivered by a signal, which could hit the target thread
2339 * anywhere in its code path, including while the ust_lock() is
2340 * held, causing a deadlock for the other thread. Let the OS
2341 * cleanup the threads if there are stalled in a syscall.
2342 */
2343 lttng_ust_cleanup(1);
2344 }
2345
2346 static
2347 void ust_context_ns_reset(void)
2348 {
2349 lttng_context_pid_ns_reset();
2350 lttng_context_cgroup_ns_reset();
2351 lttng_context_ipc_ns_reset();
2352 lttng_context_mnt_ns_reset();
2353 lttng_context_net_ns_reset();
2354 lttng_context_user_ns_reset();
2355 lttng_context_time_ns_reset();
2356 lttng_context_uts_ns_reset();
2357 }
2358
2359 static
2360 void ust_context_vuids_reset(void)
2361 {
2362 lttng_context_vuid_reset();
2363 lttng_context_veuid_reset();
2364 lttng_context_vsuid_reset();
2365 }
2366
2367 static
2368 void ust_context_vgids_reset(void)
2369 {
2370 lttng_context_vgid_reset();
2371 lttng_context_vegid_reset();
2372 lttng_context_vsgid_reset();
2373 }
2374
2375 /*
2376 * We exclude the worker threads across fork and clone (except
2377 * CLONE_VM), because these system calls only keep the forking thread
2378 * running in the child. Therefore, we don't want to call fork or clone
2379 * in the middle of an tracepoint or ust tracing state modification.
2380 * Holding this mutex protects these structures across fork and clone.
2381 */
2382 void ust_before_fork(sigset_t *save_sigset)
2383 {
2384 /*
2385 * Disable signals. This is to avoid that the child intervenes
2386 * before it is properly setup for tracing. It is safer to
2387 * disable all signals, because then we know we are not breaking
2388 * anything by restoring the original mask.
2389 */
2390 sigset_t all_sigs;
2391 int ret;
2392
2393 /* Fixup lttng-ust TLS. */
2394 lttng_ust_fixup_tls();
2395
2396 if (URCU_TLS(lttng_ust_nest_count))
2397 return;
2398 /* Disable signals */
2399 sigfillset(&all_sigs);
2400 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
2401 if (ret == -1) {
2402 PERROR("sigprocmask");
2403 }
2404
2405 pthread_mutex_lock(&ust_fork_mutex);
2406
2407 ust_lock_nocheck();
2408 lttng_ust_urcu_before_fork();
2409 lttng_ust_lock_fd_tracker();
2410 lttng_perf_lock();
2411 }
2412
2413 static void ust_after_fork_common(sigset_t *restore_sigset)
2414 {
2415 int ret;
2416
2417 DBG("process %d", getpid());
2418 lttng_perf_unlock();
2419 lttng_ust_unlock_fd_tracker();
2420 ust_unlock();
2421
2422 pthread_mutex_unlock(&ust_fork_mutex);
2423
2424 /* Restore signals */
2425 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
2426 if (ret == -1) {
2427 PERROR("sigprocmask");
2428 }
2429 }
2430
2431 void ust_after_fork_parent(sigset_t *restore_sigset)
2432 {
2433 if (URCU_TLS(lttng_ust_nest_count))
2434 return;
2435 DBG("process %d", getpid());
2436 lttng_ust_urcu_after_fork_parent();
2437 /* Release mutexes and reenable signals */
2438 ust_after_fork_common(restore_sigset);
2439 }
2440
2441 /*
2442 * After fork, in the child, we need to cleanup all the leftover state,
2443 * except the worker thread which already magically disappeared thanks
2444 * to the weird Linux fork semantics. After tyding up, we call
2445 * lttng_ust_init() again to start over as a new PID.
2446 *
2447 * This is meant for forks() that have tracing in the child between the
2448 * fork and following exec call (if there is any).
2449 */
2450 void ust_after_fork_child(sigset_t *restore_sigset)
2451 {
2452 if (URCU_TLS(lttng_ust_nest_count))
2453 return;
2454 lttng_context_vpid_reset();
2455 lttng_context_vtid_reset();
2456 lttng_context_procname_reset();
2457 ust_context_ns_reset();
2458 ust_context_vuids_reset();
2459 ust_context_vgids_reset();
2460 DBG("process %d", getpid());
2461 /* Release urcu mutexes */
2462 lttng_ust_urcu_after_fork_child();
2463 lttng_ust_cleanup(0);
2464 /* Release mutexes and reenable signals */
2465 ust_after_fork_common(restore_sigset);
2466 lttng_ust_init();
2467 }
2468
2469 void ust_after_setns(void)
2470 {
2471 ust_context_ns_reset();
2472 ust_context_vuids_reset();
2473 ust_context_vgids_reset();
2474 }
2475
2476 void ust_after_unshare(void)
2477 {
2478 ust_context_ns_reset();
2479 ust_context_vuids_reset();
2480 ust_context_vgids_reset();
2481 }
2482
2483 void ust_after_setuid(void)
2484 {
2485 ust_context_vuids_reset();
2486 }
2487
2488 void ust_after_seteuid(void)
2489 {
2490 ust_context_vuids_reset();
2491 }
2492
2493 void ust_after_setreuid(void)
2494 {
2495 ust_context_vuids_reset();
2496 }
2497
2498 void ust_after_setresuid(void)
2499 {
2500 ust_context_vuids_reset();
2501 }
2502
2503 void ust_after_setgid(void)
2504 {
2505 ust_context_vgids_reset();
2506 }
2507
2508 void ust_after_setegid(void)
2509 {
2510 ust_context_vgids_reset();
2511 }
2512
2513 void ust_after_setregid(void)
2514 {
2515 ust_context_vgids_reset();
2516 }
2517
2518 void ust_after_setresgid(void)
2519 {
2520 ust_context_vgids_reset();
2521 }
2522
2523 void lttng_ust_sockinfo_session_enabled(void *owner)
2524 {
2525 struct sock_info *sock_info = owner;
2526 sock_info->statedump_pending = 1;
2527 }
This page took 0.112851 seconds and 4 git commands to generate.