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