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