4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
6 // The contents of this file are subject to the Fraunhofer FOKUS Public License
7 // Version 1.0 (the "License"); you may not use this file except in compliance
8 // with the License. You may obtain a copy of the License at
9 // http://senf.berlios.de/license.html
11 // The Fraunhofer FOKUS Public License Version 1.0 is based on,
12 // but modifies the Mozilla Public License Version 1.1.
13 // See the full license text for the amendments.
15 // Software distributed under the License is distributed on an "AS IS" basis,
16 // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
17 // for the specific language governing rights and limitations under the License.
19 // The Original Code is Fraunhofer FOKUS code.
21 // The Initial Developer of the Original Code is Fraunhofer-Gesellschaft e.V.
22 // (registered association), Hansastraße 27 c, 80686 Munich, Germany.
23 // All Rights Reserved.
26 // Stefan Bund <g0dil@berlios.de>
29 \brief FIFORunner non-inline non-template implementation */
31 #include "FIFORunner.hh"
32 //#include "FIFORunner.ih"
38 #include <senf/config.hh>
44 #include <senf/Utils/Exception.hh>
45 #include "senf/Utils/IgnoreValue.hh"
46 #include <senf/Utils/Console/ScopedDirectory.hh>
47 #include <senf/Utils/Console/ParsedCommand.hh>
48 #include "ConsoleDir.hh"
50 //#include "FIFORunner.mpp"
52 //-/////////////////////////////////////////////////////////////////////////////////////////////////
54 prefix_ senf::scheduler::detail::FIFORunner::FIFORunner()
55 : tasks_ (), next_ (tasks_.end()), watchdogRunning_ (false), watchdogMs_ (1000),
56 watchdogAbort_ (false), watchdogCount_(0), hangCount_ (0), yield_ (false)
59 ::memset(&ev, 0, sizeof(ev));
60 ev.sigev_notify = SIGEV_SIGNAL;
61 ev.sigev_signo = SIGURG;
62 ev.sigev_value.sival_ptr = this;
63 if (timer_create(CLOCK_MONOTONIC, &ev, &watchdogId_) < 0)
64 SENF_THROW_SYSTEM_EXCEPTION("timer_create()");
67 ::memset(&sa, 0, sizeof(sa));
68 sa.sa_sigaction = &watchdog;
69 sa.sa_flags = SA_SIGINFO;
70 if (sigaction(SIGURG, &sa, 0) < 0)
71 SENF_THROW_SYSTEM_EXCEPTION("sigaction()");
75 sigaddset(&mask, SIGURG);
76 if (sigprocmask(SIG_UNBLOCK, &mask, 0) < 0)
77 SENF_THROW_SYSTEM_EXCEPTION("sigprocmask()");
79 tasks_.push_back(highPriorityEnd_);
80 tasks_.push_back(normalPriorityEnd_);
82 #ifndef SENF_DISABLE_CONSOLE
83 namespace fty = console::factory;
84 consoleDir().add("abortOnWatchdocTimeout", fty::Command(
85 SENF_MEMBINDFNP( bool, FIFORunner, abortOnTimeout, () const ))
86 .doc("Get current watchdog abort on event status.") );
87 consoleDir().add("abortOnWatchdocTimeout", fty::Command(
88 SENF_MEMBINDFNP( void, FIFORunner, abortOnTimeout, (bool) ))
89 .doc("Enable/disable abort on watchdog event.") );
90 consoleDir().add("watchdogTimeout", fty::Command(
91 SENF_MEMBINDFNP( unsigned, FIFORunner, taskTimeout, () const ))
92 .doc("Get current watchdog timeout in milliseconds") );
93 consoleDir().add("watchdogTimeout", fty::Command(
94 SENF_MEMBINDFNP( void, FIFORunner, taskTimeout, (unsigned) ))
95 .doc("Set watchdog timeout to in milliseconds\n"
96 "Setting the watchdog timeout to 0 will disable the watchdog.") );
97 consoleDir().add("watchdogEvents", fty::Command(membind( &FIFORunner::hangCount, this))
98 .doc("Get number of occurred watchdog events.\n"
99 "Calling this method will reset the counter to 0") );
103 prefix_ senf::scheduler::detail::FIFORunner::~FIFORunner()
105 timer_delete(watchdogId_);
106 signal(SIGURG, SIG_DFL);
108 #ifndef SENF_DISABLE_CONSOLE
109 consoleDir().remove("abortOnWatchdocTimeout");
110 consoleDir().remove("watchdogTimeout");
111 consoleDir().remove("watchdogEvents");
115 prefix_ void senf::scheduler::detail::FIFORunner::startWatchdog()
117 if (watchdogMs_ > 0) {
118 struct itimerspec timer;
119 ::memset(&timer, 0, sizeof(timer));
121 timer.it_interval.tv_sec = watchdogMs_ / 1000;
122 timer.it_interval.tv_nsec = (watchdogMs_ % 1000) * 1000000ul;
123 timer.it_value.tv_sec = timer.it_interval.tv_sec;
124 timer.it_value.tv_nsec = timer.it_interval.tv_nsec;
126 if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
127 SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
129 watchdogRunning_ = true;
135 prefix_ void senf::scheduler::detail::FIFORunner::stopWatchdog()
137 struct itimerspec timer;
138 ::memset(&timer, 0, sizeof(timer));
140 if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
141 SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
143 watchdogRunning_ = false;
146 // At the moment, the FIFORunner is not very efficient with many non-runnable tasks since the
147 // complete list of tasks is traversed on each run().
149 // To optimize this, we would need a way to find the relative ordering of two tasks in O(1) (at the
150 // moment, this is an O(N) operation by traversing the list).
152 // One idea is, to give each task an 'order' value. Whenever a task is added at the end, it's order
153 // value is set to the order value of the last task + 1. Whenever the order value such added exceeds
154 // some threshold (e.g. 2^31 -1 or some such), the task list is traversed from beginning to end to
155 // assign new consecutive order values. This O(N) operation is so seldom, that it is amortized over
158 // With this value at hand, we can do several optimizations: One idea would be the following: The
159 // runnable set always has two types of tasks: There are tasks, which are heavily active and are
160 // signaled constantly and other tasks which lie dormant most of the time. Those dormant tasks will
161 // end up at the beginning of the task queue.
163 // With the above defined 'ordering' field available, we can manage an iterator pointing to the
164 // first and the last runnable task. This will often help a lot since the group of runnable tasks
165 // will mostly be localized to the end of the queue. only occasionally one of the dormant tasks will
166 // be runnable. This additional traversal time will be amortized over a larger time.
168 prefix_ void senf::scheduler::detail::FIFORunner::dequeue(TaskInfo * task)
170 TaskList::iterator i (TaskList::current(*task));
176 prefix_ void senf::scheduler::detail::FIFORunner::run()
179 TaskList::iterator f (tasks_.begin());
180 TaskList::iterator l (TaskList::current(highPriorityEnd_));
188 l = TaskList::current(normalPriorityEnd_);
206 prefix_ void senf::scheduler::detail::FIFORunner::run(TaskList::iterator f, TaskList::iterator l)
209 // We'll have problems inserting NullTask between f and l below, so just explicitly bail out
212 // This algorithm is carefully adjusted to make it work even when arbitrary tasks are removed
214 // - Before we begin, we add a NullTask to the queue. The only purpose of this node is, to mark
215 // the current end of the queue. The iterator to this node becomes the end iterator of the
217 // - We update the TaskInfo and move it to the next queue Element before calling the callback so
218 // we don't access the TaskInfo if it is removed while the callback is running
219 // - We keep the next to-be-processed node in a class variable which is checked and updated
220 // whenever a node is removed.
223 tasks_.insert(l, null);
224 TaskList::iterator end (TaskList::current(null));
227 // Would prefer to use ScopeExit+boost::lambda here instead of try but profiling has shown that
228 // to be to costly here
231 while (next_ != end) {
232 TaskInfo & task (*next_);
233 if (task.runnable_) {
234 task.runnable_ = false;
235 runningName_ = task.name();
236 # ifdef SENF_BACKTRACE
237 runningBacktrace_ = task.backtrace_;
239 TaskList::iterator i (next_);
241 tasks_.splice(l, tasks_, i);
261 prefix_ senf::scheduler::detail::FIFORunner::TaskList::iterator
262 senf::scheduler::detail::FIFORunner::priorityEnd(TaskInfo::Priority p)
265 case TaskInfo::PRIORITY_LOW :
267 case TaskInfo::PRIORITY_NORMAL :
268 return TaskList::current(normalPriorityEnd_);
269 case TaskInfo::PRIORITY_HIGH :
270 return TaskList::current(highPriorityEnd_);
272 return tasks_.begin();
275 prefix_ void senf::scheduler::detail::FIFORunner::watchdog(int, siginfo_t * si, void *)
277 FIFORunner & runner (*static_cast<FIFORunner *>(si->si_value.sival_ptr));
278 if (runner.watchdogCount_ > 0) {
279 ++ runner.watchdogCount_;
280 if (runner.watchdogCount_ > 2) {
281 ++ runner.hangCount_;
282 runner.watchdogError();
287 prefix_ void senf::scheduler::detail::FIFORunner::watchdogError()
289 // We don't care if the write commands below fail, we just give our best to inform the user
290 senf::IGNORE( write(1, "\n\n*** Scheduler task hanging (pid ",34) );
292 ::snprintf(pid, 7, "%6d", ::getpid());
294 senf::IGNORE( write(1, pid, 6) );
295 senf::IGNORE( write(1, "): ", 3) );
296 senf::IGNORE( write(1, runningName_.c_str(), runningName_.size()) );
297 /* senf::IGNORE( write(1, " at\n ", 3) );
298 #ifdef SENF_BACKTRACE
299 static char const hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
300 'a', 'b', 'c', 'd', 'e', 'f' };
301 static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
302 int nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
303 for (int i=0; i < nEntries; ++i) {
304 senf::IGNORE( write(1, " 0x", 3) );
305 for (unsigned j (sizeof(void*)); j > 0; --j) {
306 uintptr_t v ( reinterpret_cast<uintptr_t>(entries[i]) >> (8*(j-1)) );
307 senf::IGNORE( write(1, &(hex[ (v >> 4) & 0x0f ]), 1) );
308 senf::IGNORE( write(1, &(hex[ (v ) & 0x0f ]), 1) );
312 senf::IGNORE( write(1, "\n", 1) );
314 #ifdef SENF_BACKTRACE
315 senf::IGNORE( write(1, "Task was initialized at\n", 24) );
316 senf::IGNORE( write(1, runningBacktrace_.c_str(), runningBacktrace_.size()) );
318 senf::IGNORE( write(1, "\n", 1) );
323 //-/////////////////////////////////////////////////////////////////////////////////////////////////
325 //#include "FIFORunner.mpp"
331 // comment-column: 40
332 // c-file-style: "senf"
333 // indent-tabs-mode: nil
334 // ispell-local-dictionary: "american"
335 // compile-command: "scons -u test"