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