Packets: Add StringParser ostream operation
[senf.git] / Scheduler / FIFORunner.cc
1 // $Id$
2 //
3 // Copyright (C) 2008 
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.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 FIFORunner non-inline non-template implementation */
25
26 #include "FIFORunner.hh"
27 //#include "FIFORunner.ih"
28
29 // Custom includes
30 #include <signal.h>
31 #include <time.h>
32 #include <boost/lambda/lambda.hpp>
33 #include "../Utils/Exception.hh"
34 #include "../Utils/senfassert.hh"
35 #include "../Utils/ScopeExit.hh"
36
37 //#include "FIFORunner.mpp"
38 #define prefix_
39 ///////////////////////////////cc.p////////////////////////////////////////
40
41 prefix_ senf::scheduler::detail::FIFORunner::FIFORunner()
42     : tasks_ (), next_ (tasks_.end()), watchdogRunning_ (false), watchdogMs_ (1000), 
43       watchdogAbort_ (false), watchdogCount_(0), hangCount_ (0), yield_ (false)
44 {
45     struct sigevent ev;
46     ::memset(&ev, 0, sizeof(ev));
47     ev.sigev_notify = SIGEV_SIGNAL;
48     ev.sigev_signo = SIGURG;
49     ev.sigev_value.sival_ptr = this;
50     if (timer_create(CLOCK_MONOTONIC, &ev, &watchdogId_) < 0)
51         SENF_THROW_SYSTEM_EXCEPTION("timer_create()");
52
53     struct sigaction sa;
54     ::memset(&sa, 0, sizeof(sa));
55     sa.sa_sigaction = &watchdog;
56     sa.sa_flags = SA_SIGINFO;
57     if (sigaction(SIGURG, &sa, 0) < 0)
58         SENF_THROW_SYSTEM_EXCEPTION("sigaction()");
59
60     sigset_t mask;
61     sigemptyset(&mask);
62     sigaddset(&mask, SIGURG);
63     if (sigprocmask(SIG_UNBLOCK, &mask, 0) < 0)
64         SENF_THROW_SYSTEM_EXCEPTION("sigprocmask()");
65
66     tasks_.push_back(highPriorityEnd_);
67     tasks_.push_back(normalPriorityEnd_);
68 }
69
70 prefix_ senf::scheduler::detail::FIFORunner::~FIFORunner()
71 {
72     timer_delete(watchdogId_);
73     signal(SIGURG, SIG_DFL);
74 }
75
76 prefix_ void senf::scheduler::detail::FIFORunner::startWatchdog()
77 {
78     if (watchdogMs_ > 0) {
79         struct itimerspec timer;
80         ::memset(&timer, 0, sizeof(timer));
81
82         timer.it_interval.tv_sec = watchdogMs_ / 1000;
83         timer.it_interval.tv_nsec = (watchdogMs_ % 1000) * 1000000ul;
84         timer.it_value.tv_sec = timer.it_interval.tv_sec;
85         timer.it_value.tv_nsec = timer.it_interval.tv_nsec;
86         
87         if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
88             SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
89
90         watchdogRunning_ = true;
91     }
92     else
93         stopWatchdog();
94 }
95
96 prefix_ void senf::scheduler::detail::FIFORunner::stopWatchdog()
97 {
98     struct itimerspec timer;
99     ::memset(&timer, 0, sizeof(timer));
100
101     if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
102         SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
103
104     watchdogRunning_ = false;
105 }
106
107 // At the moment, the FIFORunner is not very efficient with many non-runnable tasks since the
108 // complete list of tasks is traversed on each run().
109 //
110 // To optimize this, we woould need a way to find the relative ordering of two tasks in O(1) (at the
111 // moment, this is an O(N) operation by traversing the list).
112 //
113 // One idea is, to give each task an 'order' value. Whenever a task is added at the end, it's order
114 // value is set to the order value of the last task + 1. Whenever the order value such added exceeds
115 // some threshold (e.g. 2^31 -1 or some such), the task list is traversed from beginning to end to
116 // assign new consecutive order values. This O(N) operation is so seldom, that it is amortized over
117 // a very long time.
118 //
119 // With this value at hand, we can do several optimizations: One idea would be the following: The
120 // runnable set always has two types of tasks: There are tasks, which are heavily active and are
121 // signaled constantly and other tasks which lie dormant most of the time. Those dormant tasks will
122 // end up at the beginning of the task queue.
123 //
124 // With the above defined 'ordering' field available, we can manage an iterator pointing to the
125 // first and the last runnable task. This will often help a lot since the group of runnable tasks
126 // will mostly be localized to the end of the queue. only occasionally one of the dormant tasks will
127 // be runnable. This additional traversal time will be amortized over a larger time.
128
129 prefix_ void senf::scheduler::detail::FIFORunner::dequeue(TaskInfo * task)
130 {
131     TaskList::iterator i (TaskList::current(*task));
132     if (next_ == i)
133         ++next_;
134     tasks_.erase(i);
135 }
136
137 prefix_ void senf::scheduler::detail::FIFORunner::run()
138 {
139     for(;;) {
140         TaskList::iterator f (tasks_.begin());
141         TaskList::iterator l (TaskList::current(highPriorityEnd_));
142         run(f, l);
143         if (yield_) {
144             yield_ = false;
145             continue;
146         }
147
148         f = l; ++f;
149         l = TaskList::current(normalPriorityEnd_);
150         run(f, l); 
151         if (yield_) {
152             yield_ = false;
153             continue;
154         }
155        
156         f = l; ++f;
157         l = tasks_.end();
158         run(f, l);
159         if (yield_) {
160             yield_ = false;
161             continue;
162         }
163         break;
164     }
165 }
166
167 prefix_ void senf::scheduler::detail::FIFORunner::run(TaskList::iterator f, TaskList::iterator l)
168 {
169     if (f == l)
170         // We'll have problems inserting NullTask between f and l below, so just explicitly bail out
171         return;
172
173     // This algorithm is carefully adjusted to make it work even when arbitrary tasks are removed
174     // from the queue
175     // - Before we begin, we add a NullTask to the queue. The only purpose of this node is, to mark
176     //   the current end of the queue. The iterator to this node becomes the end iterator of the
177     //   range to process
178     // - We update the TaskInfo and move it to the next queue Element before calling the callback so
179     //   we don't access the TaskInfo if it is removed while the callback is running
180     // - We keep the next to-be-processed node in a class variable which is checked and updated
181     //   whenever a node is removed.
182
183     NullTask null;
184     tasks_.insert(l, null);
185     TaskList::iterator end (TaskList::current(null));
186     next_ = f;
187
188     using namespace boost::lambda;
189     ScopeExit atExit ((
190                           var(watchdogCount_) = 0, 
191                           var(next_) = l
192                      ));
193     
194     while (next_ != end) {
195         TaskInfo & task (*next_);
196         if (task.runnable_) {
197             task.runnable_ = false;
198             runningName_ = task.name();
199 #       ifdef SENF_DEBUG
200             runningBacktrace_ = task.backtrace_;
201 #       endif
202             TaskList::iterator i (next_);
203             ++ next_;
204             tasks_.splice(l, tasks_, i);
205             watchdogCount_ = 1;
206             yield_ = false;
207             task.run();
208             if (yield_)
209                 return;
210         }
211         else
212             ++ next_;
213     }
214 }
215
216 prefix_ senf::scheduler::detail::FIFORunner::TaskList::iterator
217 senf::scheduler::detail::FIFORunner::priorityEnd(TaskInfo::Priority p)
218 {
219     switch (p) {
220     case senf::scheduler::detail::FIFORunner::TaskInfo::PRIORITY_LOW : 
221         return tasks_.end();
222     case senf::scheduler::detail::FIFORunner::TaskInfo::PRIORITY_NORMAL : 
223         return TaskList::current(normalPriorityEnd_);
224     case senf::scheduler::detail::FIFORunner::TaskInfo::PRIORITY_HIGH : 
225         return TaskList::current(highPriorityEnd_);
226     }
227     return tasks_.begin();
228 }
229
230 prefix_ void senf::scheduler::detail::FIFORunner::watchdog(int, siginfo_t * si, void *)
231 {
232     FIFORunner & runner (*static_cast<FIFORunner *>(si->si_value.sival_ptr));
233     if (runner.watchdogCount_ > 0) {
234         ++ runner.watchdogCount_;
235         if (runner.watchdogCount_ > 2) {
236             ++ runner.hangCount_;
237             write(1, "\n\n*** Scheduler task hanging: ", 30);
238             write(1, runner.runningName_.c_str(), runner.runningName_.size());
239             write(1, "\n", 1);
240 #ifdef SENF_DEBUG
241             write(1, "Task was initialized at\n", 24);
242             write(1, runner.runningBacktrace_.c_str(), runner.runningBacktrace_.size());
243 #endif
244             write(1, "\n", 1);
245             if (runner.watchdogAbort_)
246                 assert(false);
247         }
248     }
249 }
250
251 ///////////////////////////////cc.e////////////////////////////////////////
252 #undef prefix_
253 //#include "FIFORunner.mpp"
254
255 \f
256 // Local Variables:
257 // mode: c++
258 // fill-column: 100
259 // comment-column: 40
260 // c-file-style: "senf"
261 // indent-tabs-mode: nil
262 // ispell-local-dictionary: "american"
263 // compile-command: "scons -u test"
264 // End: