4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
6 // Stefan Bund <stefan.bund@fokus.fraunhofer.de>
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 \brief Scheduler non-inline non-template implementation
26 \idea Implement signal handling (See source for more discussion
29 \idea Multithreading support: To support multithreading, the
30 static member Scheduler::instance() must return a thread-local
31 value (that is Scheduler::instance() must allocate one Scheduler
32 instance per thread). Another possibility would be to distribute
33 the async load unto several threads (one scheduler for multiple
37 // Here a basic concept of how to add signal support to the scheduler:
39 // ... no, I had overlooked one race condition. So back to the signal-pipe approach ...
41 #include "Scheduler.hh"
42 //#include "Scheduler.ih"
46 #include <sys/epoll.h>
49 #include "../Utils/Exception.hh"
51 static const int EPollInitialSize = 16;
54 ///////////////////////////////cc.p////////////////////////////////////////
56 prefix_ senf::Scheduler::Scheduler()
57 : files_(0), timerIdCounter_(0), epollFd_ (epoll_create(EPollInitialSize)), terminate_(false),
58 eventTime_(0), eventEarly_(ClockService::milliseconds(11)), eventAdjust_(0)
61 throw SystemException(errno);
63 if (::pipe(sigpipe_) < 0)
64 throw SystemException(errno);
66 int flags (::fcntl(sigpipe_[1],F_GETFL));
68 throw SystemException(errno);
70 if (::fcntl(sigpipe_[1], F_SETFL, flags) < 0)
71 throw SystemException(errno);
74 ::memset(&ev, 0, sizeof(ev));
76 ev.data.fd = sigpipe_[0];
77 if (::epoll_ctl(epollFd_, EPOLL_CTL_ADD, sigpipe_[0], &ev) < 0)
78 throw SystemException(errno);
81 prefix_ void senf::Scheduler::registerSignal(unsigned signal, SimpleCallback const & cb)
85 if (::sigaddset(&sig, signal) < 0)
86 throw InvalidSignalNumberException();
87 ::sigprocmask(SIG_BLOCK, &sig, 0);
88 ::sigaddset(&sigset_, signal);
89 if (sigHandlers_.size() <= signal)
90 sigHandlers_.resize(signal+1);
91 sigHandlers_[signal] = cb;
93 registerSigHandlers();
96 prefix_ void senf::Scheduler::unregisterSignal(unsigned signal)
98 if (::sigdelset(&sigset_, signal) < 0)
99 throw InvalidSignalNumberException();
100 sigHandlers_[signal] = 0;
101 ::signal(signal, SIG_DFL);
102 registerSigHandlers();
105 prefix_ void senf::Scheduler::do_add(int fd, FdCallback const & cb, int eventMask)
107 FdTable::iterator i (fdTable_.find(fd));
108 int action (EPOLL_CTL_MOD);
109 if (i == fdTable_.end()) {
110 action = EPOLL_CTL_ADD;
111 i = fdTable_.insert(std::make_pair(fd, EventSpec())).first;
114 if (eventMask & EV_READ) i->second.cb_read = cb;
115 if (eventMask & EV_PRIO) i->second.cb_prio = cb;
116 if (eventMask & EV_WRITE) i->second.cb_write = cb;
119 memset(&ev,0,sizeof(ev));
120 ev.events = i->second.epollMask();
123 if (! i->second.file && epoll_ctl(epollFd_, action, fd, &ev) < 0) {
124 if (errno == EPERM) {
125 // Argh ... epoll does not support ordinary files :-( :-(
126 i->second.file = true;
130 throwErrno("::epoll_ctl()");
134 prefix_ void senf::Scheduler::do_remove(int fd, int eventMask)
136 FdTable::iterator i (fdTable_.find(fd));
137 if (i == fdTable_.end())
140 if (eventMask & EV_READ) i->second.cb_read = 0;
141 if (eventMask & EV_PRIO) i->second.cb_prio = 0;
142 if (eventMask & EV_WRITE) i->second.cb_write = 0;
145 memset(&ev,0,sizeof(ev));
146 ev.events = i->second.epollMask();
149 int action (EPOLL_CTL_MOD);
150 bool file (i->second.file);
152 action = EPOLL_CTL_DEL;
153 fdErase_.push_back(fd);
156 if (! file && epoll_ctl(epollFd_, action, fd, &ev) < 0)
157 throwErrno("::epoll_ctl()");
162 prefix_ void senf::Scheduler::registerSigHandlers()
164 for (unsigned signal (1); signal < sigHandlers_.size(); ++signal) {
165 if (sigHandlers_[signal]) {
166 struct ::sigaction sa;
167 sa.sa_sigaction = & Scheduler::sigHandler;
168 sa.sa_mask = sigset_;
169 sa.sa_flags = SA_SIGINFO;
170 if (signal == SIGCHLD)
171 sa.sa_flags |= SA_NOCLDSTOP;
172 if (::sigaction(signal, &sa, 0) < 0)
173 throw SystemException(errno);
178 prefix_ void senf::Scheduler::sigHandler(int signal, ::siginfo_t * siginfo, void *)
180 // This is a bit unsafe. Better write single bytes and place the siginfo into an explicit
181 // queue. Since signals are only unblocked during epoll_wait, we even wouldn't need to
182 // synchronize access to that queue any further.
184 ::write(instance().sigpipe_[1], siginfo, sizeof(*siginfo));
186 // We ignore errors. The file handle is set to non-blocking IO. If any failure occurs (pipe
187 // full), the signal will be dropped. That's like kernel signal handling which may also drop
191 prefix_ int senf::Scheduler::EventSpec::epollMask()
195 if (cb_read) mask |= EPOLLIN;
196 if (cb_prio) mask |= EPOLLPRI;
197 if (cb_write) mask |= EPOLLOUT;
201 prefix_ void senf::Scheduler::process()
204 eventTime_ = ClockService::now();
205 while (! terminate_) {
207 // Since a callback may have disabled further timers, we need to check for canceled timeouts
210 while (! timerQueue_.empty()) {
211 TimerMap::iterator i (timerQueue_.top());
212 if (! i->second.canceled)
218 for (FdEraseList::iterator i (fdErase_.begin()); i != fdErase_.end(); ++i)
226 if (timerQueue_.empty()) {
227 if (fdTable_.empty())
231 ClockService::clock_type delta (
232 (timerQueue_.top()->second.timeout - eventTime_ + eventAdjust_)/1000000UL);
233 timeout = delta < 0 ? 0 : delta;
237 ///\todo Handle more than one epoll_event per call
238 struct epoll_event ev;
240 ::sigprocmask(SIG_UNBLOCK, &sigset_, 0);
241 int events (epoll_wait(epollFd_, &ev, 1, timeout));
242 ::sigprocmask(SIG_BLOCK, &sigset_, 0);
246 throw SystemException(errno);
248 eventTime_ = ClockService::now();
250 // We always run timeout handlers. This is important, even if a file-descriptor is signaled
251 // since some descriptors (e.g. real files) will *always* be ready and we still may want to
252 // handle timers. Time handlers are run before file events to not delay them unnecessarily.
254 while (! timerQueue_.empty()) {
255 TimerMap::iterator i (timerQueue_.top());
256 if (i->second.canceled)
258 else if (i->second.timeout <= eventTime_ + eventEarly_)
266 // Check the signal queue
267 if (events > 0 && ev.data.fd == sigpipe_[0]) {
269 if (::read(sigpipe_[0], &siginfo, sizeof(siginfo)) < int(sizeof(siginfo))) {
270 // We ignore truncated records which may only occur if the signal
271 // queue became filled up
272 SENF_LOG((senf::log::IMPORTANT)("Truncated signal record!"));
275 if (siginfo.si_signo < int(sigHandlers_.size()) && sigHandlers_[siginfo.si_signo])
276 sigHandlers_[siginfo.si_signo]();
280 for (FdTable::iterator i = fdTable_.begin(); i != fdTable_.end(); ++i) {
281 EventSpec & spec (i->second);
283 if (! (spec.file || (events > 0 && i->first == ev.data.fd)))
286 unsigned extraFlags (0);
287 unsigned mask (spec.file ? spec.epollMask() : ev.events);
289 if (mask & EPOLLHUP) extraFlags |= EV_HUP;
290 if (mask & EPOLLERR) extraFlags |= EV_ERR;
292 if (mask & EPOLLIN) {
293 BOOST_ASSERT(spec.cb_read);
294 spec.cb_read(EventId(EV_READ | extraFlags));
296 else if (mask & EPOLLPRI) {
297 BOOST_ASSERT(spec.cb_prio);
298 spec.cb_prio(EventId(EV_PRIO | extraFlags));
300 else if (mask & EPOLLOUT) {
301 BOOST_ASSERT(spec.cb_write);
302 spec.cb_write(EventId(EV_WRITE | extraFlags));
305 // This branch is only taken, if HUP or ERR is signaled but none of IN/OUT/PRI.
306 // In this case we will signal all registered callbacks. The callbacks must be
307 // prepared to be called multiple times if they are registered to more than
310 spec.cb_write(EventId(extraFlags));
312 spec.cb_prio(EventId(extraFlags));
314 spec.cb_read(EventId(extraFlags));
320 ///////////////////////////////////////////////////////////////////////////
321 // senf::SchedulerLogTimeSource
323 prefix_ boost::posix_time::ptime senf::SchedulerLogTimeSource::operator()()
326 return ClockService::abstime(Scheduler::instance().eventTime());
329 ///////////////////////////////cc.e////////////////////////////////////////
336 // c-file-style: "senf"
337 // indent-tabs-mode: nil
338 // ispell-local-dictionary: "american"
339 // compile-command: "scons -u test"
340 // comment-column: 40