Fix: Only notify socket should have timeout/nonblock
[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 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
952 timeout);
953 if (ret < 0) {
954 WARN("Error setting socket receive timeout");
955 }
956 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
957 timeout);
958 if (ret < 0) {
959 WARN("Error setting socket send timeout");
960 }
961 } else if (timeout == -1) {
962 ret = fcntl(sock_info->notify_socket, F_SETFL, O_NONBLOCK);
963 if (ret < 0) {
964 WARN("Error setting socket to non-blocking");
965 }
966 } else {
967 if (timeout != 0) {
968 WARN("Unsuppoorted timeout value %ld", timeout);
969 }
970 }
971
972 /*
973 * Create only one root handle per listener thread for the whole
974 * process lifetime, so we ensure we get ID which is statically
975 * assigned to the root handle.
976 */
977 if (sock_info->root_handle == -1) {
978 ret = lttng_abi_create_root_handle();
979 if (ret < 0) {
980 ERR("Error creating root handle");
981 goto quit;
982 }
983 sock_info->root_handle = ret;
984 }
985
986 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
987 if (ret < 0) {
988 ERR("Error registering to %s ust cmd socket",
989 sock_info->name);
990 prev_connect_failed = 1;
991 /*
992 * If we cannot register to the sessiond daemon, don't
993 * delay constructor execution.
994 */
995 ret = handle_register_done(sock_info);
996 assert(!ret);
997 ust_unlock();
998 goto restart;
999 }
1000 ret = register_to_sessiond(sock_info->notify_socket,
1001 USTCTL_SOCKET_NOTIFY);
1002 if (ret < 0) {
1003 ERR("Error registering to %s ust notify socket",
1004 sock_info->name);
1005 prev_connect_failed = 1;
1006 /*
1007 * If we cannot register to the sessiond daemon, don't
1008 * delay constructor execution.
1009 */
1010 ret = handle_register_done(sock_info);
1011 assert(!ret);
1012 ust_unlock();
1013 goto restart;
1014 }
1015 sock = sock_info->socket;
1016
1017 ust_unlock();
1018
1019 for (;;) {
1020 ssize_t len;
1021 struct ustcomm_ust_msg lum;
1022
1023 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1024 switch (len) {
1025 case 0: /* orderly shutdown */
1026 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
1027 ust_lock();
1028 if (lttng_ust_comm_should_quit) {
1029 goto quit;
1030 }
1031 /*
1032 * Either sessiond has shutdown or refused us by closing the socket.
1033 * In either case, we don't want to delay construction execution,
1034 * and we need to wait before retry.
1035 */
1036 prev_connect_failed = 1;
1037 /*
1038 * If we cannot register to the sessiond daemon, don't
1039 * delay constructor execution.
1040 */
1041 ret = handle_register_done(sock_info);
1042 assert(!ret);
1043 ust_unlock();
1044 goto end;
1045 case sizeof(lum):
1046 print_cmd(lum.cmd, lum.handle);
1047 ret = handle_message(sock_info, sock, &lum);
1048 if (ret) {
1049 ERR("Error handling message for %s socket", sock_info->name);
1050 }
1051 continue;
1052 default:
1053 if (len < 0) {
1054 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1055 } else {
1056 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1057 }
1058 if (len == -ECONNRESET) {
1059 DBG("%s remote end closed connection", sock_info->name);
1060 goto end;
1061 }
1062 goto end;
1063 }
1064
1065 }
1066 end:
1067 ust_lock();
1068 if (lttng_ust_comm_should_quit) {
1069 goto quit;
1070 }
1071 /* Cleanup socket handles before trying to reconnect */
1072 lttng_ust_objd_table_owner_cleanup(sock_info);
1073 ust_unlock();
1074 goto restart; /* try to reconnect */
1075
1076 quit:
1077 sock_info->thread_active = 0;
1078 ust_unlock();
1079 return NULL;
1080 }
1081
1082 /*
1083 * sessiond monitoring thread: monitor presence of global and per-user
1084 * sessiond by polling the application common named pipe.
1085 */
1086 void __attribute__((constructor)) lttng_ust_init(void)
1087 {
1088 struct timespec constructor_timeout;
1089 sigset_t sig_all_blocked, orig_parent_mask;
1090 pthread_attr_t thread_attr;
1091 int timeout_mode;
1092 int ret;
1093
1094 if (uatomic_xchg(&initialized, 1) == 1)
1095 return;
1096
1097 /*
1098 * Fixup interdependency between TLS fixup mutex (which happens
1099 * to be the dynamic linker mutex) and ust_lock, taken within
1100 * the ust lock.
1101 */
1102 lttng_fixup_ringbuffer_tls();
1103 lttng_fixup_vtid_tls();
1104 lttng_fixup_nest_count_tls();
1105 lttng_fixup_procname_tls();
1106
1107 /*
1108 * We want precise control over the order in which we construct
1109 * our sub-libraries vs starting to receive commands from
1110 * sessiond (otherwise leading to errors when trying to create
1111 * sessiond before the init functions are completed).
1112 */
1113 init_usterr();
1114 init_tracepoint();
1115 lttng_ring_buffer_metadata_client_init();
1116 lttng_ring_buffer_client_overwrite_init();
1117 lttng_ring_buffer_client_discard_init();
1118
1119 timeout_mode = get_constructor_timeout(&constructor_timeout);
1120
1121 ret = sem_init(&constructor_wait, 0, 0);
1122 assert(!ret);
1123
1124 ret = setup_local_apps();
1125 if (ret) {
1126 DBG("local apps setup returned %d", ret);
1127 }
1128
1129 /* A new thread created by pthread_create inherits the signal mask
1130 * from the parent. To avoid any signal being received by the
1131 * listener thread, we block all signals temporarily in the parent,
1132 * while we create the listener thread.
1133 */
1134 sigfillset(&sig_all_blocked);
1135 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1136 if (ret) {
1137 ERR("pthread_sigmask: %s", strerror(ret));
1138 }
1139
1140 ret = pthread_attr_init(&thread_attr);
1141 if (ret) {
1142 ERR("pthread_attr_init: %s", strerror(ret));
1143 }
1144 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1145 if (ret) {
1146 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1147 }
1148
1149 ust_lock();
1150 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1151 ust_listener_thread, &global_apps);
1152 if (ret) {
1153 ERR("pthread_create global: %s", strerror(ret));
1154 }
1155 global_apps.thread_active = 1;
1156 ust_unlock();
1157
1158 if (local_apps.allowed) {
1159 ust_lock();
1160 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
1161 ust_listener_thread, &local_apps);
1162 if (ret) {
1163 ERR("pthread_create local: %s", strerror(ret));
1164 }
1165 local_apps.thread_active = 1;
1166 ust_unlock();
1167 } else {
1168 handle_register_done(&local_apps);
1169 }
1170 ret = pthread_attr_destroy(&thread_attr);
1171 if (ret) {
1172 ERR("pthread_attr_destroy: %s", strerror(ret));
1173 }
1174
1175 /* Restore original signal mask in parent */
1176 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1177 if (ret) {
1178 ERR("pthread_sigmask: %s", strerror(ret));
1179 }
1180
1181 switch (timeout_mode) {
1182 case 1: /* timeout wait */
1183 do {
1184 ret = sem_timedwait(&constructor_wait,
1185 &constructor_timeout);
1186 } while (ret < 0 && errno == EINTR);
1187 if (ret < 0 && errno == ETIMEDOUT) {
1188 ERR("Timed out waiting for lttng-sessiond");
1189 } else {
1190 assert(!ret);
1191 }
1192 break;
1193 case -1:/* wait forever */
1194 do {
1195 ret = sem_wait(&constructor_wait);
1196 } while (ret < 0 && errno == EINTR);
1197 assert(!ret);
1198 break;
1199 case 0: /* no timeout */
1200 break;
1201 }
1202 }
1203
1204 static
1205 void lttng_ust_cleanup(int exiting)
1206 {
1207 cleanup_sock_info(&global_apps, exiting);
1208 if (local_apps.allowed) {
1209 cleanup_sock_info(&local_apps, exiting);
1210 }
1211 /*
1212 * The teardown in this function all affect data structures
1213 * accessed under the UST lock by the listener thread. This
1214 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1215 * that none of these threads are accessing this data at this
1216 * point.
1217 */
1218 lttng_ust_abi_exit();
1219 lttng_ust_events_exit();
1220 lttng_ring_buffer_client_discard_exit();
1221 lttng_ring_buffer_client_overwrite_exit();
1222 lttng_ring_buffer_metadata_client_exit();
1223 exit_tracepoint();
1224 if (!exiting) {
1225 /* Reinitialize values for fork */
1226 sem_count = 2;
1227 lttng_ust_comm_should_quit = 0;
1228 initialized = 0;
1229 }
1230 }
1231
1232 void __attribute__((destructor)) lttng_ust_exit(void)
1233 {
1234 int ret;
1235
1236 /*
1237 * Using pthread_cancel here because:
1238 * A) we don't want to hang application teardown.
1239 * B) the thread is not allocating any resource.
1240 */
1241
1242 /*
1243 * Require the communication thread to quit. Synchronize with
1244 * mutexes to ensure it is not in a mutex critical section when
1245 * pthread_cancel is later called.
1246 */
1247 ust_lock();
1248 lttng_ust_comm_should_quit = 1;
1249
1250 /* cancel threads */
1251 if (global_apps.thread_active) {
1252 ret = pthread_cancel(global_apps.ust_listener);
1253 if (ret) {
1254 ERR("Error cancelling global ust listener thread: %s",
1255 strerror(ret));
1256 } else {
1257 global_apps.thread_active = 0;
1258 }
1259 }
1260 if (local_apps.thread_active) {
1261 ret = pthread_cancel(local_apps.ust_listener);
1262 if (ret) {
1263 ERR("Error cancelling local ust listener thread: %s",
1264 strerror(ret));
1265 } else {
1266 local_apps.thread_active = 0;
1267 }
1268 }
1269 ust_unlock();
1270
1271 /*
1272 * Do NOT join threads: use of sys_futex makes it impossible to
1273 * join the threads without using async-cancel, but async-cancel
1274 * is delivered by a signal, which could hit the target thread
1275 * anywhere in its code path, including while the ust_lock() is
1276 * held, causing a deadlock for the other thread. Let the OS
1277 * cleanup the threads if there are stalled in a syscall.
1278 */
1279 lttng_ust_cleanup(1);
1280 }
1281
1282 /*
1283 * We exclude the worker threads across fork and clone (except
1284 * CLONE_VM), because these system calls only keep the forking thread
1285 * running in the child. Therefore, we don't want to call fork or clone
1286 * in the middle of an tracepoint or ust tracing state modification.
1287 * Holding this mutex protects these structures across fork and clone.
1288 */
1289 void ust_before_fork(sigset_t *save_sigset)
1290 {
1291 /*
1292 * Disable signals. This is to avoid that the child intervenes
1293 * before it is properly setup for tracing. It is safer to
1294 * disable all signals, because then we know we are not breaking
1295 * anything by restoring the original mask.
1296 */
1297 sigset_t all_sigs;
1298 int ret;
1299
1300 if (URCU_TLS(lttng_ust_nest_count))
1301 return;
1302 /* Disable signals */
1303 sigfillset(&all_sigs);
1304 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
1305 if (ret == -1) {
1306 PERROR("sigprocmask");
1307 }
1308 ust_lock();
1309 rcu_bp_before_fork();
1310 }
1311
1312 static void ust_after_fork_common(sigset_t *restore_sigset)
1313 {
1314 int ret;
1315
1316 DBG("process %d", getpid());
1317 ust_unlock();
1318 /* Restore signals */
1319 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
1320 if (ret == -1) {
1321 PERROR("sigprocmask");
1322 }
1323 }
1324
1325 void ust_after_fork_parent(sigset_t *restore_sigset)
1326 {
1327 if (URCU_TLS(lttng_ust_nest_count))
1328 return;
1329 DBG("process %d", getpid());
1330 rcu_bp_after_fork_parent();
1331 /* Release mutexes and reenable signals */
1332 ust_after_fork_common(restore_sigset);
1333 }
1334
1335 /*
1336 * After fork, in the child, we need to cleanup all the leftover state,
1337 * except the worker thread which already magically disappeared thanks
1338 * to the weird Linux fork semantics. After tyding up, we call
1339 * lttng_ust_init() again to start over as a new PID.
1340 *
1341 * This is meant for forks() that have tracing in the child between the
1342 * fork and following exec call (if there is any).
1343 */
1344 void ust_after_fork_child(sigset_t *restore_sigset)
1345 {
1346 if (URCU_TLS(lttng_ust_nest_count))
1347 return;
1348 DBG("process %d", getpid());
1349 /* Release urcu mutexes */
1350 rcu_bp_after_fork_child();
1351 lttng_ust_cleanup(0);
1352 lttng_context_vtid_reset();
1353 /* Release mutexes and reenable signals */
1354 ust_after_fork_common(restore_sigset);
1355 lttng_ust_init();
1356 }
This page took 0.061055 seconds and 5 git commands to generate.