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