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