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