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