adbb6a6b5f0fe5d3101084f4ee4f081973a23acb
[senf.git] / Scheduler / Scheduler.cc
1 // $Id$
2 //
3 // Copyright (C) 2006
4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
6 //     Stefan Bund <stefan.bund@fokus.fraunhofer.de>
7 //
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.
12 //
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.
17 //
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.
22
23 /** \file
24     \brief Scheduler non-inline non-template implementation
25
26     \idea Implement signal handling (See source for more discussion
27     about this)
28
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
34     threads)
35  */
36
37 // Here a basic concept of how to add signal support to the scheduler:
38 //
39 // Every signal to be reported by the scheduler will be asigned a
40 // generic signal handler by the scheduler. This signal handler will
41 // use longjmp (juck) to report this signal back to the scheduler
42 // main-loop.
43 //
44 // To make this safe, the main-loop will look something like:
45 //
46 //     int signal = setjmp(jmpBuffer_);
47 //     if (signal == 0) {
48 //         // unblock all signals which are registered with the
49 //         // scheduler
50 //         // call epoll
51 //         // block all relevant signals again
52 //     }
53 //
54 //     // now handle the event
55 //
56 // The signal handler is then simply defined as
57 //
58 //     static void Scheduler::sigHandler(int signal)
59 //     {
60 //         // make sure to restore the signal handler here if
61 //         // necessary
62 //         longjmp(Scheduler::instance().jmpBuffer_,signal);
63 //     }
64 //
65 // You should use sigaction to register the signal handlers and define
66 // a sa_mask so all Scheduler-registered signals are automatically
67 // *blocked* whenever one of the signals is called (including the
68 // called signal!) (This also means, we will have to re-register all
69 // signals if we change the registration of some signal since the
70 // sa_mask changes). This ensures, that no two signals can be
71 // delivered on top of each other. And of course any signal registered
72 // with the scheduler must be blocked as soon as it is registered with
73 // the scheduler.
74
75 #include "Scheduler.hh"
76 //#include "Scheduler.ih"
77
78 // Custom includes
79 #include <errno.h>
80 #include <sys/epoll.h>
81 #include "../Utils/Exception.hh"
82
83 static const int EPollInitialSize = 16;
84
85 #define prefix_
86 ///////////////////////////////cc.p////////////////////////////////////////
87
88 prefix_ senf::Scheduler::Scheduler()
89     : timerIdCounter_(0), epollFd_ (epoll_create(EPollInitialSize)), terminate_(false),
90       eventTime_(0)
91 {
92     if (epollFd_<0)
93         throw SystemException(errno);
94 }
95
96 prefix_ void senf::Scheduler::do_add(int fd, SimpleCallback const & cb, int eventMask)
97 {
98     FdTable::iterator i (fdTable_.find(fd));
99     int action (EPOLL_CTL_MOD);
100     if (i == fdTable_.end()) {
101         action = EPOLL_CTL_ADD;
102         i = fdTable_.insert(std::make_pair(fd, EventSpec())).first;
103     }
104
105     if (eventMask & EV_READ)  i->second.cb_read = cb;
106     if (eventMask & EV_PRIO)  i->second.cb_prio = cb;
107     if (eventMask & EV_WRITE) i->second.cb_write = cb;
108
109     epoll_event ev;
110     memset(&ev,0,sizeof(ev));
111     ev.events = i->second.epollMask();
112     ev.data.fd = fd;
113
114     if (epoll_ctl(epollFd_, action, fd, &ev)<0)
115         throw SystemException(errno);
116 }
117
118 prefix_ void senf::Scheduler::do_remove(int fd, int eventMask)
119 {
120     FdTable::iterator i (fdTable_.find(fd));
121     if (i == fdTable_.end())
122         return;
123
124     if (eventMask & EV_READ)  i->second.cb_read = 0;
125     if (eventMask & EV_PRIO)  i->second.cb_prio = 0;
126     if (eventMask & EV_WRITE) i->second.cb_write = 0;
127
128     epoll_event ev;
129     memset(&ev,0,sizeof(ev));
130     ev.events = i->second.epollMask();
131     ev.data.fd = fd;
132
133     int action (EPOLL_CTL_MOD);
134     if (ev.events==0) {
135         action = EPOLL_CTL_DEL;
136         fdTable_.erase(i);
137     }
138
139     if (epoll_ctl(epollFd_, action, fd, &ev)<0)
140         throw SystemException(errno);
141 }
142
143
144 prefix_ int senf::Scheduler::EventSpec::epollMask()
145     const
146 {
147     int mask (0);
148     if (cb_read)  mask |= EPOLLIN;
149     if (cb_prio)  mask |= EPOLLPRI;
150     if (cb_write) mask |= EPOLLOUT;
151     return mask;
152 }
153
154 prefix_ void senf::Scheduler::process()
155 {
156     terminate_ = false;
157     eventTime_ = ClockService::now();
158     while (! terminate_) {
159
160         // Since a callback may have disabled further timers, we need to check for canceled timeouts
161         // again.
162
163         while (! timerQueue_.empty()) {
164             TimerMap::iterator i (timerQueue_.top());
165             if (! i->second.canceled)
166                 break;
167             timerMap_.erase(i);
168             timerQueue_.pop();
169         }
170
171         int timeout (-1);
172         if (timerQueue_.empty()) {
173             if (fdTable_.empty())
174                 break;
175         }
176         else {
177             ClockService::clock_type delta (
178                 (timerQueue_.top()->second.timeout - eventTime_)/1000000UL);
179             timeout = delta < 0 ? 0 : delta;
180         }
181
182         ///\todo Handle more than one epoll_event per call
183         struct epoll_event ev;
184         int events = epoll_wait(epollFd_, &ev, 1, timeout);
185         if (events<0)
186             if (errno != EINTR)
187                 throw SystemException(errno);
188
189         eventTime_ = ClockService::now();
190
191         // We always run event handlers. This is important, even if a file-descriptor is signaled
192         // since some descriptors (e.g. real files) will *always* be ready and we still may want to
193         // handle timers.
194         // Time handlers are run before file events to not delay them unnecessarily.
195
196         while (! timerQueue_.empty()) {
197             TimerMap::iterator i (timerQueue_.top());
198             if (i->second.canceled)
199                 ;
200             else if (i->second.timeout <= eventTime_)
201                 i->second.cb();
202             else
203                 break;
204             timerQueue_.pop();
205             timerMap_.erase(i);
206         }
207
208         if (events <= 0)
209             continue;
210
211         FdTable::iterator i = fdTable_.find(ev.data.fd);
212         BOOST_ASSERT (i != fdTable_.end() );
213         EventSpec spec (i->second);
214
215         unsigned extraFlags (0);
216         if (ev.events & EPOLLHUP) extraFlags |= EV_HUP;
217         if (ev.events & EPOLLERR) extraFlags |= EV_ERR;
218
219         if (ev.events & EPOLLIN) {
220             BOOST_ASSERT(spec.cb_read);
221             spec.cb_read(EventId(EV_READ | extraFlags));
222         }
223         else if (ev.events & EPOLLPRI) {
224             BOOST_ASSERT(spec.cb_prio);
225             spec.cb_prio(EventId(EV_PRIO | extraFlags));
226         }
227         else if (ev.events & EPOLLOUT) {
228             BOOST_ASSERT(spec.cb_write);
229             spec.cb_write(EventId(EV_WRITE | extraFlags));
230         }
231         else {
232             // This branch is only taken, if HUP or ERR is signaled but none of IN/OUT/PRI. 
233             // In this case we will signal all registered callbacks. The callbacks must be
234             // prepared to be called multiple times if they are registered to more than
235             // one event.
236             if (spec.cb_write) 
237                 spec.cb_write(EventId(extraFlags));
238             if (spec.cb_prio) 
239                 spec.cb_prio(EventId(extraFlags));
240             if (spec.cb_read) 
241                 spec.cb_read(EventId(extraFlags));
242         }
243     }
244 }
245
246 ///////////////////////////////////////////////////////////////////////////
247 // senf::SchedulerLogTimeSource
248
249 prefix_ boost::posix_time::ptime senf::SchedulerLogTimeSource::operator()()
250     const
251 {
252     return ClockService::abstime(Scheduler::instance().eventTime());
253 }
254
255 ///////////////////////////////cc.e////////////////////////////////////////
256 #undef prefix_
257
258 \f
259 // Local Variables:
260 // mode: c++
261 // fill-column: 100
262 // c-file-style: "senf"
263 // indent-tabs-mode: nil
264 // ispell-local-dictionary: "american"
265 // compile-command: "scons -u test"
266 // comment-column: 40
267 // End: