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"
36 #include <senf/config.hh>
39 #include <senf/Utils/Exception.hh>
40 #include <senf/Utils/senfassert.hh>
41 #include "senf/Utils/IgnoreValue.hh"
42 #include <senf/Utils/Console/ScopedDirectory.hh>
43 #include <senf/Utils/Console/ParsedCommand.hh>
44 #include "ConsoleDir.hh"
46 //#include "FIFORunner.mpp"
48 //-/////////////////////////////////////////////////////////////////////////////////////////////////
50 prefix_ senf::scheduler::detail::FIFORunner::FIFORunner()
51 : tasks_ (), next_ (tasks_.end()), watchdogRunning_ (false), watchdogMs_ (1000),
52 watchdogAbort_ (false), watchdogCount_(0), hangCount_ (0), yield_ (false)
55 ::memset(&ev, 0, sizeof(ev));
56 ev.sigev_notify = SIGEV_SIGNAL;
57 ev.sigev_signo = SIGURG;
58 ev.sigev_value.sival_ptr = this;
59 if (timer_create(CLOCK_MONOTONIC, &ev, &watchdogId_) < 0)
60 SENF_THROW_SYSTEM_EXCEPTION("timer_create()");
63 ::memset(&sa, 0, sizeof(sa));
64 sa.sa_sigaction = &watchdog;
65 sa.sa_flags = SA_SIGINFO;
66 if (sigaction(SIGURG, &sa, 0) < 0)
67 SENF_THROW_SYSTEM_EXCEPTION("sigaction()");
71 sigaddset(&mask, SIGURG);
72 if (sigprocmask(SIG_UNBLOCK, &mask, 0) < 0)
73 SENF_THROW_SYSTEM_EXCEPTION("sigprocmask()");
75 tasks_.push_back(highPriorityEnd_);
76 tasks_.push_back(normalPriorityEnd_);
78 #ifndef SENF_DISABLE_CONSOLE
79 namespace fty = console::factory;
80 consoleDir().add("abortOnWatchdocTimeout", fty::Command(
81 SENF_MEMBINDFNP( bool, FIFORunner, abortOnTimeout, () const ))
82 .doc("Get current watchdog abort on event status.") );
83 consoleDir().add("abortOnWatchdocTimeout", fty::Command(
84 SENF_MEMBINDFNP( void, FIFORunner, abortOnTimeout, (bool) ))
85 .doc("Enable/disable abort on watchdog event.") );
86 consoleDir().add("watchdogTimeout", fty::Command(
87 SENF_MEMBINDFNP( unsigned, FIFORunner, taskTimeout, () const ))
88 .doc("Get current watchdog timeout in milliseconds") );
89 consoleDir().add("watchdogTimeout", fty::Command(
90 SENF_MEMBINDFNP( void, FIFORunner, taskTimeout, (unsigned) ))
91 .doc("Set watchdog timeout to in milliseconds\n"
92 "Setting the watchdog timeout to 0 will disable the watchdog.") );
93 consoleDir().add("watchdogEvents", fty::Command(membind( &FIFORunner::hangCount, this))
94 .doc("Get number of occurred watchdog events.\n"
95 "Calling this method will reset the counter to 0") );
99 prefix_ senf::scheduler::detail::FIFORunner::~FIFORunner()
101 timer_delete(watchdogId_);
102 signal(SIGURG, SIG_DFL);
104 #ifndef SENF_DISABLE_CONSOLE
105 consoleDir().remove("abortOnWatchdocTimeout");
106 consoleDir().remove("watchdogTimeout");
107 consoleDir().remove("watchdogEvents");
111 prefix_ void senf::scheduler::detail::FIFORunner::startWatchdog()
113 if (watchdogMs_ > 0) {
114 struct itimerspec timer;
115 ::memset(&timer, 0, sizeof(timer));
117 timer.it_interval.tv_sec = watchdogMs_ / 1000;
118 timer.it_interval.tv_nsec = (watchdogMs_ % 1000) * 1000000ul;
119 timer.it_value.tv_sec = timer.it_interval.tv_sec;
120 timer.it_value.tv_nsec = timer.it_interval.tv_nsec;
122 if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
123 SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
125 watchdogRunning_ = true;
131 prefix_ void senf::scheduler::detail::FIFORunner::stopWatchdog()
133 struct itimerspec timer;
134 ::memset(&timer, 0, sizeof(timer));
136 if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
137 SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
139 watchdogRunning_ = false;
142 // At the moment, the FIFORunner is not very efficient with many non-runnable tasks since the
143 // complete list of tasks is traversed on each run().
145 // To optimize this, we would need a way to find the relative ordering of two tasks in O(1) (at the
146 // moment, this is an O(N) operation by traversing the list).
148 // One idea is, to give each task an 'order' value. Whenever a task is added at the end, it's order
149 // value is set to the order value of the last task + 1. Whenever the order value such added exceeds
150 // some threshold (e.g. 2^31 -1 or some such), the task list is traversed from beginning to end to
151 // assign new consecutive order values. This O(N) operation is so seldom, that it is amortized over
154 // With this value at hand, we can do several optimizations: One idea would be the following: The
155 // runnable set always has two types of tasks: There are tasks, which are heavily active and are
156 // signaled constantly and other tasks which lie dormant most of the time. Those dormant tasks will
157 // end up at the beginning of the task queue.
159 // With the above defined 'ordering' field available, we can manage an iterator pointing to the
160 // first and the last runnable task. This will often help a lot since the group of runnable tasks
161 // will mostly be localized to the end of the queue. only occasionally one of the dormant tasks will
162 // be runnable. This additional traversal time will be amortized over a larger time.
164 prefix_ void senf::scheduler::detail::FIFORunner::dequeue(TaskInfo * task)
166 TaskList::iterator i (TaskList::current(*task));
172 prefix_ void senf::scheduler::detail::FIFORunner::run()
175 TaskList::iterator f (tasks_.begin());
176 TaskList::iterator l (TaskList::current(highPriorityEnd_));
184 l = TaskList::current(normalPriorityEnd_);
202 prefix_ void senf::scheduler::detail::FIFORunner::run(TaskList::iterator f, TaskList::iterator l)
205 // We'll have problems inserting NullTask between f and l below, so just explicitly bail out
208 // This algorithm is carefully adjusted to make it work even when arbitrary tasks are removed
210 // - Before we begin, we add a NullTask to the queue. The only purpose of this node is, to mark
211 // the current end of the queue. The iterator to this node becomes the end iterator of the
213 // - We update the TaskInfo and move it to the next queue Element before calling the callback so
214 // we don't access the TaskInfo if it is removed while the callback is running
215 // - We keep the next to-be-processed node in a class variable which is checked and updated
216 // whenever a node is removed.
219 tasks_.insert(l, null);
220 TaskList::iterator end (TaskList::current(null));
223 // Would prefer to use ScopeExit+boost::lambda here instead of try but profiling has shown that
224 // to be to costly here
227 while (next_ != end) {
228 TaskInfo & task (*next_);
229 if (task.runnable_) {
230 task.runnable_ = false;
231 runningName_ = task.name();
233 runningBacktrace_ = task.backtrace_;
235 TaskList::iterator i (next_);
237 tasks_.splice(l, tasks_, i);
257 prefix_ senf::scheduler::detail::FIFORunner::TaskList::iterator
258 senf::scheduler::detail::FIFORunner::priorityEnd(TaskInfo::Priority p)
261 case TaskInfo::PRIORITY_LOW :
263 case TaskInfo::PRIORITY_NORMAL :
264 return TaskList::current(normalPriorityEnd_);
265 case TaskInfo::PRIORITY_HIGH :
266 return TaskList::current(highPriorityEnd_);
268 return tasks_.begin();
271 prefix_ void senf::scheduler::detail::FIFORunner::watchdog(int, siginfo_t * si, void *)
273 FIFORunner & runner (*static_cast<FIFORunner *>(si->si_value.sival_ptr));
274 if (runner.watchdogCount_ > 0) {
275 ++ runner.watchdogCount_;
276 if (runner.watchdogCount_ > 2) {
277 ++ runner.hangCount_;
278 runner.watchdogError();
283 prefix_ void senf::scheduler::detail::FIFORunner::watchdogError()
285 // We don't care if the write commands below fail, we just give our best to inform the user
286 senf::IGNORE( write(1, "\n\n*** Scheduler task hanging (pid ",34) );
288 ::snprintf(pid, 7, "%6d", ::getpid());
290 senf::IGNORE( write(1, pid, 6) );
291 senf::IGNORE( write(1, "): ", 3) );
292 senf::IGNORE( write(1, runningName_.c_str(), runningName_.size()) );
293 senf::IGNORE( write(1, " at\n ", 3) );
295 static char const hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
296 'a', 'b', 'c', 'd', 'e', 'f' };
297 static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
298 unsigned nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
299 for (unsigned i (0); i < nEntries; ++i) {
300 senf::IGNORE( write(1, " 0x", 3) );
301 for (unsigned j (sizeof(void*)); j > 0; --j) {
302 uintptr_t v ( reinterpret_cast<uintptr_t>(entries[i]) >> (8*(j-1)) );
303 senf::IGNORE( write(1, &(hex[ (v >> 4) & 0x0f ]), 1) );
304 senf::IGNORE( write(1, &(hex[ (v ) & 0x0f ]), 1) );
308 senf::IGNORE( write(1, "\n", 1) );
311 senf::IGNORE( write(1, "Task was initialized at\n", 24) );
312 senf::IGNORE( write(1, runningBacktrace_.c_str(), runningBacktrace_.size()) );
314 senf::IGNORE( write(1, "\n", 1) );
319 //-/////////////////////////////////////////////////////////////////////////////////////////////////
321 //#include "FIFORunner.mpp"
327 // comment-column: 40
328 // c-file-style: "senf"
329 // indent-tabs-mode: nil
330 // ispell-local-dictionary: "american"
331 // compile-command: "scons -u test"