4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 // Stefan Bund <g0dil@berlios.de>
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.
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.
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.
24 \brief FIFORunner non-inline non-template implementation */
26 #include "FIFORunner.hh"
27 //#include "FIFORunner.ih"
38 #include <senf/Utils/Exception.hh>
39 #include <senf/Utils/senfassert.hh>
40 #include "senf/Utils/IgnoreValue.hh"
41 #include <senf/Utils/Console/ScopedDirectory.hh>
42 #include <senf/Utils/Console/ParsedCommand.hh>
43 #include "ConsoleDir.hh"
45 //#include "FIFORunner.mpp"
47 //-/////////////////////////////////////////////////////////////////////////////////////////////////
49 prefix_ senf::scheduler::detail::FIFORunner::FIFORunner()
50 : tasks_ (), next_ (tasks_.end()), watchdogRunning_ (false), watchdogMs_ (1000),
51 watchdogAbort_ (false), watchdogCount_(0), hangCount_ (0), yield_ (false)
54 ::memset(&ev, 0, sizeof(ev));
55 ev.sigev_notify = SIGEV_SIGNAL;
56 ev.sigev_signo = SIGURG;
57 ev.sigev_value.sival_ptr = this;
58 if (timer_create(CLOCK_MONOTONIC, &ev, &watchdogId_) < 0)
59 SENF_THROW_SYSTEM_EXCEPTION("timer_create()");
62 ::memset(&sa, 0, sizeof(sa));
63 sa.sa_sigaction = &watchdog;
64 sa.sa_flags = SA_SIGINFO;
65 if (sigaction(SIGURG, &sa, 0) < 0)
66 SENF_THROW_SYSTEM_EXCEPTION("sigaction()");
70 sigaddset(&mask, SIGURG);
71 if (sigprocmask(SIG_UNBLOCK, &mask, 0) < 0)
72 SENF_THROW_SYSTEM_EXCEPTION("sigprocmask()");
74 tasks_.push_back(highPriorityEnd_);
75 tasks_.push_back(normalPriorityEnd_);
77 #ifndef SENF_DISABLE_CONSOLE
78 namespace fty = console::factory;
79 consoleDir().add("abortOnWatchdocTimeout", fty::Command(
80 SENF_MEMBINDFNP( bool, FIFORunner, abortOnTimeout, () const ))
81 .doc("Get current watchdog abort on event status.") );
82 consoleDir().add("abortOnWatchdocTimeout", fty::Command(
83 SENF_MEMBINDFNP( void, FIFORunner, abortOnTimeout, (bool) ))
84 .doc("Enable/disable abort on watchdog event.") );
85 consoleDir().add("watchdogTimeout", fty::Command(
86 SENF_MEMBINDFNP( unsigned, FIFORunner, taskTimeout, () const ))
87 .doc("Get current watchdog timeout in milliseconds") );
88 consoleDir().add("watchdogTimeout", fty::Command(
89 SENF_MEMBINDFNP( void, FIFORunner, taskTimeout, (unsigned) ))
90 .doc("Set watchdog timeout to in milliseconds\n"
91 "Setting the watchdog timeout to 0 will disable the watchdog.") );
92 consoleDir().add("watchdogEvents", fty::Command(membind( &FIFORunner::hangCount, this))
93 .doc("Get number of occurred watchdog events.\n"
94 "Calling this method will reset the counter to 0") );
98 prefix_ senf::scheduler::detail::FIFORunner::~FIFORunner()
100 timer_delete(watchdogId_);
101 signal(SIGURG, SIG_DFL);
103 #ifndef SENF_DISABLE_CONSOLE
104 consoleDir().remove("abortOnWatchdocTimeout");
105 consoleDir().remove("watchdogTimeout");
106 consoleDir().remove("watchdogEvents");
110 prefix_ void senf::scheduler::detail::FIFORunner::startWatchdog()
112 if (watchdogMs_ > 0) {
113 struct itimerspec timer;
114 ::memset(&timer, 0, sizeof(timer));
116 timer.it_interval.tv_sec = watchdogMs_ / 1000;
117 timer.it_interval.tv_nsec = (watchdogMs_ % 1000) * 1000000ul;
118 timer.it_value.tv_sec = timer.it_interval.tv_sec;
119 timer.it_value.tv_nsec = timer.it_interval.tv_nsec;
121 if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
122 SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
124 watchdogRunning_ = true;
130 prefix_ void senf::scheduler::detail::FIFORunner::stopWatchdog()
132 struct itimerspec timer;
133 ::memset(&timer, 0, sizeof(timer));
135 if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
136 SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
138 watchdogRunning_ = false;
141 // At the moment, the FIFORunner is not very efficient with many non-runnable tasks since the
142 // complete list of tasks is traversed on each run().
144 // To optimize this, we would need a way to find the relative ordering of two tasks in O(1) (at the
145 // moment, this is an O(N) operation by traversing the list).
147 // One idea is, to give each task an 'order' value. Whenever a task is added at the end, it's order
148 // value is set to the order value of the last task + 1. Whenever the order value such added exceeds
149 // some threshold (e.g. 2^31 -1 or some such), the task list is traversed from beginning to end to
150 // assign new consecutive order values. This O(N) operation is so seldom, that it is amortized over
153 // With this value at hand, we can do several optimizations: One idea would be the following: The
154 // runnable set always has two types of tasks: There are tasks, which are heavily active and are
155 // signaled constantly and other tasks which lie dormant most of the time. Those dormant tasks will
156 // end up at the beginning of the task queue.
158 // With the above defined 'ordering' field available, we can manage an iterator pointing to the
159 // first and the last runnable task. This will often help a lot since the group of runnable tasks
160 // will mostly be localized to the end of the queue. only occasionally one of the dormant tasks will
161 // be runnable. This additional traversal time will be amortized over a larger time.
163 prefix_ void senf::scheduler::detail::FIFORunner::dequeue(TaskInfo * task)
165 TaskList::iterator i (TaskList::current(*task));
171 prefix_ void senf::scheduler::detail::FIFORunner::run()
174 TaskList::iterator f (tasks_.begin());
175 TaskList::iterator l (TaskList::current(highPriorityEnd_));
183 l = TaskList::current(normalPriorityEnd_);
201 prefix_ void senf::scheduler::detail::FIFORunner::run(TaskList::iterator f, TaskList::iterator l)
204 // We'll have problems inserting NullTask between f and l below, so just explicitly bail out
207 // This algorithm is carefully adjusted to make it work even when arbitrary tasks are removed
209 // - Before we begin, we add a NullTask to the queue. The only purpose of this node is, to mark
210 // the current end of the queue. The iterator to this node becomes the end iterator of the
212 // - We update the TaskInfo and move it to the next queue Element before calling the callback so
213 // we don't access the TaskInfo if it is removed while the callback is running
214 // - We keep the next to-be-processed node in a class variable which is checked and updated
215 // whenever a node is removed.
218 tasks_.insert(l, null);
219 TaskList::iterator end (TaskList::current(null));
222 // Would prefer to use ScopeExit+boost::lambda here instead of try but profiling has shown that
223 // to be to costly here
226 while (next_ != end) {
227 TaskInfo & task (*next_);
228 if (task.runnable_) {
229 task.runnable_ = false;
230 runningName_ = task.name();
231 # ifdef SENF_BACKTRACE
232 runningBacktrace_ = task.backtrace_;
234 TaskList::iterator i (next_);
236 tasks_.splice(l, tasks_, i);
256 prefix_ senf::scheduler::detail::FIFORunner::TaskList::iterator
257 senf::scheduler::detail::FIFORunner::priorityEnd(TaskInfo::Priority p)
260 case TaskInfo::PRIORITY_LOW :
262 case TaskInfo::PRIORITY_NORMAL :
263 return TaskList::current(normalPriorityEnd_);
264 case TaskInfo::PRIORITY_HIGH :
265 return TaskList::current(highPriorityEnd_);
267 return tasks_.begin();
270 prefix_ void senf::scheduler::detail::FIFORunner::watchdog(int, siginfo_t * si, void *)
272 FIFORunner & runner (*static_cast<FIFORunner *>(si->si_value.sival_ptr));
273 if (runner.watchdogCount_ > 0) {
274 ++ runner.watchdogCount_;
275 if (runner.watchdogCount_ > 2) {
276 ++ runner.hangCount_;
277 runner.watchdogError();
282 prefix_ void senf::scheduler::detail::FIFORunner::watchdogError()
284 // We don't care if the write commands below fail, we just give our best to inform the user
285 senf::IGNORE( write(1, "\n\n*** Scheduler task hanging (pid ",34) );
287 ::snprintf(pid, 7, "%6d", ::getpid());
289 senf::IGNORE( write(1, pid, 6) );
290 senf::IGNORE( write(1, "): ", 3) );
291 senf::IGNORE( write(1, runningName_.c_str(), runningName_.size()) );
292 senf::IGNORE( write(1, " at\n ", 3) );
293 #ifdef SENF_BACKTRACE
294 static char const hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
295 'a', 'b', 'c', 'd', 'e', 'f' };
296 static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
297 unsigned nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
298 for (unsigned i (0); i < nEntries; ++i) {
299 senf::IGNORE( write(1, " 0x", 3) );
300 for (unsigned j (sizeof(void*)); j > 0; --j) {
301 uintptr_t v ( reinterpret_cast<uintptr_t>(entries[i]) >> (8*(j-1)) );
302 senf::IGNORE( write(1, &(hex[ (v >> 4) & 0x0f ]), 1) );
303 senf::IGNORE( write(1, &(hex[ (v ) & 0x0f ]), 1) );
307 senf::IGNORE( write(1, "\n", 1) );
310 senf::IGNORE( write(1, "Task was initialized at\n", 24) );
311 senf::IGNORE( write(1, runningBacktrace_.c_str(), runningBacktrace_.size()) );
313 senf::IGNORE( write(1, "\n", 1) );
318 //-/////////////////////////////////////////////////////////////////////////////////////////////////
320 //#include "FIFORunner.mpp"
326 // comment-column: 40
327 // c-file-style: "senf"
328 // indent-tabs-mode: nil
329 // ispell-local-dictionary: "american"
330 // compile-command: "scons -u test"