Git init
[framework/multimedia/pulseaudio.git] / src / daemon / cpulimit.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public
17   License along with PulseAudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <pulse/error.h>
27 #include <pulse/rtclock.h>
28 #include <pulse/timeval.h>
29
30 #include <pulsecore/core-rtclock.h>
31 #include <pulsecore/core-util.h>
32 #include <pulsecore/core-error.h>
33 #include <pulsecore/log.h>
34 #include <pulsecore/macro.h>
35
36 #include "cpulimit.h"
37
38 #ifdef HAVE_SIGXCPU
39
40 #include <errno.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <sys/time.h>
44 #include <unistd.h>
45 #include <signal.h>
46
47 #ifdef HAVE_SYS_RESOURCE_H
48 #include <sys/resource.h>
49 #endif
50
51 /* This module implements a watchdog that makes sure that the current
52  * process doesn't consume more than 70% CPU time for 10 seconds. This
53  * is very useful when using SCHED_FIFO scheduling which effectively
54  * disables multitasking. */
55
56 /* Method of operation: Using SIGXCPU a signal handler is called every
57  * 10s process CPU time. That function checks if less than 14s system
58  * time have passed. In that case, it tries to contact the main event
59  * loop through a pipe. After two additional seconds it is checked
60  * whether the main event loop contact was successful. If not, the
61  * program is terminated forcibly. */
62
63 /* Utilize this much CPU time at maximum */
64 #define CPUTIME_PERCENT 70
65
66 /* Check every 10s */
67 #define CPUTIME_INTERVAL_SOFT (10)
68
69 /* Recheck after 5s */
70 #define CPUTIME_INTERVAL_HARD (5)
71
72 /* Time of the last CPU load check */
73 static pa_usec_t last_time = 0;
74
75 /* Pipe for communicating with the main loop */
76 static int the_pipe[2] = {-1, -1};
77
78 /* Main event loop and IO event for the FIFO */
79 static pa_mainloop_api *api = NULL;
80 static pa_io_event *io_event = NULL;
81
82 /* Saved sigaction struct for SIGXCPU */
83 static struct sigaction sigaction_prev;
84
85 /* Nonzero after pa_cpu_limit_init() */
86 static pa_bool_t installed = FALSE;
87
88 /* The current state of operation */
89 static enum  {
90     PHASE_IDLE,   /* Normal state */
91     PHASE_SOFT    /* After CPU overload has been detected */
92 } phase = PHASE_IDLE;
93
94 /* Reset the SIGXCPU timer to the next t seconds */
95 static void reset_cpu_time(int t) {
96     long n;
97     struct rlimit rl;
98     struct rusage ru;
99
100     /* Get the current CPU time of the current process */
101     pa_assert_se(getrusage(RUSAGE_SELF, &ru) >= 0);
102
103     n = ru.ru_utime.tv_sec + ru.ru_stime.tv_sec + t;
104     pa_assert_se(getrlimit(RLIMIT_CPU, &rl) >= 0);
105
106     rl.rlim_cur = (rlim_t) n;
107     pa_assert_se(setrlimit(RLIMIT_CPU, &rl) >= 0);
108 }
109
110 /* A simple, thread-safe puts() work-alike */
111 static void write_err(const char *p) {
112     pa_loop_write(2, p, strlen(p), NULL);
113 }
114
115 /* The signal handler, called on every SIGXCPU */
116 static void signal_handler(int sig) {
117     int saved_errno;
118
119     saved_errno = errno;
120     pa_assert(sig == SIGXCPU);
121
122     if (phase == PHASE_IDLE) {
123         pa_usec_t now, elapsed;
124
125 #ifdef PRINT_CPU_LOAD
126         char t[256];
127 #endif
128
129         now = pa_rtclock_now();
130         elapsed = now - last_time;
131
132 #ifdef PRINT_CPU_LOAD
133         pa_snprintf(t, sizeof(t), "Using %0.1f%% CPU\n", ((double) CPUTIME_INTERVAL_SOFT * (double) PA_USEC_PER_SEC) / (double) elapsed * 100.0);
134         write_err(t);
135 #endif
136
137         if (((double) CPUTIME_INTERVAL_SOFT * (double) PA_USEC_PER_SEC) >= ((double) elapsed * (double) CPUTIME_PERCENT / 100.0)) {
138             static const char c = 'X';
139
140             write_err("Soft CPU time limit exhausted, terminating.\n");
141
142             /* Try a soft cleanup */
143             (void) write(the_pipe[1], &c, sizeof(c));
144             phase = PHASE_SOFT;
145             reset_cpu_time(CPUTIME_INTERVAL_HARD);
146
147         } else {
148
149             /* Everything's fine */
150             reset_cpu_time(CPUTIME_INTERVAL_SOFT);
151             last_time = now;
152         }
153
154     } else if (phase == PHASE_SOFT) {
155         write_err("Hard CPU time limit exhausted, terminating forcibly.\n");
156         abort(); /* Forced exit */
157     }
158
159     errno = saved_errno;
160 }
161
162 /* Callback for IO events on the FIFO */
163 static void callback(pa_mainloop_api*m, pa_io_event*e, int fd, pa_io_event_flags_t f, void *userdata) {
164     char c;
165     pa_assert(m);
166     pa_assert(e);
167     pa_assert(f == PA_IO_EVENT_INPUT);
168     pa_assert(e == io_event);
169     pa_assert(fd == the_pipe[0]);
170
171     pa_log("Received request to terminate due to CPU overload.");
172
173     pa_read(the_pipe[0], &c, sizeof(c), NULL);
174     m->quit(m, 1); /* Quit the main loop */
175 }
176
177 /* Initializes CPU load limiter */
178 int pa_cpu_limit_init(pa_mainloop_api *m) {
179     struct sigaction sa;
180
181     pa_assert(m);
182     pa_assert(!api);
183     pa_assert(!io_event);
184     pa_assert(the_pipe[0] == -1);
185     pa_assert(the_pipe[1] == -1);
186     pa_assert(!installed);
187
188     last_time = pa_rtclock_now();
189
190     /* Prepare the main loop pipe */
191     if (pipe(the_pipe) < 0) {
192         pa_log("pipe() failed: %s", pa_cstrerror(errno));
193         return -1;
194     }
195
196     pa_make_fd_nonblock(the_pipe[0]);
197     pa_make_fd_nonblock(the_pipe[1]);
198     pa_make_fd_cloexec(the_pipe[0]);
199     pa_make_fd_cloexec(the_pipe[1]);
200
201     api = m;
202     io_event = api->io_new(m, the_pipe[0], PA_IO_EVENT_INPUT, callback, NULL);
203
204     phase = PHASE_IDLE;
205
206     /* Install signal handler for SIGXCPU */
207     memset(&sa, 0, sizeof(sa));
208     sa.sa_handler = signal_handler;
209     sigemptyset(&sa.sa_mask);
210     sa.sa_flags = SA_RESTART;
211
212     if (sigaction(SIGXCPU, &sa, &sigaction_prev) < 0) {
213         pa_cpu_limit_done();
214         return -1;
215     }
216
217     installed = TRUE;
218
219     reset_cpu_time(CPUTIME_INTERVAL_SOFT);
220
221     return 0;
222 }
223
224 /* Shutdown CPU load limiter */
225 void pa_cpu_limit_done(void) {
226
227     if (io_event) {
228         pa_assert(api);
229         api->io_free(io_event);
230         io_event = NULL;
231         api = NULL;
232     }
233
234     pa_close_pipe(the_pipe);
235
236     if (installed) {
237         pa_assert_se(sigaction(SIGXCPU, &sigaction_prev, NULL) >= 0);
238         installed = FALSE;
239     }
240 }
241
242 #else /* HAVE_SIGXCPU */
243
244 int pa_cpu_limit_init(pa_mainloop_api *m) {
245     return 0;
246 }
247
248 void pa_cpu_limit_done(void) {
249 }
250
251 #endif