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 job_notify_fd[2];
58 static int run_work_on_queue(struct work_queue *queue)
60 struct work_struct *work;
62 mutex_lock(&queue->lock);
65 mutex_unlock(&queue->lock);
71 queue->work = work->next;
74 mutex_unlock(&queue->lock);
76 pr_info("Executing work %s from queue %s, %d still pending\n",
77 work->name, queue->name, queue->length);
79 work->work_fn(work->arg);
80 pr_info("Work %s done\n", work->name);
86 static void *worker_thread(void *arg)
91 mutex_lock(&work_stats_mutex);
92 snprintf(name, sizeof(name), "worker%d", worker_count);
94 mutex_unlock(&work_stats_mutex);
96 pthread_setname_np(pthread_self(), name);
97 pthread_detach(pthread_self());
99 pr_info("Worker started\n");
101 /* Execute all high priority work from the queue */
102 while (run_work_on_queue(&work_queues[WORK_PRIORITY_HIGH]))
105 * All high priority work is now done, see if we have enough
106 * workers executing low priority worl. Continue from there if
109 mutex_lock(&work_stats_mutex);
110 if (workers_active > max_jobs)
113 mutex_unlock(&work_stats_mutex);
116 * Start executing the low priority work. Drop the nice value
117 * as this really is low priority stuff
120 pr_info("Worker priority dropped to %d\n", ret);
122 while (run_work_on_queue(&work_queues[WORK_PRIORITY_LOW]))
126 mutex_lock(&work_stats_mutex);
129 pr_info("Worker exiting, %d left active\n",
133 * Last exiting worker zeroes the worker_count. This
134 * ensures next time we start spawning worker threads
135 * the first thread will have number zero on its name.
137 if (!workers_active) {
141 * Kick the job poller, just to print the time of next
144 notify_job_request();
147 mutex_unlock(&work_stats_mutex);
152 int queue_work(unsigned int priority, char *name,
153 int (work_fn)(void *arg), void *arg)
156 struct work_queue *queue;
157 struct work_struct *work, *last_work;
159 if (priority >= WORK_PRIORITIES_NUM) {
160 pr_err("Invalid priority: %d\n", priority);
164 work = calloc(sizeof(*work), 1);
167 work->work_fn = work_fn;
170 queue = &work_queues[priority];
172 /* Insert new work at the end of the work queue */
173 mutex_lock(&queue->lock);
175 last_work = queue->work;
176 while (last_work && last_work->next)
177 last_work = last_work->next;
182 last_work->next = work;
184 pr_info("Inserted work %s in queue %s, with %d pending items\n",
185 work->name, queue->name, queue->length);
187 mutex_unlock(&queue->lock);
189 mutex_lock(&work_stats_mutex);
190 pr_info("workers_active: %d, priority: %d\n", workers_active, priority);
191 if (priority != WORK_PRIORITY_HIGH && workers_active >= max_jobs) {
192 mutex_unlock(&work_stats_mutex);
196 mutex_unlock(&work_stats_mutex);
198 pr_info("Creating new worker thread\n");
199 /* We need a worker thread, create one */
200 thread = calloc(sizeof(*thread), 1);
201 pthread_create(thread, NULL, worker_thread, NULL);
208 static int job_notify_handler(struct event_handler *h)
213 ret = read(job_notify_fd[0], buf, sizeof(buf));
215 pr_err("Failed to read: %m\n");
221 * Initialize the jobcontrol.
223 * Create the pipes that are used to grant children execution
224 * permissions. If max_jobs is zero, count the number of CPUs from
225 * /proc/cpuinfo and use that.
227 int init_jobcontrol(int max_jobs_requested)
229 static struct event_handler ev;
235 epoll_fd = epoll_create(1);
236 if (epoll_fd == -1) {
237 pr_err("Failed to epoll_create(): %m\n");
241 if (max_jobs_requested > 0) {
242 max_jobs = max_jobs_requested;
247 file = fopen("/proc/cpuinfo", "ro");
249 pr_err("Failed to open /proc/cpuinfo: %m\n");
254 * The CPU count algorithm simply reads the first 8 bytes from
255 * the /proc/cpuinfo and then expects that line to be there as
256 * many times as there are CPUs.
258 ret = fread(match, 1, sizeof(match), file);
259 if (ret < sizeof(match)) {
260 pr_err("read %d bytes when expecting %zd %m\n",
265 while(fgets(buf, sizeof(buf), file)) {
266 if (!strncmp(buf, match, sizeof(match)))
270 ret = pipe(job_notify_fd);
272 pr_err("pipe() failed: %m\n");
276 ev.fd = job_notify_fd[0];
278 ev.handle_event = job_notify_handler;
279 ev.name = "job_notify";
280 register_event_handler(&ev, EPOLL_CTL_ADD);
287 pr_info("Set maximum number of parallel jobs to %d\n", max_jobs);
289 max_jobs_pending = max_jobs * 10 + 25;
290 pr_info("Set maximum number of pending jobs to %d\n", max_jobs_pending);
295 int poll_job_requests(int timeout)
297 struct epoll_event event;
298 struct event_handler *job_handler;
301 /* Convert positive seconds to milliseconds */
302 timeout = timeout > 0 ? 1000 * timeout : timeout;
304 ret = epoll_wait(epoll_fd, &event, 1, timeout);
307 if (errno != EINTR) {
308 pr_err("epoll_wait: %m\n");
313 * If epoll_wait() was interrupted, better start
314 * everything again from the beginning
320 pr_info("Timed out\n");
324 job_handler = event.data.ptr;
326 if (!job_handler || !job_handler->handle_event) {
327 pr_err("Corrupted event handler for fd %d\n",
332 pr_debug("Running handler %s to handle events from fd %d\n",
333 job_handler->name, job_handler->fd);
334 job_handler->handle_event(job_handler);
337 pr_info("Workers active: %u\n", workers_active);
341 int notify_job_request(void)
346 ret = write(job_notify_fd[1], &byte, sizeof(byte));
348 pr_err("Failed to write: %m\n");
358 pr_err("fork() failed: %m\n");
363 pr_debug("Fork child %d\n", child);
370 int clear_zombie(int pid)
373 struct rusage rusage;
374 char *status_str = NULL;
378 pr_debug("Waiting on pid %d\n", pid);
381 pid = wait4(pid, &status, 0, &rusage);
383 pr_err("Error on waitid(): %m\n");
386 /* Wait until the child has become a zombie */
387 } while (!WIFEXITED(status) && !WIFSIGNALED(status));
389 if (WIFEXITED(status)) {
390 status_str = "exited with status";
391 code = WEXITSTATUS(status);
392 } else if (WIFSIGNALED(status)) {
393 status_str = "killed by signal";
394 code = WTERMSIG(status);
396 pr_debug("pid %d: %s %d.\n", pid,
398 pr_debug("pid %d: User time: %ld.%03lds, System %ld.%03lds\n", pid,
399 (long)rusage.ru_utime.tv_sec, rusage.ru_utime.tv_usec / 1000,
400 (long)rusage.ru_stime.tv_sec, rusage.ru_stime.tv_usec / 1000);
406 * Runs a command cmd with params argv, connects stdin and stdout to
409 * Returns the pid of the executed process
411 int run_piped(const char *cmd, char *const argv[],
412 int *stdinfd, int *stdoutfd, int *stderrfd)
414 int ifd[2], ofd[2], efd[2], pid;
416 pr_info("Running command %s\n", cmd);
418 if (stdinfd && pipe(ifd)) {
419 pr_err("pipe() failed: %m\n");
423 if (stdoutfd && pipe(ofd)) {
424 pr_err("pipe() failed: %m\n");
428 if (stderrfd && pipe(efd)) {
429 pr_err("pipe() failed: %m\n");
434 if (pid) { /* Parent side */
455 dup2(ifd[0], STDIN_FILENO);
460 dup2(ofd[1], STDOUT_FILENO);
465 dup2(efd[1], STDERR_FILENO);
468 /* Now we have redirected standard streams to parent process */
470 pr_err("Failed to execv command %s: %m\n", cmd);
477 * Runs a command cmd with params argv, connects stdin and stdout to
480 * Returns the pid of the executed process
482 int run_piped_stream(const char *cmd, char *const argv[],
483 FILE **stdinf, FILE **stdoutf, FILE **stderrf)
485 int ifd, ofd, efd, pid;
501 pid = run_piped(cmd, argv, i, o, e);
504 *stdinf = fdopen(ifd, "r");
505 if (*stdinf == NULL) {
506 pr_err("Error opening file stream for fd %d: %m\n",
513 *stdoutf = fdopen(ofd, "w");
514 if (*stdoutf == NULL) {
515 pr_err("Error opening file stream for fd %d: %m\n",
522 *stderrf = fdopen(efd, "r");
523 if (*stderrf == NULL) {
524 pr_err("Error opening file stream for fd %d: %m\n",
534 * Forks a child and executes a command to run on parallel
537 #define BUF_SIZE (128*1024)
538 int run(const char *cmd, char *const argv[])
546 child = run_piped(cmd, argv, NULL, &ofd, &efd);
558 maxfd = max(ofd, efd);
559 error = select(maxfd, &rfds, NULL, NULL, NULL);
562 pr_err("Error with select: %m\n");
566 if (FD_ISSET(ofd, &rfds)) {
567 bytes = read(ofd, rbuf, BUF_SIZE);
571 if (FD_ISSET(efd, &rfds)) {
573 bytes = read(efd, rbuf, BUF_SIZE);
577 pr_err("select() returned unknown fd\n");
582 pr_err("read() failed: %m\n");
587 * Workaround: When a process had die and it has only
588 * written to stderr, select() doesn't indicate that
589 * there might be something to read in stderr fd. To
590 * work around this issue, we try to read stderr just
591 * in case in order to ensure everything gets read.
594 bytes = read(efd, rbuf, BUF_SIZE);
604 pr_err("%s: stderr: %s\n",
607 pr_info("%s: stdout: %s\n",
623 int register_event_handler(struct event_handler *handler, int op)
625 struct epoll_event ev;
629 if (handler->fd <= 0) {
630 pr_err("Invalid file descriptor of %d\n", handler->fd);
634 if (!handler->handle_event) {
635 pr_err("Handler callback missing\n");
653 pr_err("Invalid op %d\n", op);
657 pr_info("Doing a epoll %s for handler %s, fd %d\n", str,
658 handler->name, handler->fd);
660 ev.data.fd = handler->fd;
661 ev.data.ptr = handler;
662 ev.events = handler->events;
663 ret = epoll_ctl(epoll_fd, op, handler->fd, &ev);
665 pr_err("Failed to do epoll_ctl %s: %m\n", str);
672 void _mutex_lock_acquired(struct mutex *lock, char *file, int line)
676 pthread_getname_np(pthread_self(),
677 lock->owner_name, sizeof(lock->owner_name));
680 int _mutex_lock(struct mutex *lock, char *file, int line)
685 if (!pthread_mutex_trylock(&lock->lock))
689 pr_info("Lock contention at %s:%d on lock %s acquired by %s at %s:%d\n",
690 file, line, lock->name,
691 lock->owner_name, lock->file, lock->line);
693 ret = pthread_mutex_lock(&lock->lock);
695 pr_err("Acquirin lock %s failed: %m, acquired on %s:%d\n",
696 lock->name, lock->file, lock->line);
700 pr_info("Lock %s acquired at %s:%d after contention\n",
701 lock->name, file, line);
702 _mutex_lock_acquired(lock, file, line);
706 int _mutex_unlock(struct mutex *lock)
710 pthread_mutex_unlock(&lock->lock);