177a874f837e13654a7420d8970e3ef4b7c8b811
[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 {
91     if (epollFd_<0)
92         throw SystemException(errno);
93 }
94
95 prefix_ void senf::Scheduler::do_add(int fd, SimpleCallback const & cb, int eventMask)
96 {
97     FdTable::iterator i (fdTable_.find(fd));
98     int action (EPOLL_CTL_MOD);
99     if (i == fdTable_.end()) {
100         action = EPOLL_CTL_ADD;
101         i = fdTable_.insert(std::make_pair(fd, EventSpec())).first;
102     }
103
104     if (eventMask & EV_READ)  i->second.cb_read = cb;
105     if (eventMask & EV_PRIO)  i->second.cb_prio = cb;
106     if (eventMask & EV_WRITE) i->second.cb_write = cb;
107
108     epoll_event ev;
109     memset(&ev,0,sizeof(ev));
110     ev.events = i->second.epollMask();
111     ev.data.fd = fd;
112
113     if (epoll_ctl(epollFd_, action, fd, &ev)<0)
114         throw SystemException(errno);
115 }
116
117 prefix_ void senf::Scheduler::do_remove(int fd, int eventMask)
118 {
119     FdTable::iterator i (fdTable_.find(fd));
120     if (i == fdTable_.end())
121         return;
122
123     if (eventMask & EV_READ)  i->second.cb_read = 0;
124     if (eventMask & EV_PRIO)  i->second.cb_prio = 0;
125     if (eventMask & EV_WRITE) i->second.cb_write = 0;
126
127     epoll_event ev;
128     memset(&ev,0,sizeof(ev));
129     ev.events = i->second.epollMask();
130     ev.data.fd = fd;
131
132     int action (EPOLL_CTL_MOD);
133     if (ev.events==0) {
134         action = EPOLL_CTL_DEL;
135         fdTable_.erase(i);
136     }
137
138     if (epoll_ctl(epollFd_, action, fd, &ev)<0)
139         throw SystemException(errno);
140 }
141
142
143 prefix_ int senf::Scheduler::EventSpec::epollMask()
144     const
145 {
146     int mask (0);
147     if (cb_read)  mask |= EPOLLIN;
148     if (cb_prio)  mask |= EPOLLPRI;
149     if (cb_write) mask |= EPOLLOUT;
150     return mask;
151 }
152
153 prefix_ void senf::Scheduler::process()
154 {
155     terminate_ = false;
156     while (! terminate_) {
157         ClockService::clock_type timeNow = ClockService::now();
158
159         while ( ! timerQueue_.empty() && timerQueue_.top()->second.timeout <= timeNow ) {
160             TimerMap::iterator i (timerQueue_.top());
161             if (! i->second.canceled)
162                 i->second.cb();
163             timerMap_.erase(i);
164             timerQueue_.pop();
165         }
166
167         if (terminate_)
168             return;
169
170         int timeout (MinTimeout);
171         if (! timerQueue_.empty()) {
172             ClockService::clock_type delta (
173                 (timerQueue_.top()->second.timeout - timeNow)/1000000UL);
174             if (delta<MinTimeout)
175                 timeout = int(delta);
176         }
177
178         struct epoll_event ev;
179         int events = epoll_wait(epollFd_, &ev, 1, timeout);
180         if (events<0)
181             // 'man epoll' says, epoll will not return with EINTR.
182             throw SystemException(errno);
183         if (events==0)
184             // Timeout .. the handler will be run when going back to the loop top
185             continue;
186
187         FdTable::iterator i = fdTable_.find(ev.data.fd);
188         BOOST_ASSERT (i != fdTable_.end() );
189         EventSpec spec (i->second);
190
191         unsigned extraFlags (0);
192         if (ev.events & EPOLLHUP) extraFlags |= EV_HUP;
193         if (ev.events & EPOLLERR) extraFlags |= EV_ERR;
194
195         if (ev.events & EPOLLIN) {
196             BOOST_ASSERT(spec.cb_read);
197             spec.cb_read(EventId(EV_READ | extraFlags));
198         }
199         else if (ev.events & EPOLLPRI) {
200             BOOST_ASSERT(spec.cb_prio);
201             spec.cb_prio(EventId(EV_PRIO | extraFlags));
202         }
203         else if (ev.events & EPOLLOUT) {
204             BOOST_ASSERT(spec.cb_write);
205             spec.cb_write(EventId(EV_WRITE | extraFlags));
206         }
207         else {
208             // This branch is only taken, if HUP or ERR is signaled but none of IN/OUT/PRI. 
209             // In this case we will signal all registered callbacks. The callbacks must be
210             // prepared to be called multiple times if they are registered to more than
211             // one event.
212             if (spec.cb_write) 
213                 spec.cb_write(EventId(extraFlags));
214             if (spec.cb_prio) 
215                 spec.cb_prio(EventId(extraFlags));
216             if (spec.cb_read) 
217                 spec.cb_read(EventId(extraFlags));
218         }
219     }
220 }
221
222 ///////////////////////////////cc.e////////////////////////////////////////
223 #undef prefix_
224
225 \f
226 // Local Variables:
227 // mode: c++
228 // fill-column: 100
229 // c-file-style: "senf"
230 // indent-tabs-mode: nil
231 // ispell-local-dictionary: "american"
232 // compile-command: "scons -u test"
233 // comment-column: 40
234 // End: