drm: add modifiers for MediaTek tiled formats
[drm/drm-misc.git] / tools / thermal / lib / mainloop.c
blobbf4c1b730d7b76ae6a9b84d68244da2797d8f637
1 // SPDX-License-Identifier: LGPL-2.1+
2 // Copyright (C) 2022, Linaro Ltd - Daniel Lezcano <daniel.lezcano@linaro.org>
3 #include <stdlib.h>
4 #include <errno.h>
5 #include <unistd.h>
6 #include <signal.h>
7 #include <sys/epoll.h>
8 #include "mainloop.h"
9 #include "log.h"
11 static int epfd = -1;
12 static sig_atomic_t exit_mainloop;
14 struct mainloop_data {
15 mainloop_callback_t cb;
16 void *data;
17 int fd;
20 #define MAX_EVENTS 10
22 int mainloop(unsigned int timeout)
24 int i, nfds;
25 struct epoll_event events[MAX_EVENTS];
26 struct mainloop_data *md;
28 if (epfd < 0)
29 return -1;
31 for (;;) {
33 nfds = epoll_wait(epfd, events, MAX_EVENTS, timeout);
35 if (exit_mainloop || !nfds)
36 return 0;
38 if (nfds < 0) {
39 if (errno == EINTR)
40 continue;
41 return -1;
44 for (i = 0; i < nfds; i++) {
45 md = events[i].data.ptr;
47 if (md->cb(md->fd, md->data) > 0)
48 return 0;
53 int mainloop_add(int fd, mainloop_callback_t cb, void *data)
55 struct epoll_event ev = {
56 .events = EPOLLIN,
59 struct mainloop_data *md;
61 md = malloc(sizeof(*md));
62 if (!md)
63 return -1;
65 md->data = data;
66 md->cb = cb;
67 md->fd = fd;
69 ev.data.ptr = md;
71 if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) < 0) {
72 free(md);
73 return -1;
76 return 0;
79 int mainloop_del(int fd)
81 if (epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL) < 0)
82 return -1;
84 return 0;
87 int mainloop_init(void)
89 epfd = epoll_create(2);
90 if (epfd < 0)
91 return -1;
93 return 0;
96 void mainloop_exit(void)
98 exit_mainloop = 1;
101 void mainloop_fini(void)
103 close(epfd);