2186dc92aa38d124d328b5187d98fe9b99a4d8c3
[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
655 return 0;
656 }
657
658 static
659 int handle_register_failed(struct sock_info *sock_info)
660 {
661 if (sock_info->registration_done)
662 return 0;
663 sock_info->registration_done = 1;
664 sock_info->initial_statedump_done = 1;
665
666 decrement_sem_count(2);
667
668 return 0;
669 }
670
671 /*
672 * Only execute pending statedump after the constructor semaphore has
673 * been posted by the current listener thread. This means statedump will
674 * only be performed after the "registration done" command is received
675 * from this thread's session daemon.
676 *
677 * This ensures we don't run into deadlock issues with the dynamic
678 * loader mutex, which is held while the constructor is called and
679 * waiting on the constructor semaphore. All operations requiring this
680 * dynamic loader lock need to be postponed using this mechanism.
681 *
682 * In a scenario with two session daemons connected to the application,
683 * it is possible that the first listener thread which receives the
684 * registration done command issues its statedump while the dynamic
685 * loader lock is still held by the application constructor waiting on
686 * the semaphore. It will however be allowed to proceed when the
687 * second session daemon sends the registration done command to the
688 * second listener thread. This situation therefore does not produce
689 * a deadlock.
690 */
691 static
692 void handle_pending_statedump(struct sock_info *sock_info)
693 {
694 if (sock_info->registration_done && sock_info->statedump_pending) {
695 sock_info->statedump_pending = 0;
696 pthread_mutex_lock(&ust_fork_mutex);
697 lttng_handle_pending_statedump(sock_info);
698 pthread_mutex_unlock(&ust_fork_mutex);
699
700 if (!sock_info->initial_statedump_done) {
701 sock_info->initial_statedump_done = 1;
702 decrement_sem_count(1);
703 }
704 }
705 }
706
707 static
708 int handle_message(struct sock_info *sock_info,
709 int sock, struct ustcomm_ust_msg *lum)
710 {
711 int ret = 0;
712 const struct lttng_ust_objd_ops *ops;
713 struct ustcomm_ust_reply lur;
714 union ust_args args;
715 char ctxstr[LTTNG_UST_SYM_NAME_LEN]; /* App context string. */
716 ssize_t len;
717
718 memset(&lur, 0, sizeof(lur));
719
720 if (ust_lock()) {
721 ret = -LTTNG_UST_ERR_EXITING;
722 goto error;
723 }
724
725 ops = objd_ops(lum->handle);
726 if (!ops) {
727 ret = -ENOENT;
728 goto error;
729 }
730
731 switch (lum->cmd) {
732 case LTTNG_UST_REGISTER_DONE:
733 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
734 ret = handle_register_done(sock_info);
735 else
736 ret = -EINVAL;
737 break;
738 case LTTNG_UST_RELEASE:
739 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
740 ret = -EPERM;
741 else
742 ret = lttng_ust_objd_unref(lum->handle, 1);
743 break;
744 case LTTNG_UST_FILTER:
745 {
746 /* Receive filter data */
747 struct lttng_ust_filter_bytecode_node *bytecode;
748
749 if (lum->u.filter.data_size > FILTER_BYTECODE_MAX_LEN) {
750 ERR("Filter data size is too large: %u bytes",
751 lum->u.filter.data_size);
752 ret = -EINVAL;
753 goto error;
754 }
755
756 if (lum->u.filter.reloc_offset > lum->u.filter.data_size) {
757 ERR("Filter reloc offset %u is not within data",
758 lum->u.filter.reloc_offset);
759 ret = -EINVAL;
760 goto error;
761 }
762
763 bytecode = zmalloc(sizeof(*bytecode) + lum->u.filter.data_size);
764 if (!bytecode) {
765 ret = -ENOMEM;
766 goto error;
767 }
768 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data,
769 lum->u.filter.data_size);
770 switch (len) {
771 case 0: /* orderly shutdown */
772 ret = 0;
773 free(bytecode);
774 goto error;
775 default:
776 if (len == lum->u.filter.data_size) {
777 DBG("filter data received");
778 break;
779 } else if (len < 0) {
780 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
781 if (len == -ECONNRESET) {
782 ERR("%s remote end closed connection", sock_info->name);
783 ret = len;
784 free(bytecode);
785 goto error;
786 }
787 ret = len;
788 free(bytecode);
789 goto error;
790 } else {
791 DBG("incorrect filter data message size: %zd", len);
792 ret = -EINVAL;
793 free(bytecode);
794 goto error;
795 }
796 }
797 bytecode->bc.len = lum->u.filter.data_size;
798 bytecode->bc.reloc_offset = lum->u.filter.reloc_offset;
799 bytecode->bc.seqnum = lum->u.filter.seqnum;
800 if (ops->cmd) {
801 ret = ops->cmd(lum->handle, lum->cmd,
802 (unsigned long) bytecode,
803 &args, sock_info);
804 if (ret) {
805 free(bytecode);
806 }
807 /* don't free bytecode if everything went fine. */
808 } else {
809 ret = -ENOSYS;
810 free(bytecode);
811 }
812 break;
813 }
814 case LTTNG_UST_EXCLUSION:
815 {
816 /* Receive exclusion names */
817 struct lttng_ust_excluder_node *node;
818 unsigned int count;
819
820 count = lum->u.exclusion.count;
821 if (count == 0) {
822 /* There are no names to read */
823 ret = 0;
824 goto error;
825 }
826 node = zmalloc(sizeof(*node) +
827 count * LTTNG_UST_SYM_NAME_LEN);
828 if (!node) {
829 ret = -ENOMEM;
830 goto error;
831 }
832 node->excluder.count = count;
833 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
834 count * LTTNG_UST_SYM_NAME_LEN);
835 switch (len) {
836 case 0: /* orderly shutdown */
837 ret = 0;
838 free(node);
839 goto error;
840 default:
841 if (len == count * LTTNG_UST_SYM_NAME_LEN) {
842 DBG("Exclusion data received");
843 break;
844 } else if (len < 0) {
845 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
846 if (len == -ECONNRESET) {
847 ERR("%s remote end closed connection", sock_info->name);
848 ret = len;
849 free(node);
850 goto error;
851 }
852 ret = len;
853 free(node);
854 goto error;
855 } else {
856 DBG("Incorrect exclusion data message size: %zd", len);
857 ret = -EINVAL;
858 free(node);
859 goto error;
860 }
861 }
862 if (ops->cmd) {
863 ret = ops->cmd(lum->handle, lum->cmd,
864 (unsigned long) node,
865 &args, sock_info);
866 if (ret) {
867 free(node);
868 }
869 /* Don't free exclusion data if everything went fine. */
870 } else {
871 ret = -ENOSYS;
872 free(node);
873 }
874 break;
875 }
876 case LTTNG_UST_CHANNEL:
877 {
878 void *chan_data;
879 int wakeup_fd;
880
881 len = ustcomm_recv_channel_from_sessiond(sock,
882 &chan_data, lum->u.channel.len,
883 &wakeup_fd);
884 switch (len) {
885 case 0: /* orderly shutdown */
886 ret = 0;
887 goto error;
888 default:
889 if (len == lum->u.channel.len) {
890 DBG("channel data received");
891 break;
892 } else if (len < 0) {
893 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
894 if (len == -ECONNRESET) {
895 ERR("%s remote end closed connection", sock_info->name);
896 ret = len;
897 goto error;
898 }
899 ret = len;
900 goto error;
901 } else {
902 DBG("incorrect channel data message size: %zd", len);
903 ret = -EINVAL;
904 goto error;
905 }
906 }
907 args.channel.chan_data = chan_data;
908 args.channel.wakeup_fd = wakeup_fd;
909 if (ops->cmd)
910 ret = ops->cmd(lum->handle, lum->cmd,
911 (unsigned long) &lum->u,
912 &args, sock_info);
913 else
914 ret = -ENOSYS;
915 break;
916 }
917 case LTTNG_UST_STREAM:
918 {
919 /* Receive shm_fd, wakeup_fd */
920 ret = ustcomm_recv_stream_from_sessiond(sock,
921 NULL,
922 &args.stream.shm_fd,
923 &args.stream.wakeup_fd);
924 if (ret) {
925 goto error;
926 }
927
928 if (ops->cmd)
929 ret = ops->cmd(lum->handle, lum->cmd,
930 (unsigned long) &lum->u,
931 &args, sock_info);
932 else
933 ret = -ENOSYS;
934 break;
935 }
936 case LTTNG_UST_CONTEXT:
937 switch (lum->u.context.ctx) {
938 case LTTNG_UST_CONTEXT_APP_CONTEXT:
939 {
940 char *p;
941 size_t ctxlen, recvlen;
942
943 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
944 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
945 if (ctxlen >= LTTNG_UST_SYM_NAME_LEN) {
946 ERR("Application context string length size is too large: %zu bytes",
947 ctxlen);
948 ret = -EINVAL;
949 goto error;
950 }
951 strcpy(ctxstr, "$app.");
952 p = &ctxstr[strlen("$app.")];
953 recvlen = ctxlen - strlen("$app.");
954 len = ustcomm_recv_unix_sock(sock, p, recvlen);
955 switch (len) {
956 case 0: /* orderly shutdown */
957 ret = 0;
958 goto error;
959 default:
960 if (len == recvlen) {
961 DBG("app context data received");
962 break;
963 } else if (len < 0) {
964 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
965 if (len == -ECONNRESET) {
966 ERR("%s remote end closed connection", sock_info->name);
967 ret = len;
968 goto error;
969 }
970 ret = len;
971 goto error;
972 } else {
973 DBG("incorrect app context data message size: %zd", len);
974 ret = -EINVAL;
975 goto error;
976 }
977 }
978 /* Put : between provider and ctxname. */
979 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
980 args.app_context.ctxname = ctxstr;
981 break;
982 }
983 default:
984 break;
985 }
986 if (ops->cmd) {
987 ret = ops->cmd(lum->handle, lum->cmd,
988 (unsigned long) &lum->u,
989 &args, sock_info);
990 } else {
991 ret = -ENOSYS;
992 }
993 break;
994 default:
995 if (ops->cmd)
996 ret = ops->cmd(lum->handle, lum->cmd,
997 (unsigned long) &lum->u,
998 &args, sock_info);
999 else
1000 ret = -ENOSYS;
1001 break;
1002 }
1003
1004 lur.handle = lum->handle;
1005 lur.cmd = lum->cmd;
1006 lur.ret_val = ret;
1007 if (ret >= 0) {
1008 lur.ret_code = LTTNG_UST_OK;
1009 } else {
1010 /*
1011 * Use -LTTNG_UST_ERR as wildcard for UST internal
1012 * error that are not caused by the transport, except if
1013 * we already have a more precise error message to
1014 * report.
1015 */
1016 if (ret > -LTTNG_UST_ERR) {
1017 /* Translate code to UST error. */
1018 switch (ret) {
1019 case -EEXIST:
1020 lur.ret_code = -LTTNG_UST_ERR_EXIST;
1021 break;
1022 case -EINVAL:
1023 lur.ret_code = -LTTNG_UST_ERR_INVAL;
1024 break;
1025 case -ENOENT:
1026 lur.ret_code = -LTTNG_UST_ERR_NOENT;
1027 break;
1028 case -EPERM:
1029 lur.ret_code = -LTTNG_UST_ERR_PERM;
1030 break;
1031 case -ENOSYS:
1032 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
1033 break;
1034 default:
1035 lur.ret_code = -LTTNG_UST_ERR;
1036 break;
1037 }
1038 } else {
1039 lur.ret_code = ret;
1040 }
1041 }
1042 if (ret >= 0) {
1043 switch (lum->cmd) {
1044 case LTTNG_UST_TRACER_VERSION:
1045 lur.u.version = lum->u.version;
1046 break;
1047 case LTTNG_UST_TRACEPOINT_LIST_GET:
1048 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1049 break;
1050 }
1051 }
1052 DBG("Return value: %d", lur.ret_val);
1053
1054 ust_unlock();
1055
1056 /*
1057 * Performed delayed statedump operations outside of the UST
1058 * lock. We need to take the dynamic loader lock before we take
1059 * the UST lock internally within handle_pending_statedump().
1060 */
1061 handle_pending_statedump(sock_info);
1062
1063 if (ust_lock()) {
1064 ret = -LTTNG_UST_ERR_EXITING;
1065 goto error;
1066 }
1067
1068 ret = send_reply(sock, &lur);
1069 if (ret < 0) {
1070 DBG("error sending reply");
1071 goto error;
1072 }
1073
1074 /*
1075 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1076 * after the reply.
1077 */
1078 if (lur.ret_code == LTTNG_UST_OK) {
1079 switch (lum->cmd) {
1080 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
1081 len = ustcomm_send_unix_sock(sock,
1082 &args.field_list.entry,
1083 sizeof(args.field_list.entry));
1084 if (len < 0) {
1085 ret = len;
1086 goto error;
1087 }
1088 if (len != sizeof(args.field_list.entry)) {
1089 ret = -EINVAL;
1090 goto error;
1091 }
1092 }
1093 }
1094
1095 error:
1096 ust_unlock();
1097
1098 return ret;
1099 }
1100
1101 static
1102 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
1103 {
1104 int ret;
1105
1106 if (sock_info->root_handle != -1) {
1107 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1108 if (ret) {
1109 ERR("Error unref root handle");
1110 }
1111 sock_info->root_handle = -1;
1112 }
1113 sock_info->registration_done = 0;
1114 sock_info->initial_statedump_done = 0;
1115
1116 /*
1117 * wait_shm_mmap, socket and notify socket are used by listener
1118 * threads outside of the ust lock, so we cannot tear them down
1119 * ourselves, because we cannot join on these threads. Leave
1120 * responsibility of cleaning up these resources to the OS
1121 * process exit.
1122 */
1123 if (exiting)
1124 return;
1125
1126 if (sock_info->socket != -1) {
1127 ret = ustcomm_close_unix_sock(sock_info->socket);
1128 if (ret) {
1129 ERR("Error closing ust cmd socket");
1130 }
1131 sock_info->socket = -1;
1132 }
1133 if (sock_info->notify_socket != -1) {
1134 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1135 if (ret) {
1136 ERR("Error closing ust notify socket");
1137 }
1138 sock_info->notify_socket = -1;
1139 }
1140 if (sock_info->wait_shm_mmap) {
1141 long page_size;
1142
1143 page_size = sysconf(_SC_PAGE_SIZE);
1144 if (page_size <= 0) {
1145 if (!page_size) {
1146 errno = EINVAL;
1147 }
1148 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1149 } else {
1150 ret = munmap(sock_info->wait_shm_mmap, page_size);
1151 if (ret) {
1152 ERR("Error unmapping wait shm");
1153 }
1154 }
1155 sock_info->wait_shm_mmap = NULL;
1156 }
1157 }
1158
1159 /*
1160 * Using fork to set umask in the child process (not multi-thread safe).
1161 * We deal with the shm_open vs ftruncate race (happening when the
1162 * sessiond owns the shm and does not let everybody modify it, to ensure
1163 * safety against shm_unlink) by simply letting the mmap fail and
1164 * retrying after a few seconds.
1165 * For global shm, everybody has rw access to it until the sessiond
1166 * starts.
1167 */
1168 static
1169 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
1170 {
1171 int wait_shm_fd, ret;
1172 pid_t pid;
1173
1174 /*
1175 * Try to open read-only.
1176 */
1177 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1178 if (wait_shm_fd >= 0) {
1179 int32_t tmp_read;
1180 ssize_t len;
1181 size_t bytes_read = 0;
1182
1183 /*
1184 * Try to read the fd. If unable to do so, try opening
1185 * it in write mode.
1186 */
1187 do {
1188 len = read(wait_shm_fd,
1189 &((char *) &tmp_read)[bytes_read],
1190 sizeof(tmp_read) - bytes_read);
1191 if (len > 0) {
1192 bytes_read += len;
1193 }
1194 } while ((len < 0 && errno == EINTR)
1195 || (len > 0 && bytes_read < sizeof(tmp_read)));
1196 if (bytes_read != sizeof(tmp_read)) {
1197 ret = close(wait_shm_fd);
1198 if (ret) {
1199 ERR("close wait_shm_fd");
1200 }
1201 goto open_write;
1202 }
1203 goto end;
1204 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1205 /*
1206 * Real-only open did not work, and it's not because the
1207 * entry was not present. It's a failure that prohibits
1208 * using shm.
1209 */
1210 ERR("Error opening shm %s", sock_info->wait_shm_path);
1211 goto end;
1212 }
1213
1214 open_write:
1215 /*
1216 * If the open failed because the file did not exist, or because
1217 * the file was not truncated yet, try creating it ourself.
1218 */
1219 URCU_TLS(lttng_ust_nest_count)++;
1220 pid = fork();
1221 URCU_TLS(lttng_ust_nest_count)--;
1222 if (pid > 0) {
1223 int status;
1224
1225 /*
1226 * Parent: wait for child to return, in which case the
1227 * shared memory map will have been created.
1228 */
1229 pid = wait(&status);
1230 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1231 wait_shm_fd = -1;
1232 goto end;
1233 }
1234 /*
1235 * Try to open read-only again after creation.
1236 */
1237 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1238 if (wait_shm_fd < 0) {
1239 /*
1240 * Real-only open did not work. It's a failure
1241 * that prohibits using shm.
1242 */
1243 ERR("Error opening shm %s", sock_info->wait_shm_path);
1244 goto end;
1245 }
1246 goto end;
1247 } else if (pid == 0) {
1248 int create_mode;
1249
1250 /* Child */
1251 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
1252 if (sock_info->global)
1253 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
1254 /*
1255 * We're alone in a child process, so we can modify the
1256 * process-wide umask.
1257 */
1258 umask(~create_mode);
1259 /*
1260 * Try creating shm (or get rw access).
1261 * We don't do an exclusive open, because we allow other
1262 * processes to create+ftruncate it concurrently.
1263 */
1264 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1265 O_RDWR | O_CREAT, create_mode);
1266 if (wait_shm_fd >= 0) {
1267 ret = ftruncate(wait_shm_fd, mmap_size);
1268 if (ret) {
1269 PERROR("ftruncate");
1270 _exit(EXIT_FAILURE);
1271 }
1272 _exit(EXIT_SUCCESS);
1273 }
1274 /*
1275 * For local shm, we need to have rw access to accept
1276 * opening it: this means the local sessiond will be
1277 * able to wake us up. For global shm, we open it even
1278 * if rw access is not granted, because the root.root
1279 * sessiond will be able to override all rights and wake
1280 * us up.
1281 */
1282 if (!sock_info->global && errno != EACCES) {
1283 ERR("Error opening shm %s", sock_info->wait_shm_path);
1284 _exit(EXIT_FAILURE);
1285 }
1286 /*
1287 * The shm exists, but we cannot open it RW. Report
1288 * success.
1289 */
1290 _exit(EXIT_SUCCESS);
1291 } else {
1292 return -1;
1293 }
1294 end:
1295 if (wait_shm_fd >= 0 && !sock_info->global) {
1296 struct stat statbuf;
1297
1298 /*
1299 * Ensure that our user is the owner of the shm file for
1300 * local shm. If we do not own the file, it means our
1301 * sessiond will not have access to wake us up (there is
1302 * probably a rogue process trying to fake our
1303 * sessiond). Fallback to polling method in this case.
1304 */
1305 ret = fstat(wait_shm_fd, &statbuf);
1306 if (ret) {
1307 PERROR("fstat");
1308 goto error_close;
1309 }
1310 if (statbuf.st_uid != getuid())
1311 goto error_close;
1312 }
1313 return wait_shm_fd;
1314
1315 error_close:
1316 ret = close(wait_shm_fd);
1317 if (ret) {
1318 PERROR("Error closing fd");
1319 }
1320 return -1;
1321 }
1322
1323 static
1324 char *get_map_shm(struct sock_info *sock_info)
1325 {
1326 long page_size;
1327 int wait_shm_fd, ret;
1328 char *wait_shm_mmap;
1329
1330 page_size = sysconf(_SC_PAGE_SIZE);
1331 if (page_size <= 0) {
1332 if (!page_size) {
1333 errno = EINVAL;
1334 }
1335 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1336 goto error;
1337 }
1338
1339 lttng_ust_lock_fd_tracker();
1340 wait_shm_fd = get_wait_shm(sock_info, page_size);
1341 if (wait_shm_fd < 0) {
1342 lttng_ust_unlock_fd_tracker();
1343 goto error;
1344 }
1345
1346 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1347 if (ret < 0) {
1348 ret = close(wait_shm_fd);
1349 if (!ret) {
1350 PERROR("Error closing fd");
1351 }
1352 lttng_ust_unlock_fd_tracker();
1353 goto error;
1354 }
1355
1356 wait_shm_fd = ret;
1357 lttng_ust_unlock_fd_tracker();
1358
1359 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
1360 MAP_SHARED, wait_shm_fd, 0);
1361
1362 /* close shm fd immediately after taking the mmap reference */
1363 lttng_ust_lock_fd_tracker();
1364 ret = close(wait_shm_fd);
1365 if (!ret) {
1366 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1367 } else {
1368 PERROR("Error closing fd");
1369 }
1370 lttng_ust_unlock_fd_tracker();
1371
1372 if (wait_shm_mmap == MAP_FAILED) {
1373 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1374 goto error;
1375 }
1376 return wait_shm_mmap;
1377
1378 error:
1379 return NULL;
1380 }
1381
1382 static
1383 void wait_for_sessiond(struct sock_info *sock_info)
1384 {
1385 /* Use ust_lock to check if we should quit. */
1386 if (ust_lock()) {
1387 goto quit;
1388 }
1389 if (wait_poll_fallback) {
1390 goto error;
1391 }
1392 ust_unlock();
1393
1394 assert(sock_info->wait_shm_mmap);
1395
1396 DBG("Waiting for %s apps sessiond", sock_info->name);
1397 /* Wait for futex wakeup */
1398 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1399 goto end_wait;
1400
1401 while (futex_async((int32_t *) sock_info->wait_shm_mmap,
1402 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1403 switch (errno) {
1404 case EWOULDBLOCK:
1405 /* Value already changed. */
1406 goto end_wait;
1407 case EINTR:
1408 /* Retry if interrupted by signal. */
1409 break; /* Get out of switch. */
1410 case EFAULT:
1411 wait_poll_fallback = 1;
1412 DBG(
1413 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1414 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1415 "Please upgrade your kernel "
1416 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1417 "mainline). LTTng-UST will use polling mode fallback.");
1418 if (ust_debug())
1419 PERROR("futex");
1420 goto end_wait;
1421 }
1422 }
1423 end_wait:
1424 return;
1425
1426 quit:
1427 ust_unlock();
1428 return;
1429
1430 error:
1431 ust_unlock();
1432 return;
1433 }
1434
1435 /*
1436 * This thread does not allocate any resource, except within
1437 * handle_message, within mutex protection. This mutex protects against
1438 * fork and exit.
1439 * The other moment it allocates resources is at socket connection, which
1440 * is also protected by the mutex.
1441 */
1442 static
1443 void *ust_listener_thread(void *arg)
1444 {
1445 struct sock_info *sock_info = arg;
1446 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
1447 long timeout;
1448
1449 lttng_ust_fixup_tls();
1450 /*
1451 * If available, add '-ust' to the end of this thread's
1452 * process name
1453 */
1454 ret = lttng_ust_setustprocname();
1455 if (ret) {
1456 ERR("Unable to set UST process name");
1457 }
1458
1459 /* Restart trying to connect to the session daemon */
1460 restart:
1461 if (prev_connect_failed) {
1462 /* Wait for sessiond availability with pipe */
1463 wait_for_sessiond(sock_info);
1464 if (has_waited) {
1465 has_waited = 0;
1466 /*
1467 * Sleep for 5 seconds before retrying after a
1468 * sequence of failure / wait / failure. This
1469 * deals with a killed or broken session daemon.
1470 */
1471 sleep(5);
1472 } else {
1473 has_waited = 1;
1474 }
1475 prev_connect_failed = 0;
1476 }
1477
1478 if (ust_lock()) {
1479 goto quit;
1480 }
1481
1482 if (sock_info->socket != -1) {
1483 /* FD tracker is updated by ustcomm_close_unix_sock() */
1484 ret = ustcomm_close_unix_sock(sock_info->socket);
1485 if (ret) {
1486 ERR("Error closing %s ust cmd socket",
1487 sock_info->name);
1488 }
1489 sock_info->socket = -1;
1490 }
1491 if (sock_info->notify_socket != -1) {
1492 /* FD tracker is updated by ustcomm_close_unix_sock() */
1493 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1494 if (ret) {
1495 ERR("Error closing %s ust notify socket",
1496 sock_info->name);
1497 }
1498 sock_info->notify_socket = -1;
1499 }
1500
1501
1502 /*
1503 * Register. We need to perform both connect and sending
1504 * registration message before doing the next connect otherwise
1505 * we may reach unix socket connect queue max limits and block
1506 * on the 2nd connect while the session daemon is awaiting the
1507 * first connect registration message.
1508 */
1509 /* Connect cmd socket */
1510 lttng_ust_lock_fd_tracker();
1511 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1512 get_connect_sock_timeout());
1513 if (ret < 0) {
1514 lttng_ust_unlock_fd_tracker();
1515 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1516 prev_connect_failed = 1;
1517
1518 /*
1519 * If we cannot find the sessiond daemon, don't delay
1520 * constructor execution.
1521 */
1522 ret = handle_register_failed(sock_info);
1523 assert(!ret);
1524 ust_unlock();
1525 goto restart;
1526 }
1527 fd = ret;
1528 ret = lttng_ust_add_fd_to_tracker(fd);
1529 if (ret < 0) {
1530 ret = close(fd);
1531 if (ret) {
1532 PERROR("close on sock_info->socket");
1533 }
1534 ret = -1;
1535 lttng_ust_unlock_fd_tracker();
1536 ust_unlock();
1537 goto quit;
1538 }
1539
1540 sock_info->socket = ret;
1541 lttng_ust_unlock_fd_tracker();
1542
1543 ust_unlock();
1544 /*
1545 * Unlock/relock ust lock because connect is blocking (with
1546 * timeout). Don't delay constructors on the ust lock for too
1547 * long.
1548 */
1549 if (ust_lock()) {
1550 goto quit;
1551 }
1552
1553 /*
1554 * Create only one root handle per listener thread for the whole
1555 * process lifetime, so we ensure we get ID which is statically
1556 * assigned to the root handle.
1557 */
1558 if (sock_info->root_handle == -1) {
1559 ret = lttng_abi_create_root_handle();
1560 if (ret < 0) {
1561 ERR("Error creating root handle");
1562 goto quit;
1563 }
1564 sock_info->root_handle = ret;
1565 }
1566
1567 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
1568 if (ret < 0) {
1569 ERR("Error registering to %s ust cmd socket",
1570 sock_info->name);
1571 prev_connect_failed = 1;
1572 /*
1573 * If we cannot register to the sessiond daemon, don't
1574 * delay constructor execution.
1575 */
1576 ret = handle_register_failed(sock_info);
1577 assert(!ret);
1578 ust_unlock();
1579 goto restart;
1580 }
1581
1582 ust_unlock();
1583 /*
1584 * Unlock/relock ust lock because connect is blocking (with
1585 * timeout). Don't delay constructors on the ust lock for too
1586 * long.
1587 */
1588 if (ust_lock()) {
1589 goto quit;
1590 }
1591
1592 /* Connect notify socket */
1593 lttng_ust_lock_fd_tracker();
1594 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1595 get_connect_sock_timeout());
1596 if (ret < 0) {
1597 lttng_ust_unlock_fd_tracker();
1598 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1599 prev_connect_failed = 1;
1600
1601 /*
1602 * If we cannot find the sessiond daemon, don't delay
1603 * constructor execution.
1604 */
1605 ret = handle_register_failed(sock_info);
1606 assert(!ret);
1607 ust_unlock();
1608 goto restart;
1609 }
1610
1611 fd = ret;
1612 ret = lttng_ust_add_fd_to_tracker(fd);
1613 if (ret < 0) {
1614 ret = close(fd);
1615 if (ret) {
1616 PERROR("close on sock_info->notify_socket");
1617 }
1618 ret = -1;
1619 lttng_ust_unlock_fd_tracker();
1620 ust_unlock();
1621 goto quit;
1622 }
1623
1624 sock_info->notify_socket = ret;
1625 lttng_ust_unlock_fd_tracker();
1626
1627 ust_unlock();
1628 /*
1629 * Unlock/relock ust lock because connect is blocking (with
1630 * timeout). Don't delay constructors on the ust lock for too
1631 * long.
1632 */
1633 if (ust_lock()) {
1634 goto quit;
1635 }
1636
1637 timeout = get_notify_sock_timeout();
1638 if (timeout >= 0) {
1639 /*
1640 * Give at least 10ms to sessiond to reply to
1641 * notifications.
1642 */
1643 if (timeout < 10)
1644 timeout = 10;
1645 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1646 timeout);
1647 if (ret < 0) {
1648 WARN("Error setting socket receive timeout");
1649 }
1650 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1651 timeout);
1652 if (ret < 0) {
1653 WARN("Error setting socket send timeout");
1654 }
1655 } else if (timeout < -1) {
1656 WARN("Unsupported timeout value %ld", timeout);
1657 }
1658
1659 ret = register_to_sessiond(sock_info->notify_socket,
1660 USTCTL_SOCKET_NOTIFY);
1661 if (ret < 0) {
1662 ERR("Error registering to %s ust notify socket",
1663 sock_info->name);
1664 prev_connect_failed = 1;
1665 /*
1666 * If we cannot register to the sessiond daemon, don't
1667 * delay constructor execution.
1668 */
1669 ret = handle_register_failed(sock_info);
1670 assert(!ret);
1671 ust_unlock();
1672 goto restart;
1673 }
1674 sock = sock_info->socket;
1675
1676 ust_unlock();
1677
1678 for (;;) {
1679 ssize_t len;
1680 struct ustcomm_ust_msg lum;
1681
1682 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1683 switch (len) {
1684 case 0: /* orderly shutdown */
1685 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
1686 if (ust_lock()) {
1687 goto quit;
1688 }
1689 /*
1690 * Either sessiond has shutdown or refused us by closing the socket.
1691 * In either case, we don't want to delay construction execution,
1692 * and we need to wait before retry.
1693 */
1694 prev_connect_failed = 1;
1695 /*
1696 * If we cannot register to the sessiond daemon, don't
1697 * delay constructor execution.
1698 */
1699 ret = handle_register_failed(sock_info);
1700 assert(!ret);
1701 ust_unlock();
1702 goto end;
1703 case sizeof(lum):
1704 print_cmd(lum.cmd, lum.handle);
1705 ret = handle_message(sock_info, sock, &lum);
1706 if (ret) {
1707 ERR("Error handling message for %s socket",
1708 sock_info->name);
1709 /*
1710 * Close socket if protocol error is
1711 * detected.
1712 */
1713 goto end;
1714 }
1715 continue;
1716 default:
1717 if (len < 0) {
1718 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1719 } else {
1720 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1721 }
1722 if (len == -ECONNRESET) {
1723 DBG("%s remote end closed connection", sock_info->name);
1724 goto end;
1725 }
1726 goto end;
1727 }
1728
1729 }
1730 end:
1731 if (ust_lock()) {
1732 goto quit;
1733 }
1734 /* Cleanup socket handles before trying to reconnect */
1735 lttng_ust_objd_table_owner_cleanup(sock_info);
1736 ust_unlock();
1737 goto restart; /* try to reconnect */
1738
1739 quit:
1740 ust_unlock();
1741
1742 pthread_mutex_lock(&ust_exit_mutex);
1743 sock_info->thread_active = 0;
1744 pthread_mutex_unlock(&ust_exit_mutex);
1745 return NULL;
1746 }
1747
1748 /*
1749 * Weak symbol to call when the ust malloc wrapper is not loaded.
1750 */
1751 __attribute__((weak))
1752 void lttng_ust_malloc_wrapper_init(void)
1753 {
1754 }
1755
1756 /*
1757 * sessiond monitoring thread: monitor presence of global and per-user
1758 * sessiond by polling the application common named pipe.
1759 */
1760 void __attribute__((constructor)) lttng_ust_init(void)
1761 {
1762 struct timespec constructor_timeout;
1763 sigset_t sig_all_blocked, orig_parent_mask;
1764 pthread_attr_t thread_attr;
1765 int timeout_mode;
1766 int ret;
1767
1768 if (uatomic_xchg(&initialized, 1) == 1)
1769 return;
1770
1771 /*
1772 * Fixup interdependency between TLS fixup mutex (which happens
1773 * to be the dynamic linker mutex) and ust_lock, taken within
1774 * the ust lock.
1775 */
1776 lttng_ust_fixup_tls();
1777
1778 lttng_ust_loaded = 1;
1779
1780 /*
1781 * We want precise control over the order in which we construct
1782 * our sub-libraries vs starting to receive commands from
1783 * sessiond (otherwise leading to errors when trying to create
1784 * sessiond before the init functions are completed).
1785 */
1786 init_usterr();
1787 lttng_ust_getenv_init(); /* Needs init_usterr() to be completed. */
1788 init_tracepoint();
1789 lttng_ust_init_fd_tracker();
1790 lttng_ust_clock_init();
1791 lttng_ust_getcpu_init();
1792 lttng_ust_statedump_init();
1793 lttng_ring_buffer_metadata_client_init();
1794 lttng_ring_buffer_client_overwrite_init();
1795 lttng_ring_buffer_client_overwrite_rt_init();
1796 lttng_ring_buffer_client_discard_init();
1797 lttng_ring_buffer_client_discard_rt_init();
1798 lttng_perf_counter_init();
1799 /*
1800 * Invoke ust malloc wrapper init before starting other threads.
1801 */
1802 lttng_ust_malloc_wrapper_init();
1803
1804 timeout_mode = get_constructor_timeout(&constructor_timeout);
1805
1806 get_allow_blocking();
1807
1808 ret = sem_init(&constructor_wait, 0, 0);
1809 if (ret) {
1810 PERROR("sem_init");
1811 }
1812
1813 ret = setup_global_apps();
1814 if (ret) {
1815 assert(global_apps.allowed == 0);
1816 DBG("global apps setup returned %d", ret);
1817 }
1818
1819 ret = setup_local_apps();
1820 if (ret) {
1821 assert(local_apps.allowed == 0);
1822 DBG("local apps setup returned %d", ret);
1823 }
1824
1825 /* A new thread created by pthread_create inherits the signal mask
1826 * from the parent. To avoid any signal being received by the
1827 * listener thread, we block all signals temporarily in the parent,
1828 * while we create the listener thread.
1829 */
1830 sigfillset(&sig_all_blocked);
1831 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1832 if (ret) {
1833 ERR("pthread_sigmask: %s", strerror(ret));
1834 }
1835
1836 ret = pthread_attr_init(&thread_attr);
1837 if (ret) {
1838 ERR("pthread_attr_init: %s", strerror(ret));
1839 }
1840 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1841 if (ret) {
1842 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1843 }
1844
1845 if (global_apps.allowed) {
1846 pthread_mutex_lock(&ust_exit_mutex);
1847 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1848 ust_listener_thread, &global_apps);
1849 if (ret) {
1850 ERR("pthread_create global: %s", strerror(ret));
1851 }
1852 global_apps.thread_active = 1;
1853 pthread_mutex_unlock(&ust_exit_mutex);
1854 } else {
1855 handle_register_done(&global_apps);
1856 }
1857
1858 if (local_apps.allowed) {
1859 pthread_mutex_lock(&ust_exit_mutex);
1860 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
1861 ust_listener_thread, &local_apps);
1862 if (ret) {
1863 ERR("pthread_create local: %s", strerror(ret));
1864 }
1865 local_apps.thread_active = 1;
1866 pthread_mutex_unlock(&ust_exit_mutex);
1867 } else {
1868 handle_register_done(&local_apps);
1869 }
1870 ret = pthread_attr_destroy(&thread_attr);
1871 if (ret) {
1872 ERR("pthread_attr_destroy: %s", strerror(ret));
1873 }
1874
1875 /* Restore original signal mask in parent */
1876 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1877 if (ret) {
1878 ERR("pthread_sigmask: %s", strerror(ret));
1879 }
1880
1881 switch (timeout_mode) {
1882 case 1: /* timeout wait */
1883 do {
1884 ret = sem_timedwait(&constructor_wait,
1885 &constructor_timeout);
1886 } while (ret < 0 && errno == EINTR);
1887 if (ret < 0) {
1888 switch (errno) {
1889 case ETIMEDOUT:
1890 ERR("Timed out waiting for lttng-sessiond");
1891 break;
1892 case EINVAL:
1893 PERROR("sem_timedwait");
1894 break;
1895 default:
1896 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1897 strerror(errno));
1898 }
1899 }
1900 break;
1901 case -1:/* wait forever */
1902 do {
1903 ret = sem_wait(&constructor_wait);
1904 } while (ret < 0 && errno == EINTR);
1905 if (ret < 0) {
1906 switch (errno) {
1907 case EINVAL:
1908 PERROR("sem_wait");
1909 break;
1910 default:
1911 ERR("Unexpected error \"%s\" returned by sem_wait",
1912 strerror(errno));
1913 }
1914 }
1915 break;
1916 case 0: /* no timeout */
1917 break;
1918 }
1919 }
1920
1921 static
1922 void lttng_ust_cleanup(int exiting)
1923 {
1924 cleanup_sock_info(&global_apps, exiting);
1925 cleanup_sock_info(&local_apps, exiting);
1926 local_apps.allowed = 0;
1927 global_apps.allowed = 0;
1928 /*
1929 * The teardown in this function all affect data structures
1930 * accessed under the UST lock by the listener thread. This
1931 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1932 * that none of these threads are accessing this data at this
1933 * point.
1934 */
1935 lttng_ust_abi_exit();
1936 lttng_ust_events_exit();
1937 lttng_perf_counter_exit();
1938 lttng_ring_buffer_client_discard_rt_exit();
1939 lttng_ring_buffer_client_discard_exit();
1940 lttng_ring_buffer_client_overwrite_rt_exit();
1941 lttng_ring_buffer_client_overwrite_exit();
1942 lttng_ring_buffer_metadata_client_exit();
1943 lttng_ust_statedump_destroy();
1944 exit_tracepoint();
1945 if (!exiting) {
1946 /* Reinitialize values for fork */
1947 sem_count = sem_count_initial_value;
1948 lttng_ust_comm_should_quit = 0;
1949 initialized = 0;
1950 }
1951 }
1952
1953 void __attribute__((destructor)) lttng_ust_exit(void)
1954 {
1955 int ret;
1956
1957 /*
1958 * Using pthread_cancel here because:
1959 * A) we don't want to hang application teardown.
1960 * B) the thread is not allocating any resource.
1961 */
1962
1963 /*
1964 * Require the communication thread to quit. Synchronize with
1965 * mutexes to ensure it is not in a mutex critical section when
1966 * pthread_cancel is later called.
1967 */
1968 ust_lock_nocheck();
1969 lttng_ust_comm_should_quit = 1;
1970 ust_unlock();
1971
1972 pthread_mutex_lock(&ust_exit_mutex);
1973 /* cancel threads */
1974 if (global_apps.thread_active) {
1975 ret = pthread_cancel(global_apps.ust_listener);
1976 if (ret) {
1977 ERR("Error cancelling global ust listener thread: %s",
1978 strerror(ret));
1979 } else {
1980 global_apps.thread_active = 0;
1981 }
1982 }
1983 if (local_apps.thread_active) {
1984 ret = pthread_cancel(local_apps.ust_listener);
1985 if (ret) {
1986 ERR("Error cancelling local ust listener thread: %s",
1987 strerror(ret));
1988 } else {
1989 local_apps.thread_active = 0;
1990 }
1991 }
1992 pthread_mutex_unlock(&ust_exit_mutex);
1993
1994 /*
1995 * Do NOT join threads: use of sys_futex makes it impossible to
1996 * join the threads without using async-cancel, but async-cancel
1997 * is delivered by a signal, which could hit the target thread
1998 * anywhere in its code path, including while the ust_lock() is
1999 * held, causing a deadlock for the other thread. Let the OS
2000 * cleanup the threads if there are stalled in a syscall.
2001 */
2002 lttng_ust_cleanup(1);
2003 }
2004
2005 /*
2006 * We exclude the worker threads across fork and clone (except
2007 * CLONE_VM), because these system calls only keep the forking thread
2008 * running in the child. Therefore, we don't want to call fork or clone
2009 * in the middle of an tracepoint or ust tracing state modification.
2010 * Holding this mutex protects these structures across fork and clone.
2011 */
2012 void ust_before_fork(sigset_t *save_sigset)
2013 {
2014 /*
2015 * Disable signals. This is to avoid that the child intervenes
2016 * before it is properly setup for tracing. It is safer to
2017 * disable all signals, because then we know we are not breaking
2018 * anything by restoring the original mask.
2019 */
2020 sigset_t all_sigs;
2021 int ret;
2022
2023 /* Fixup lttng-ust TLS. */
2024 lttng_ust_fixup_tls();
2025
2026 if (URCU_TLS(lttng_ust_nest_count))
2027 return;
2028 /* Disable signals */
2029 sigfillset(&all_sigs);
2030 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
2031 if (ret == -1) {
2032 PERROR("sigprocmask");
2033 }
2034
2035 pthread_mutex_lock(&ust_fork_mutex);
2036
2037 ust_lock_nocheck();
2038 rcu_bp_before_fork();
2039 }
2040
2041 static void ust_after_fork_common(sigset_t *restore_sigset)
2042 {
2043 int ret;
2044
2045 DBG("process %d", getpid());
2046 ust_unlock();
2047
2048 pthread_mutex_unlock(&ust_fork_mutex);
2049
2050 /* Restore signals */
2051 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
2052 if (ret == -1) {
2053 PERROR("sigprocmask");
2054 }
2055 }
2056
2057 void ust_after_fork_parent(sigset_t *restore_sigset)
2058 {
2059 if (URCU_TLS(lttng_ust_nest_count))
2060 return;
2061 DBG("process %d", getpid());
2062 rcu_bp_after_fork_parent();
2063 /* Release mutexes and reenable signals */
2064 ust_after_fork_common(restore_sigset);
2065 }
2066
2067 /*
2068 * After fork, in the child, we need to cleanup all the leftover state,
2069 * except the worker thread which already magically disappeared thanks
2070 * to the weird Linux fork semantics. After tyding up, we call
2071 * lttng_ust_init() again to start over as a new PID.
2072 *
2073 * This is meant for forks() that have tracing in the child between the
2074 * fork and following exec call (if there is any).
2075 */
2076 void ust_after_fork_child(sigset_t *restore_sigset)
2077 {
2078 if (URCU_TLS(lttng_ust_nest_count))
2079 return;
2080 lttng_context_vpid_reset();
2081 lttng_context_vtid_reset();
2082 lttng_context_procname_reset();
2083 DBG("process %d", getpid());
2084 /* Release urcu mutexes */
2085 rcu_bp_after_fork_child();
2086 lttng_ust_cleanup(0);
2087 /* Release mutexes and reenable signals */
2088 ust_after_fork_common(restore_sigset);
2089 lttng_ust_init();
2090 }
2091
2092 void lttng_ust_sockinfo_session_enabled(void *owner)
2093 {
2094 struct sock_info *sock_info = owner;
2095 sock_info->statedump_pending = 1;
2096 }
This page took 0.088427 seconds and 3 git commands to generate.