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