3 #include <sys/select.h>
7 #include <sys/signalfd.h>
8 #include <sys/resource.h>
15 static unsigned int max_jobs;
16 static unsigned int max_jobs_pending;
20 int (*work_fn)(void *);
22 struct work_struct *next;
26 struct work_struct *work;
32 struct work_queue work_queues[WORK_PRIORITIES_NUM] = {
34 .name = "high priority",
36 .name = "high_prio_queue",
37 .lock = PTHREAD_MUTEX_INITIALIZER,
41 .name = "low priority",
43 .name = "low_prio_queue",
44 .lock = PTHREAD_MUTEX_INITIALIZER,
49 struct mutex work_stats_mutex = {
51 .lock = PTHREAD_MUTEX_INITIALIZER,
53 static int workers_active;
54 static int worker_count;
56 static int run_work_on_queue(struct work_queue *queue)
58 struct work_struct *work;
60 mutex_lock(&queue->lock);
63 mutex_unlock(&queue->lock);
69 queue->work = work->next;
72 mutex_unlock(&queue->lock);
74 pr_info("Executing work %s from queue %s, %d still pending\n",
75 work->name, queue->name, queue->length);
77 work->work_fn(work->arg);
78 pr_info("Work %s done\n", work->name);
84 static void *worker_thread(void *arg)
89 mutex_lock(&work_stats_mutex);
90 snprintf(name, sizeof(name), "worker%d", worker_count);
92 mutex_unlock(&work_stats_mutex);
94 pthread_setname_np(pthread_self(), name);
95 pthread_detach(pthread_self());
97 pr_info("Worker started\n");
99 /* Execute all high priority work from the queue */
100 while (run_work_on_queue(&work_queues[WORK_PRIORITY_HIGH]))
103 * All high priority work is now done, see if we have enough
104 * workers executing low priority worl. Continue from there if
107 mutex_lock(&work_stats_mutex);
108 if (workers_active > max_jobs)
111 mutex_unlock(&work_stats_mutex);
114 * Start executing the low priority work. Drop the nice value
115 * as this really is low priority stuff
118 pr_info("Worker priority dropped to %d\n", ret);
120 while (run_work_on_queue(&work_queues[WORK_PRIORITY_LOW]))
124 mutex_lock(&work_stats_mutex);
127 pr_info("Worker exiting, %d left active\n",
131 * Last exiting worker zeroes the worker_count. This
132 * ensures next time we start spawning worker threads
133 * the first thread will have number zero on its name.
138 mutex_unlock(&work_stats_mutex);
143 int queue_work(unsigned int priority, char *name,
144 int (work_fn)(void *arg), void *arg)
147 struct work_queue *queue;
148 struct work_struct *work, *last_work;
150 if (priority >= WORK_PRIORITIES_NUM) {
151 pr_err("Invalid priority: %d\n", priority);
155 work = calloc(sizeof(*work), 1);
158 work->work_fn = work_fn;
161 queue = &work_queues[priority];
163 /* Insert new work at the end of the work queue */
164 mutex_lock(&queue->lock);
166 last_work = queue->work;
167 while (last_work && last_work->next)
168 last_work = last_work->next;
173 last_work->next = work;
175 pr_info("Inserted work %s in queue %s, with %d pending items\n",
176 work->name, queue->name, queue->length);
178 mutex_unlock(&queue->lock);
180 mutex_lock(&work_stats_mutex);
181 pr_info("workers_active: %d, priority: %d\n", workers_active, priority);
182 if (priority != WORK_PRIORITY_HIGH && workers_active >= max_jobs) {
183 mutex_unlock(&work_stats_mutex);
187 mutex_unlock(&work_stats_mutex);
189 pr_info("Creating new worker thread\n");
190 /* We need a worker thread, create one */
191 thread = calloc(sizeof(*thread), 1);
192 pthread_create(thread, NULL, worker_thread, NULL);
200 * Initialize the jobcontrol.
202 * Create the pipes that are used to grant children execution
203 * permissions. If max_jobs is zero, count the number of CPUs from
204 * /proc/cpuinfo and use that.
206 int init_jobcontrol(int max_jobs_requested)
213 epoll_fd = epoll_create(1);
214 if (epoll_fd == -1) {
215 pr_err("Failed to epoll_create(): %m\n");
219 if (max_jobs_requested > 0) {
220 max_jobs = max_jobs_requested;
225 file = fopen("/proc/cpuinfo", "ro");
227 pr_err("Failed to open /proc/cpuinfo: %m\n");
232 * The CPU count algorithm simply reads the first 8 bytes from
233 * the /proc/cpuinfo and then expects that line to be there as
234 * many times as there are CPUs.
236 ret = fread(match, 1, sizeof(match), file);
237 if (ret < sizeof(match)) {
238 pr_err("read %d bytes when expecting %zd %m\n",
243 while(fgets(buf, sizeof(buf), file)) {
244 if (!strncmp(buf, match, sizeof(match)))
253 pr_info("Set maximum number of parallel jobs to %d\n", max_jobs);
255 max_jobs_pending = max_jobs * 10 + 25;
256 pr_info("Set maximum number of pending jobs to %d\n", max_jobs_pending);
261 int poll_job_requests(int timeout)
263 struct epoll_event event;
264 struct event_handler *job_handler;
267 /* Convert positive seconds to milliseconds */
268 timeout = timeout > 0 ? 1000 * timeout : timeout;
270 ret = epoll_wait(epoll_fd, &event, 1, timeout);
273 if (errno != EINTR) {
274 pr_err("epoll_wait: %m\n");
279 * If epoll_wait() was interrupted, better start
280 * everything again from the beginning
286 pr_info("Timed out\n");
290 job_handler = event.data.ptr;
292 if (!job_handler || !job_handler->handle_event) {
293 pr_err("Corrupted event handler for fd %d\n",
298 pr_debug("Running handler %s to handle events from fd %d\n",
299 job_handler->name, job_handler->fd);
300 job_handler->handle_event(job_handler);
303 pr_info("Workers active: %u\n", workers_active);
312 pr_err("fork() failed: %m\n");
317 pr_debug("Fork child %d\n", child);
324 int clear_zombie(int pid)
327 struct rusage rusage;
328 char *status_str = NULL;
332 pr_debug("Waiting on pid %d\n", pid);
335 pid = wait4(pid, &status, 0, &rusage);
337 pr_err("Error on waitid(): %m\n");
340 /* Wait until the child has become a zombie */
341 } while (!WIFEXITED(status) && !WIFSIGNALED(status));
343 if (WIFEXITED(status)) {
344 status_str = "exited with status";
345 code = WEXITSTATUS(status);
346 } else if (WIFSIGNALED(status)) {
347 status_str = "killed by signal";
348 code = WTERMSIG(status);
350 pr_debug("pid %d: %s %d.\n", pid,
352 pr_debug("pid %d: User time: %ld.%03lds, System %ld.%03lds\n", pid,
353 (long)rusage.ru_utime.tv_sec, rusage.ru_utime.tv_usec / 1000,
354 (long)rusage.ru_stime.tv_sec, rusage.ru_stime.tv_usec / 1000);
360 * Runs a command cmd with params argv, connects stdin and stdout to
363 * Returns the pid of the executed process
365 int run_piped(const char *cmd, char *const argv[],
366 int *stdinfd, int *stdoutfd, int *stderrfd)
368 int ifd[2], ofd[2], efd[2], pid;
370 pr_info("Running command %s\n", cmd);
372 if (stdinfd && pipe(ifd)) {
373 pr_err("pipe() failed: %m\n");
377 if (stdoutfd && pipe(ofd)) {
378 pr_err("pipe() failed: %m\n");
382 if (stderrfd && pipe(efd)) {
383 pr_err("pipe() failed: %m\n");
388 if (pid) { /* Parent side */
409 dup2(ifd[0], STDIN_FILENO);
414 dup2(ofd[1], STDOUT_FILENO);
419 dup2(efd[1], STDERR_FILENO);
422 /* Now we have redirected standard streams to parent process */
424 pr_err("Failed to execv command %s: %m\n", cmd);
431 * Runs a command cmd with params argv, connects stdin and stdout to
434 * Returns the pid of the executed process
436 int run_piped_stream(const char *cmd, char *const argv[],
437 FILE **stdinf, FILE **stdoutf, FILE **stderrf)
439 int ifd, ofd, efd, pid;
455 pid = run_piped(cmd, argv, i, o, e);
458 *stdinf = fdopen(ifd, "r");
459 if (*stdinf == NULL) {
460 pr_err("Error opening file stream for fd %d: %m\n",
467 *stdoutf = fdopen(ofd, "w");
468 if (*stdoutf == NULL) {
469 pr_err("Error opening file stream for fd %d: %m\n",
476 *stderrf = fdopen(efd, "r");
477 if (*stderrf == NULL) {
478 pr_err("Error opening file stream for fd %d: %m\n",
488 * Forks a child and executes a command to run on parallel
491 #define BUF_SIZE (128*1024)
492 int run(const char *cmd, char *const argv[])
500 child = run_piped(cmd, argv, NULL, &ofd, &efd);
512 maxfd = max(ofd, efd);
513 error = select(maxfd, &rfds, NULL, NULL, NULL);
516 pr_err("Error with select: %m\n");
520 if (FD_ISSET(ofd, &rfds)) {
521 bytes = read(ofd, rbuf, BUF_SIZE);
525 if (FD_ISSET(efd, &rfds)) {
527 bytes = read(efd, rbuf, BUF_SIZE);
531 pr_err("select() returned unknown fd\n");
536 pr_err("read() failed: %m\n");
541 * Workaround: When a process had die and it has only
542 * written to stderr, select() doesn't indicate that
543 * there might be something to read in stderr fd. To
544 * work around this issue, we try to read stderr just
545 * in case in order to ensure everything gets read.
548 bytes = read(efd, rbuf, BUF_SIZE);
558 pr_err("%s: stderr: %s\n",
561 pr_info("%s: stdout: %s\n",
577 int register_event_handler(struct event_handler *handler)
579 struct epoll_event ev;
582 if (handler->fd <= 0) {
583 pr_err("Invalid file descriptor of %d\n", handler->fd);
587 if (!handler->handle_event) {
588 pr_err("Handler callback missing\n");
592 pr_info("Registering handler for %s, fd %d\n",
593 handler->name, handler->fd);
595 ev.data.fd = handler->fd;
596 ev.data.ptr = handler;
597 ev.events = handler->events;
598 ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, handler->fd, &ev);
600 pr_err("Failed to add epoll_fd: %m\n");
607 void _mutex_lock_acquired(struct mutex *lock, char *file, int line)
611 pthread_getname_np(pthread_self(),
612 lock->owner_name, sizeof(lock->owner_name));
615 int _mutex_lock(struct mutex *lock, char *file, int line)
620 if (!pthread_mutex_trylock(&lock->lock))
624 pr_info("Lock contention at %s:%d on lock %s acquired by %s at %s:%d\n",
625 file, line, lock->name,
626 lock->owner_name, lock->file, lock->line);
628 ret = pthread_mutex_lock(&lock->lock);
630 pr_err("Acquirin lock %s failed: %m, acquired on %s:%d\n",
631 lock->name, lock->file, lock->line);
635 pr_info("Lock %s acquired at %s:%d after contention\n",
636 lock->name, file, line);
637 _mutex_lock_acquired(lock, file, line);
641 int _mutex_unlock(struct mutex *lock)
645 pthread_mutex_unlock(&lock->lock);