Fix: notification timeout logic
[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
55 /*
56 * Has lttng ust comm constructor been called ?
57 */
58 static int initialized;
59
60 /*
61 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
62 * Held when handling a command, also held by fork() to deal with
63 * removal of threads, and by exit path.
64 */
65
66 /* Should the ust comm thread quit ? */
67 static int lttng_ust_comm_should_quit;
68
69 /*
70 * Wait for either of these before continuing to the main
71 * program:
72 * - the register_done message from sessiond daemon
73 * (will let the sessiond daemon enable sessions before main
74 * starts.)
75 * - sessiond daemon is not reachable.
76 * - timeout (ensuring applications are resilient to session
77 * daemon problems).
78 */
79 static sem_t constructor_wait;
80 /*
81 * Doing this for both the global and local sessiond.
82 */
83 static int sem_count = { 2 };
84
85 /*
86 * Counting nesting within lttng-ust. Used to ensure that calling fork()
87 * from liblttng-ust does not execute the pre/post fork handlers.
88 */
89 static DEFINE_URCU_TLS(int, lttng_ust_nest_count);
90
91 /*
92 * Info about socket and associated listener thread.
93 */
94 struct sock_info {
95 const char *name;
96 pthread_t ust_listener; /* listener thread */
97 int root_handle;
98 int constructor_sem_posted;
99 int allowed;
100 int global;
101 int thread_active;
102
103 char sock_path[PATH_MAX];
104 int socket;
105 int notify_socket;
106
107 char wait_shm_path[PATH_MAX];
108 char *wait_shm_mmap;
109 };
110
111 /* Socket from app (connect) to session daemon (listen) for communication */
112 struct sock_info global_apps = {
113 .name = "global",
114 .global = 1,
115
116 .root_handle = -1,
117 .allowed = 1,
118 .thread_active = 0,
119
120 .sock_path = LTTNG_DEFAULT_RUNDIR "/" LTTNG_UST_SOCK_FILENAME,
121 .socket = -1,
122 .notify_socket = -1,
123
124 .wait_shm_path = "/" LTTNG_UST_WAIT_FILENAME,
125 };
126
127 /* TODO: allow global_apps_sock_path override */
128
129 struct sock_info local_apps = {
130 .name = "local",
131 .global = 0,
132 .root_handle = -1,
133 .allowed = 0, /* Check setuid bit first */
134 .thread_active = 0,
135
136 .socket = -1,
137 .notify_socket = -1,
138 };
139
140 static int wait_poll_fallback;
141
142 static const char *cmd_name_mapping[] = {
143 [ LTTNG_UST_RELEASE ] = "Release",
144 [ LTTNG_UST_SESSION ] = "Create Session",
145 [ LTTNG_UST_TRACER_VERSION ] = "Get Tracer Version",
146
147 [ LTTNG_UST_TRACEPOINT_LIST ] = "Create Tracepoint List",
148 [ LTTNG_UST_WAIT_QUIESCENT ] = "Wait for Quiescent State",
149 [ LTTNG_UST_REGISTER_DONE ] = "Registration Done",
150 [ LTTNG_UST_TRACEPOINT_FIELD_LIST ] = "Create Tracepoint Field List",
151
152 /* Session FD commands */
153 [ LTTNG_UST_CHANNEL ] = "Create Channel",
154 [ LTTNG_UST_SESSION_START ] = "Start Session",
155 [ LTTNG_UST_SESSION_STOP ] = "Stop Session",
156
157 /* Channel FD commands */
158 [ LTTNG_UST_STREAM ] = "Create Stream",
159 [ LTTNG_UST_EVENT ] = "Create Event",
160
161 /* Event and Channel FD commands */
162 [ LTTNG_UST_CONTEXT ] = "Create Context",
163 [ LTTNG_UST_FLUSH_BUFFER ] = "Flush Buffer",
164
165 /* Event, Channel and Session commands */
166 [ LTTNG_UST_ENABLE ] = "Enable",
167 [ LTTNG_UST_DISABLE ] = "Disable",
168
169 /* Tracepoint list commands */
170 [ LTTNG_UST_TRACEPOINT_LIST_GET ] = "List Next Tracepoint",
171 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET ] = "List Next Tracepoint Field",
172
173 /* Event FD commands */
174 [ LTTNG_UST_FILTER ] = "Create Filter",
175 };
176
177 static const char *str_timeout;
178 static int got_timeout_env;
179
180 extern void lttng_ring_buffer_client_overwrite_init(void);
181 extern void lttng_ring_buffer_client_discard_init(void);
182 extern void lttng_ring_buffer_metadata_client_init(void);
183 extern void lttng_ring_buffer_client_overwrite_exit(void);
184 extern void lttng_ring_buffer_client_discard_exit(void);
185 extern void lttng_ring_buffer_metadata_client_exit(void);
186
187 /*
188 * Force a read (imply TLS fixup for dlopen) of TLS variables.
189 */
190 static
191 void lttng_fixup_nest_count_tls(void)
192 {
193 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count)));
194 }
195
196 int lttng_get_notify_socket(void *owner)
197 {
198 struct sock_info *info = owner;
199
200 return info->notify_socket;
201 }
202
203 static
204 void print_cmd(int cmd, int handle)
205 {
206 const char *cmd_name = "Unknown";
207
208 if (cmd_name_mapping[cmd]) {
209 cmd_name = cmd_name_mapping[cmd];
210 }
211 DBG("Message Received \"%s\", Handle \"%s\" (%d)", cmd_name,
212 lttng_ust_obj_get_name(handle), handle);
213 }
214
215 static
216 int setup_local_apps(void)
217 {
218 const char *home_dir;
219 uid_t uid;
220
221 uid = getuid();
222 /*
223 * Disallow per-user tracing for setuid binaries.
224 */
225 if (uid != geteuid()) {
226 assert(local_apps.allowed == 0);
227 return 0;
228 }
229 home_dir = (const char *) getenv("HOME");
230 if (!home_dir) {
231 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
232 assert(local_apps.allowed == 0);
233 return -ENOENT;
234 }
235 local_apps.allowed = 1;
236 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
237 home_dir,
238 LTTNG_DEFAULT_HOME_RUNDIR,
239 LTTNG_UST_SOCK_FILENAME);
240 snprintf(local_apps.wait_shm_path, PATH_MAX, "/%s-%u",
241 LTTNG_UST_WAIT_FILENAME,
242 uid);
243 return 0;
244 }
245
246 /*
247 * Get notify_sock timeout, in ms.
248 * -1: don't wait. 0: wait forever. >0: timeout, in ms.
249 */
250 static
251 long get_timeout(void)
252 {
253 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
254
255 if (!got_timeout_env) {
256 str_timeout = getenv("LTTNG_UST_REGISTER_TIMEOUT");
257 got_timeout_env = 1;
258 }
259 if (str_timeout)
260 constructor_delay_ms = strtol(str_timeout, NULL, 10);
261 return constructor_delay_ms;
262 }
263
264 static
265 long get_notify_sock_timeout(void)
266 {
267 return get_timeout();
268 }
269
270 /*
271 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
272 */
273 static
274 int get_constructor_timeout(struct timespec *constructor_timeout)
275 {
276 long constructor_delay_ms;
277 int ret;
278
279 constructor_delay_ms = get_timeout();
280
281 switch (constructor_delay_ms) {
282 case -1:/* fall-through */
283 case 0:
284 return constructor_delay_ms;
285 default:
286 break;
287 }
288
289 /*
290 * If we are unable to find the current time, don't wait.
291 */
292 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
293 if (ret) {
294 return -1;
295 }
296 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
297 constructor_timeout->tv_nsec +=
298 (constructor_delay_ms % 1000UL) * 1000000UL;
299 if (constructor_timeout->tv_nsec >= 1000000000UL) {
300 constructor_timeout->tv_sec++;
301 constructor_timeout->tv_nsec -= 1000000000UL;
302 }
303 return 1;
304 }
305
306 static
307 int register_to_sessiond(int socket, enum ustctl_socket_type type)
308 {
309 return ustcomm_send_reg_msg(socket,
310 type,
311 CAA_BITS_PER_LONG,
312 lttng_alignof(uint8_t) * CHAR_BIT,
313 lttng_alignof(uint16_t) * CHAR_BIT,
314 lttng_alignof(uint32_t) * CHAR_BIT,
315 lttng_alignof(uint64_t) * CHAR_BIT,
316 lttng_alignof(unsigned long) * CHAR_BIT);
317 }
318
319 static
320 int send_reply(int sock, struct ustcomm_ust_reply *lur)
321 {
322 ssize_t len;
323
324 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
325 switch (len) {
326 case sizeof(*lur):
327 DBG("message successfully sent");
328 return 0;
329 default:
330 if (len == -ECONNRESET) {
331 DBG("remote end closed connection");
332 return 0;
333 }
334 if (len < 0)
335 return len;
336 DBG("incorrect message size: %zd", len);
337 return -EINVAL;
338 }
339 }
340
341 static
342 int handle_register_done(struct sock_info *sock_info)
343 {
344 int ret;
345
346 if (sock_info->constructor_sem_posted)
347 return 0;
348 sock_info->constructor_sem_posted = 1;
349 if (uatomic_read(&sem_count) <= 0) {
350 return 0;
351 }
352 ret = uatomic_add_return(&sem_count, -1);
353 if (ret == 0) {
354 ret = sem_post(&constructor_wait);
355 assert(!ret);
356 }
357 return 0;
358 }
359
360 static
361 int handle_message(struct sock_info *sock_info,
362 int sock, struct ustcomm_ust_msg *lum)
363 {
364 int ret = 0;
365 const struct lttng_ust_objd_ops *ops;
366 struct ustcomm_ust_reply lur;
367 union ust_args args;
368 ssize_t len;
369
370 ust_lock();
371
372 memset(&lur, 0, sizeof(lur));
373
374 if (lttng_ust_comm_should_quit) {
375 ret = -LTTNG_UST_ERR_EXITING;
376 goto end;
377 }
378
379 ops = objd_ops(lum->handle);
380 if (!ops) {
381 ret = -ENOENT;
382 goto end;
383 }
384
385 switch (lum->cmd) {
386 case LTTNG_UST_REGISTER_DONE:
387 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
388 ret = handle_register_done(sock_info);
389 else
390 ret = -EINVAL;
391 break;
392 case LTTNG_UST_RELEASE:
393 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
394 ret = -EPERM;
395 else
396 ret = lttng_ust_objd_unref(lum->handle);
397 break;
398 case LTTNG_UST_FILTER:
399 {
400 /* Receive filter data */
401 struct lttng_ust_filter_bytecode_node *bytecode;
402
403 if (lum->u.filter.data_size > FILTER_BYTECODE_MAX_LEN) {
404 ERR("Filter data size is too large: %u bytes",
405 lum->u.filter.data_size);
406 ret = -EINVAL;
407 goto error;
408 }
409
410 if (lum->u.filter.reloc_offset > lum->u.filter.data_size) {
411 ERR("Filter reloc offset %u is not within data",
412 lum->u.filter.reloc_offset);
413 ret = -EINVAL;
414 goto error;
415 }
416
417 bytecode = zmalloc(sizeof(*bytecode) + lum->u.filter.data_size);
418 if (!bytecode) {
419 ret = -ENOMEM;
420 goto error;
421 }
422 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data,
423 lum->u.filter.data_size);
424 switch (len) {
425 case 0: /* orderly shutdown */
426 ret = 0;
427 free(bytecode);
428 goto error;
429 default:
430 if (len == lum->u.filter.data_size) {
431 DBG("filter data received");
432 break;
433 } else if (len < 0) {
434 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
435 if (len == -ECONNRESET) {
436 ERR("%s remote end closed connection", sock_info->name);
437 ret = len;
438 free(bytecode);
439 goto error;
440 }
441 ret = len;
442 goto end;
443 } else {
444 DBG("incorrect filter data message size: %zd", len);
445 ret = -EINVAL;
446 free(bytecode);
447 goto end;
448 }
449 }
450 bytecode->bc.len = lum->u.filter.data_size;
451 bytecode->bc.reloc_offset = lum->u.filter.reloc_offset;
452 bytecode->bc.seqnum = lum->u.filter.seqnum;
453 if (ops->cmd) {
454 ret = ops->cmd(lum->handle, lum->cmd,
455 (unsigned long) bytecode,
456 &args, sock_info);
457 if (ret) {
458 free(bytecode);
459 }
460 /* don't free bytecode if everything went fine. */
461 } else {
462 ret = -ENOSYS;
463 free(bytecode);
464 }
465 break;
466 }
467 case LTTNG_UST_CHANNEL:
468 {
469 void *chan_data;
470
471 len = ustcomm_recv_channel_from_sessiond(sock,
472 &chan_data, lum->u.channel.len);
473 switch (len) {
474 case 0: /* orderly shutdown */
475 ret = 0;
476 goto error;
477 default:
478 if (len == lum->u.channel.len) {
479 DBG("channel data received");
480 break;
481 } else if (len < 0) {
482 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
483 if (len == -ECONNRESET) {
484 ERR("%s remote end closed connection", sock_info->name);
485 ret = len;
486 goto error;
487 }
488 ret = len;
489 goto end;
490 } else {
491 DBG("incorrect channel data message size: %zd", len);
492 ret = -EINVAL;
493 goto end;
494 }
495 }
496 args.channel.chan_data = chan_data;
497 if (ops->cmd)
498 ret = ops->cmd(lum->handle, lum->cmd,
499 (unsigned long) &lum->u,
500 &args, sock_info);
501 else
502 ret = -ENOSYS;
503 break;
504 }
505 case LTTNG_UST_STREAM:
506 {
507 /* Receive shm_fd, wakeup_fd */
508 ret = ustcomm_recv_stream_from_sessiond(sock,
509 &lum->u.stream.len,
510 &args.stream.shm_fd,
511 &args.stream.wakeup_fd);
512 if (ret) {
513 goto end;
514 }
515 if (ops->cmd)
516 ret = ops->cmd(lum->handle, lum->cmd,
517 (unsigned long) &lum->u,
518 &args, sock_info);
519 else
520 ret = -ENOSYS;
521 break;
522 }
523 default:
524 if (ops->cmd)
525 ret = ops->cmd(lum->handle, lum->cmd,
526 (unsigned long) &lum->u,
527 &args, sock_info);
528 else
529 ret = -ENOSYS;
530 break;
531 }
532
533 end:
534 lur.handle = lum->handle;
535 lur.cmd = lum->cmd;
536 lur.ret_val = ret;
537 if (ret >= 0) {
538 lur.ret_code = LTTNG_UST_OK;
539 } else {
540 /*
541 * Use -LTTNG_UST_ERR as wildcard for UST internal
542 * error that are not caused by the transport, except if
543 * we already have a more precise error message to
544 * report.
545 */
546 if (ret > -LTTNG_UST_ERR) {
547 /* Translate code to UST error. */
548 switch (ret) {
549 case -EEXIST:
550 lur.ret_code = -LTTNG_UST_ERR_EXIST;
551 break;
552 case -EINVAL:
553 lur.ret_code = -LTTNG_UST_ERR_INVAL;
554 break;
555 case -ENOENT:
556 lur.ret_code = -LTTNG_UST_ERR_NOENT;
557 break;
558 case -EPERM:
559 lur.ret_code = -LTTNG_UST_ERR_PERM;
560 break;
561 case -ENOSYS:
562 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
563 break;
564 default:
565 lur.ret_code = -LTTNG_UST_ERR;
566 break;
567 }
568 } else {
569 lur.ret_code = ret;
570 }
571 }
572 if (ret >= 0) {
573 switch (lum->cmd) {
574 case LTTNG_UST_TRACER_VERSION:
575 lur.u.version = lum->u.version;
576 break;
577 case LTTNG_UST_TRACEPOINT_LIST_GET:
578 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
579 break;
580 }
581 }
582 DBG("Return value: %d", lur.ret_val);
583 ret = send_reply(sock, &lur);
584 if (ret < 0) {
585 DBG("error sending reply");
586 goto error;
587 }
588
589 /*
590 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
591 * after the reply.
592 */
593 if (lur.ret_code == LTTNG_UST_OK) {
594 switch (lum->cmd) {
595 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
596 len = ustcomm_send_unix_sock(sock,
597 &args.field_list.entry,
598 sizeof(args.field_list.entry));
599 if (len < 0) {
600 ret = len;
601 goto error;
602 }
603 if (len != sizeof(args.field_list.entry)) {
604 ret = -EINVAL;
605 goto error;
606 }
607 }
608 }
609
610 error:
611 ust_unlock();
612 return ret;
613 }
614
615 static
616 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
617 {
618 int ret;
619
620 if (sock_info->socket != -1) {
621 ret = ustcomm_close_unix_sock(sock_info->socket);
622 if (ret) {
623 ERR("Error closing ust cmd socket");
624 }
625 sock_info->socket = -1;
626 }
627 if (sock_info->notify_socket != -1) {
628 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
629 if (ret) {
630 ERR("Error closing ust notify socket");
631 }
632 sock_info->notify_socket = -1;
633 }
634 if (sock_info->root_handle != -1) {
635 ret = lttng_ust_objd_unref(sock_info->root_handle);
636 if (ret) {
637 ERR("Error unref root handle");
638 }
639 sock_info->root_handle = -1;
640 }
641 sock_info->constructor_sem_posted = 0;
642 /*
643 * wait_shm_mmap is used by listener threads outside of the
644 * ust lock, so we cannot tear it down ourselves, because we
645 * cannot join on these threads. Leave this task to the OS
646 * process exit.
647 */
648 if (!exiting && sock_info->wait_shm_mmap) {
649 ret = munmap(sock_info->wait_shm_mmap, sysconf(_SC_PAGE_SIZE));
650 if (ret) {
651 ERR("Error unmapping wait shm");
652 }
653 sock_info->wait_shm_mmap = NULL;
654 }
655 }
656
657 /*
658 * Using fork to set umask in the child process (not multi-thread safe).
659 * We deal with the shm_open vs ftruncate race (happening when the
660 * sessiond owns the shm and does not let everybody modify it, to ensure
661 * safety against shm_unlink) by simply letting the mmap fail and
662 * retrying after a few seconds.
663 * For global shm, everybody has rw access to it until the sessiond
664 * starts.
665 */
666 static
667 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
668 {
669 int wait_shm_fd, ret;
670 pid_t pid;
671
672 /*
673 * Try to open read-only.
674 */
675 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
676 if (wait_shm_fd >= 0) {
677 goto end;
678 } else if (wait_shm_fd < 0 && errno != ENOENT) {
679 /*
680 * Real-only open did not work, and it's not because the
681 * entry was not present. It's a failure that prohibits
682 * using shm.
683 */
684 ERR("Error opening shm %s", sock_info->wait_shm_path);
685 goto end;
686 }
687 /*
688 * If the open failed because the file did not exist, try
689 * creating it ourself.
690 */
691 URCU_TLS(lttng_ust_nest_count)++;
692 pid = fork();
693 URCU_TLS(lttng_ust_nest_count)--;
694 if (pid > 0) {
695 int status;
696
697 /*
698 * Parent: wait for child to return, in which case the
699 * shared memory map will have been created.
700 */
701 pid = wait(&status);
702 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
703 wait_shm_fd = -1;
704 goto end;
705 }
706 /*
707 * Try to open read-only again after creation.
708 */
709 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
710 if (wait_shm_fd < 0) {
711 /*
712 * Real-only open did not work. It's a failure
713 * that prohibits using shm.
714 */
715 ERR("Error opening shm %s", sock_info->wait_shm_path);
716 goto end;
717 }
718 goto end;
719 } else if (pid == 0) {
720 int create_mode;
721
722 /* Child */
723 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
724 if (sock_info->global)
725 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
726 /*
727 * We're alone in a child process, so we can modify the
728 * process-wide umask.
729 */
730 umask(~create_mode);
731 /*
732 * Try creating shm (or get rw access).
733 * We don't do an exclusive open, because we allow other
734 * processes to create+ftruncate it concurrently.
735 */
736 wait_shm_fd = shm_open(sock_info->wait_shm_path,
737 O_RDWR | O_CREAT, create_mode);
738 if (wait_shm_fd >= 0) {
739 ret = ftruncate(wait_shm_fd, mmap_size);
740 if (ret) {
741 PERROR("ftruncate");
742 _exit(EXIT_FAILURE);
743 }
744 _exit(EXIT_SUCCESS);
745 }
746 /*
747 * For local shm, we need to have rw access to accept
748 * opening it: this means the local sessiond will be
749 * able to wake us up. For global shm, we open it even
750 * if rw access is not granted, because the root.root
751 * sessiond will be able to override all rights and wake
752 * us up.
753 */
754 if (!sock_info->global && errno != EACCES) {
755 ERR("Error opening shm %s", sock_info->wait_shm_path);
756 _exit(EXIT_FAILURE);
757 }
758 /*
759 * The shm exists, but we cannot open it RW. Report
760 * success.
761 */
762 _exit(EXIT_SUCCESS);
763 } else {
764 return -1;
765 }
766 end:
767 if (wait_shm_fd >= 0 && !sock_info->global) {
768 struct stat statbuf;
769
770 /*
771 * Ensure that our user is the owner of the shm file for
772 * local shm. If we do not own the file, it means our
773 * sessiond will not have access to wake us up (there is
774 * probably a rogue process trying to fake our
775 * sessiond). Fallback to polling method in this case.
776 */
777 ret = fstat(wait_shm_fd, &statbuf);
778 if (ret) {
779 PERROR("fstat");
780 goto error_close;
781 }
782 if (statbuf.st_uid != getuid())
783 goto error_close;
784 }
785 return wait_shm_fd;
786
787 error_close:
788 ret = close(wait_shm_fd);
789 if (ret) {
790 PERROR("Error closing fd");
791 }
792 return -1;
793 }
794
795 static
796 char *get_map_shm(struct sock_info *sock_info)
797 {
798 size_t mmap_size = sysconf(_SC_PAGE_SIZE);
799 int wait_shm_fd, ret;
800 char *wait_shm_mmap;
801
802 wait_shm_fd = get_wait_shm(sock_info, mmap_size);
803 if (wait_shm_fd < 0) {
804 goto error;
805 }
806 wait_shm_mmap = mmap(NULL, mmap_size, PROT_READ,
807 MAP_SHARED, wait_shm_fd, 0);
808 /* close shm fd immediately after taking the mmap reference */
809 ret = close(wait_shm_fd);
810 if (ret) {
811 PERROR("Error closing fd");
812 }
813 if (wait_shm_mmap == MAP_FAILED) {
814 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
815 goto error;
816 }
817 return wait_shm_mmap;
818
819 error:
820 return NULL;
821 }
822
823 static
824 void wait_for_sessiond(struct sock_info *sock_info)
825 {
826 int ret;
827
828 ust_lock();
829 if (lttng_ust_comm_should_quit) {
830 goto quit;
831 }
832 if (wait_poll_fallback) {
833 goto error;
834 }
835 if (!sock_info->wait_shm_mmap) {
836 sock_info->wait_shm_mmap = get_map_shm(sock_info);
837 if (!sock_info->wait_shm_mmap)
838 goto error;
839 }
840 ust_unlock();
841
842 DBG("Waiting for %s apps sessiond", sock_info->name);
843 /* Wait for futex wakeup */
844 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap) == 0) {
845 ret = futex_async((int32_t *) sock_info->wait_shm_mmap,
846 FUTEX_WAIT, 0, NULL, NULL, 0);
847 if (ret < 0) {
848 if (errno == EFAULT) {
849 wait_poll_fallback = 1;
850 DBG(
851 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
852 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
853 "Please upgrade your kernel "
854 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
855 "mainline). LTTng-UST will use polling mode fallback.");
856 if (ust_debug())
857 PERROR("futex");
858 }
859 }
860 }
861 return;
862
863 quit:
864 ust_unlock();
865 return;
866
867 error:
868 ust_unlock();
869 return;
870 }
871
872 /*
873 * This thread does not allocate any resource, except within
874 * handle_message, within mutex protection. This mutex protects against
875 * fork and exit.
876 * The other moment it allocates resources is at socket connection, which
877 * is also protected by the mutex.
878 */
879 static
880 void *ust_listener_thread(void *arg)
881 {
882 struct sock_info *sock_info = arg;
883 int sock, ret, prev_connect_failed = 0, has_waited = 0;
884 int open_sock[2];
885 int i;
886 long timeout;
887
888 /* Restart trying to connect to the session daemon */
889 restart:
890 if (prev_connect_failed) {
891 /* Wait for sessiond availability with pipe */
892 wait_for_sessiond(sock_info);
893 if (has_waited) {
894 has_waited = 0;
895 /*
896 * Sleep for 5 seconds before retrying after a
897 * sequence of failure / wait / failure. This
898 * deals with a killed or broken session daemon.
899 */
900 sleep(5);
901 }
902 has_waited = 1;
903 prev_connect_failed = 0;
904 }
905 ust_lock();
906
907 if (lttng_ust_comm_should_quit) {
908 goto quit;
909 }
910
911 if (sock_info->socket != -1) {
912 ret = ustcomm_close_unix_sock(sock_info->socket);
913 if (ret) {
914 ERR("Error closing %s ust cmd socket",
915 sock_info->name);
916 }
917 sock_info->socket = -1;
918 }
919 if (sock_info->notify_socket != -1) {
920 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
921 if (ret) {
922 ERR("Error closing %s ust notify socket",
923 sock_info->name);
924 }
925 sock_info->notify_socket = -1;
926 }
927
928 /* Register */
929 for (i = 0; i < 2; i++) {
930 ret = ustcomm_connect_unix_sock(sock_info->sock_path);
931 if (ret < 0) {
932 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
933 prev_connect_failed = 1;
934 /*
935 * If we cannot find the sessiond daemon, don't delay
936 * constructor execution.
937 */
938 ret = handle_register_done(sock_info);
939 assert(!ret);
940 ust_unlock();
941 goto restart;
942 }
943 open_sock[i] = ret;
944 }
945
946 sock_info->socket = open_sock[0];
947 sock_info->notify_socket = open_sock[1];
948
949 timeout = get_notify_sock_timeout();
950 if (timeout >= 0) {
951 /*
952 * Give at least 10ms to sessiond to reply to
953 * notifications.
954 */
955 if (timeout < 10)
956 timeout = 10;
957 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
958 timeout);
959 if (ret < 0) {
960 WARN("Error setting socket receive timeout");
961 }
962 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
963 timeout);
964 if (ret < 0) {
965 WARN("Error setting socket send timeout");
966 }
967 } else if (timeout < -1) {
968 WARN("Unsuppoorted timeout value %ld", timeout);
969 }
970
971 /*
972 * Create only one root handle per listener thread for the whole
973 * process lifetime, so we ensure we get ID which is statically
974 * assigned to the root handle.
975 */
976 if (sock_info->root_handle == -1) {
977 ret = lttng_abi_create_root_handle();
978 if (ret < 0) {
979 ERR("Error creating root handle");
980 goto quit;
981 }
982 sock_info->root_handle = ret;
983 }
984
985 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
986 if (ret < 0) {
987 ERR("Error registering to %s ust cmd socket",
988 sock_info->name);
989 prev_connect_failed = 1;
990 /*
991 * If we cannot register to the sessiond daemon, don't
992 * delay constructor execution.
993 */
994 ret = handle_register_done(sock_info);
995 assert(!ret);
996 ust_unlock();
997 goto restart;
998 }
999 ret = register_to_sessiond(sock_info->notify_socket,
1000 USTCTL_SOCKET_NOTIFY);
1001 if (ret < 0) {
1002 ERR("Error registering to %s ust notify socket",
1003 sock_info->name);
1004 prev_connect_failed = 1;
1005 /*
1006 * If we cannot register to the sessiond daemon, don't
1007 * delay constructor execution.
1008 */
1009 ret = handle_register_done(sock_info);
1010 assert(!ret);
1011 ust_unlock();
1012 goto restart;
1013 }
1014 sock = sock_info->socket;
1015
1016 ust_unlock();
1017
1018 for (;;) {
1019 ssize_t len;
1020 struct ustcomm_ust_msg lum;
1021
1022 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1023 switch (len) {
1024 case 0: /* orderly shutdown */
1025 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
1026 ust_lock();
1027 if (lttng_ust_comm_should_quit) {
1028 goto quit;
1029 }
1030 /*
1031 * Either sessiond has shutdown or refused us by closing the socket.
1032 * In either case, we don't want to delay construction execution,
1033 * and we need to wait before retry.
1034 */
1035 prev_connect_failed = 1;
1036 /*
1037 * If we cannot register to the sessiond daemon, don't
1038 * delay constructor execution.
1039 */
1040 ret = handle_register_done(sock_info);
1041 assert(!ret);
1042 ust_unlock();
1043 goto end;
1044 case sizeof(lum):
1045 print_cmd(lum.cmd, lum.handle);
1046 ret = handle_message(sock_info, sock, &lum);
1047 if (ret) {
1048 ERR("Error handling message for %s socket", sock_info->name);
1049 }
1050 continue;
1051 default:
1052 if (len < 0) {
1053 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1054 } else {
1055 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1056 }
1057 if (len == -ECONNRESET) {
1058 DBG("%s remote end closed connection", sock_info->name);
1059 goto end;
1060 }
1061 goto end;
1062 }
1063
1064 }
1065 end:
1066 ust_lock();
1067 if (lttng_ust_comm_should_quit) {
1068 goto quit;
1069 }
1070 /* Cleanup socket handles before trying to reconnect */
1071 lttng_ust_objd_table_owner_cleanup(sock_info);
1072 ust_unlock();
1073 goto restart; /* try to reconnect */
1074
1075 quit:
1076 sock_info->thread_active = 0;
1077 ust_unlock();
1078 return NULL;
1079 }
1080
1081 /*
1082 * sessiond monitoring thread: monitor presence of global and per-user
1083 * sessiond by polling the application common named pipe.
1084 */
1085 void __attribute__((constructor)) lttng_ust_init(void)
1086 {
1087 struct timespec constructor_timeout;
1088 sigset_t sig_all_blocked, orig_parent_mask;
1089 pthread_attr_t thread_attr;
1090 int timeout_mode;
1091 int ret;
1092
1093 if (uatomic_xchg(&initialized, 1) == 1)
1094 return;
1095
1096 /*
1097 * Fixup interdependency between TLS fixup mutex (which happens
1098 * to be the dynamic linker mutex) and ust_lock, taken within
1099 * the ust lock.
1100 */
1101 lttng_fixup_ringbuffer_tls();
1102 lttng_fixup_vtid_tls();
1103 lttng_fixup_nest_count_tls();
1104 lttng_fixup_procname_tls();
1105
1106 /*
1107 * We want precise control over the order in which we construct
1108 * our sub-libraries vs starting to receive commands from
1109 * sessiond (otherwise leading to errors when trying to create
1110 * sessiond before the init functions are completed).
1111 */
1112 init_usterr();
1113 init_tracepoint();
1114 lttng_ring_buffer_metadata_client_init();
1115 lttng_ring_buffer_client_overwrite_init();
1116 lttng_ring_buffer_client_discard_init();
1117
1118 timeout_mode = get_constructor_timeout(&constructor_timeout);
1119
1120 ret = sem_init(&constructor_wait, 0, 0);
1121 assert(!ret);
1122
1123 ret = setup_local_apps();
1124 if (ret) {
1125 DBG("local apps setup returned %d", ret);
1126 }
1127
1128 /* A new thread created by pthread_create inherits the signal mask
1129 * from the parent. To avoid any signal being received by the
1130 * listener thread, we block all signals temporarily in the parent,
1131 * while we create the listener thread.
1132 */
1133 sigfillset(&sig_all_blocked);
1134 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1135 if (ret) {
1136 ERR("pthread_sigmask: %s", strerror(ret));
1137 }
1138
1139 ret = pthread_attr_init(&thread_attr);
1140 if (ret) {
1141 ERR("pthread_attr_init: %s", strerror(ret));
1142 }
1143 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1144 if (ret) {
1145 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1146 }
1147
1148 ust_lock();
1149 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1150 ust_listener_thread, &global_apps);
1151 if (ret) {
1152 ERR("pthread_create global: %s", strerror(ret));
1153 }
1154 global_apps.thread_active = 1;
1155 ust_unlock();
1156
1157 if (local_apps.allowed) {
1158 ust_lock();
1159 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
1160 ust_listener_thread, &local_apps);
1161 if (ret) {
1162 ERR("pthread_create local: %s", strerror(ret));
1163 }
1164 local_apps.thread_active = 1;
1165 ust_unlock();
1166 } else {
1167 handle_register_done(&local_apps);
1168 }
1169 ret = pthread_attr_destroy(&thread_attr);
1170 if (ret) {
1171 ERR("pthread_attr_destroy: %s", strerror(ret));
1172 }
1173
1174 /* Restore original signal mask in parent */
1175 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1176 if (ret) {
1177 ERR("pthread_sigmask: %s", strerror(ret));
1178 }
1179
1180 switch (timeout_mode) {
1181 case 1: /* timeout wait */
1182 do {
1183 ret = sem_timedwait(&constructor_wait,
1184 &constructor_timeout);
1185 } while (ret < 0 && errno == EINTR);
1186 if (ret < 0 && errno == ETIMEDOUT) {
1187 ERR("Timed out waiting for lttng-sessiond");
1188 } else {
1189 assert(!ret);
1190 }
1191 break;
1192 case -1:/* wait forever */
1193 do {
1194 ret = sem_wait(&constructor_wait);
1195 } while (ret < 0 && errno == EINTR);
1196 assert(!ret);
1197 break;
1198 case 0: /* no timeout */
1199 break;
1200 }
1201 }
1202
1203 static
1204 void lttng_ust_cleanup(int exiting)
1205 {
1206 cleanup_sock_info(&global_apps, exiting);
1207 if (local_apps.allowed) {
1208 cleanup_sock_info(&local_apps, exiting);
1209 }
1210 /*
1211 * The teardown in this function all affect data structures
1212 * accessed under the UST lock by the listener thread. This
1213 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1214 * that none of these threads are accessing this data at this
1215 * point.
1216 */
1217 lttng_ust_abi_exit();
1218 lttng_ust_events_exit();
1219 lttng_ring_buffer_client_discard_exit();
1220 lttng_ring_buffer_client_overwrite_exit();
1221 lttng_ring_buffer_metadata_client_exit();
1222 exit_tracepoint();
1223 if (!exiting) {
1224 /* Reinitialize values for fork */
1225 sem_count = 2;
1226 lttng_ust_comm_should_quit = 0;
1227 initialized = 0;
1228 }
1229 }
1230
1231 void __attribute__((destructor)) lttng_ust_exit(void)
1232 {
1233 int ret;
1234
1235 /*
1236 * Using pthread_cancel here because:
1237 * A) we don't want to hang application teardown.
1238 * B) the thread is not allocating any resource.
1239 */
1240
1241 /*
1242 * Require the communication thread to quit. Synchronize with
1243 * mutexes to ensure it is not in a mutex critical section when
1244 * pthread_cancel is later called.
1245 */
1246 ust_lock();
1247 lttng_ust_comm_should_quit = 1;
1248
1249 /* cancel threads */
1250 if (global_apps.thread_active) {
1251 ret = pthread_cancel(global_apps.ust_listener);
1252 if (ret) {
1253 ERR("Error cancelling global ust listener thread: %s",
1254 strerror(ret));
1255 } else {
1256 global_apps.thread_active = 0;
1257 }
1258 }
1259 if (local_apps.thread_active) {
1260 ret = pthread_cancel(local_apps.ust_listener);
1261 if (ret) {
1262 ERR("Error cancelling local ust listener thread: %s",
1263 strerror(ret));
1264 } else {
1265 local_apps.thread_active = 0;
1266 }
1267 }
1268 ust_unlock();
1269
1270 /*
1271 * Do NOT join threads: use of sys_futex makes it impossible to
1272 * join the threads without using async-cancel, but async-cancel
1273 * is delivered by a signal, which could hit the target thread
1274 * anywhere in its code path, including while the ust_lock() is
1275 * held, causing a deadlock for the other thread. Let the OS
1276 * cleanup the threads if there are stalled in a syscall.
1277 */
1278 lttng_ust_cleanup(1);
1279 }
1280
1281 /*
1282 * We exclude the worker threads across fork and clone (except
1283 * CLONE_VM), because these system calls only keep the forking thread
1284 * running in the child. Therefore, we don't want to call fork or clone
1285 * in the middle of an tracepoint or ust tracing state modification.
1286 * Holding this mutex protects these structures across fork and clone.
1287 */
1288 void ust_before_fork(sigset_t *save_sigset)
1289 {
1290 /*
1291 * Disable signals. This is to avoid that the child intervenes
1292 * before it is properly setup for tracing. It is safer to
1293 * disable all signals, because then we know we are not breaking
1294 * anything by restoring the original mask.
1295 */
1296 sigset_t all_sigs;
1297 int ret;
1298
1299 if (URCU_TLS(lttng_ust_nest_count))
1300 return;
1301 /* Disable signals */
1302 sigfillset(&all_sigs);
1303 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
1304 if (ret == -1) {
1305 PERROR("sigprocmask");
1306 }
1307 ust_lock();
1308 rcu_bp_before_fork();
1309 }
1310
1311 static void ust_after_fork_common(sigset_t *restore_sigset)
1312 {
1313 int ret;
1314
1315 DBG("process %d", getpid());
1316 ust_unlock();
1317 /* Restore signals */
1318 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
1319 if (ret == -1) {
1320 PERROR("sigprocmask");
1321 }
1322 }
1323
1324 void ust_after_fork_parent(sigset_t *restore_sigset)
1325 {
1326 if (URCU_TLS(lttng_ust_nest_count))
1327 return;
1328 DBG("process %d", getpid());
1329 rcu_bp_after_fork_parent();
1330 /* Release mutexes and reenable signals */
1331 ust_after_fork_common(restore_sigset);
1332 }
1333
1334 /*
1335 * After fork, in the child, we need to cleanup all the leftover state,
1336 * except the worker thread which already magically disappeared thanks
1337 * to the weird Linux fork semantics. After tyding up, we call
1338 * lttng_ust_init() again to start over as a new PID.
1339 *
1340 * This is meant for forks() that have tracing in the child between the
1341 * fork and following exec call (if there is any).
1342 */
1343 void ust_after_fork_child(sigset_t *restore_sigset)
1344 {
1345 if (URCU_TLS(lttng_ust_nest_count))
1346 return;
1347 DBG("process %d", getpid());
1348 /* Release urcu mutexes */
1349 rcu_bp_after_fork_child();
1350 lttng_ust_cleanup(0);
1351 lttng_context_vtid_reset();
1352 /* Release mutexes and reenable signals */
1353 ust_after_fork_common(restore_sigset);
1354 lttng_ust_init();
1355 }
This page took 0.061528 seconds and 5 git commands to generate.