On x86 compilers without fastcall, simulate it when invoking traces and un-simulate...
[wine-gecko.git] / xpcom / threads / TimerThread.cpp
blobc9e5a8bb3f03bea99c7dbde099ac8032afa12a78
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
17 * The Original Code is mozilla.org code.
19 * The Initial Developer of the Original Code is
20 * Netscape Communications Corporation.
21 * Portions created by the Initial Developer are Copyright (C) 2001
22 * the Initial Developer. All Rights Reserved.
24 * Contributor(s):
25 * Stuart Parmenter <pavlov@netscape.com>
27 * Alternatively, the contents of this file may be used under the terms of
28 * either of the GNU General Public License Version 2 or later (the "GPL"),
29 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
39 * ***** END LICENSE BLOCK ***** */
41 #include "nsTimerImpl.h"
42 #include "TimerThread.h"
44 #include "nsAutoLock.h"
45 #include "nsThreadUtils.h"
46 #include "pratom.h"
48 #include "nsIObserverService.h"
49 #include "nsIServiceManager.h"
50 #include "nsIProxyObjectManager.h"
52 NS_IMPL_THREADSAFE_ISUPPORTS2(TimerThread, nsIRunnable, nsIObserver)
54 TimerThread::TimerThread() :
55 mInitInProgress(0),
56 mInitialized(PR_FALSE),
57 mLock(nsnull),
58 mCondVar(nsnull),
59 mShutdown(PR_FALSE),
60 mWaiting(PR_FALSE),
61 mSleeping(PR_FALSE),
62 mDelayLineCounter(0),
63 mMinTimerPeriod(0),
64 mTimeoutAdjustment(0)
68 TimerThread::~TimerThread()
70 if (mCondVar)
71 PR_DestroyCondVar(mCondVar);
72 if (mLock)
73 PR_DestroyLock(mLock);
75 mThread = nsnull;
77 NS_ASSERTION(mTimers.Count() == 0, "Timers remain in TimerThread::~TimerThread");
80 nsresult
81 TimerThread::InitLocks()
83 NS_ASSERTION(!mLock, "InitLocks called twice?");
84 mLock = PR_NewLock();
85 if (!mLock)
86 return NS_ERROR_OUT_OF_MEMORY;
88 mCondVar = PR_NewCondVar(mLock);
89 if (!mCondVar)
90 return NS_ERROR_OUT_OF_MEMORY;
92 return NS_OK;
95 nsresult TimerThread::Init()
97 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("TimerThread::Init [%d]\n", mInitialized));
99 if (mInitialized) {
100 if (!mThread)
101 return NS_ERROR_FAILURE;
103 return NS_OK;
106 if (PR_AtomicSet(&mInitInProgress, 1) == 0) {
107 // We hold on to mThread to keep the thread alive.
108 nsresult rv = NS_NewThread(getter_AddRefs(mThread), this);
109 if (NS_FAILED(rv)) {
110 mThread = nsnull;
112 else {
113 nsCOMPtr<nsIObserverService> observerService =
114 do_GetService("@mozilla.org/observer-service;1");
115 // We must not use the observer service from a background thread!
116 if (observerService && !NS_IsMainThread()) {
117 nsCOMPtr<nsIObserverService> result = nsnull;
118 NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
119 NS_GET_IID(nsIObserverService),
120 observerService, NS_PROXY_ASYNC,
121 getter_AddRefs(result));
122 observerService.swap(result);
124 // We'll be released at xpcom shutdown
125 if (observerService) {
126 observerService->AddObserver(this, "sleep_notification", PR_FALSE);
127 observerService->AddObserver(this, "wake_notification", PR_FALSE);
131 PR_Lock(mLock);
132 mInitialized = PR_TRUE;
133 PR_NotifyAllCondVar(mCondVar);
134 PR_Unlock(mLock);
136 else {
137 PR_Lock(mLock);
138 while (!mInitialized) {
139 PR_WaitCondVar(mCondVar, PR_INTERVAL_NO_TIMEOUT);
141 PR_Unlock(mLock);
144 if (!mThread)
145 return NS_ERROR_FAILURE;
147 return NS_OK;
150 nsresult TimerThread::Shutdown()
152 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("TimerThread::Shutdown begin\n"));
154 if (!mThread)
155 return NS_ERROR_NOT_INITIALIZED;
157 nsVoidArray timers;
158 { // lock scope
159 nsAutoLock lock(mLock);
161 mShutdown = PR_TRUE;
163 // notify the cond var so that Run() can return
164 if (mCondVar && mWaiting)
165 PR_NotifyCondVar(mCondVar);
167 // Need to copy content of mTimers array to a local array
168 // because call to timers' ReleaseCallback() (and release its self)
169 // must not be done under the lock. Destructor of a callback
170 // might potentially call some code reentering the same lock
171 // that leads to unexpected behavior or deadlock.
172 // See bug 422472.
173 PRBool rv = timers.AppendElements(mTimers);
174 NS_ASSERTION(rv, "Could not copy timers array, remaining timers will not be released");
175 mTimers.Clear();
178 PRInt32 timersCount = timers.Count();
179 for (PRInt32 i = 0; i < timersCount; i++) {
180 nsTimerImpl *timer = static_cast<nsTimerImpl*>(timers[i]);
181 timer->ReleaseCallback();
182 ReleaseTimerInternal(timer);
185 mThread->Shutdown(); // wait for the thread to die
187 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("TimerThread::Shutdown end\n"));
188 return NS_OK;
191 // Keep track of how early (positive slack) or late (negative slack) timers
192 // are running, and use the filtered slack number to adaptively estimate how
193 // early timers should fire to be "on time".
194 void TimerThread::UpdateFilter(PRUint32 aDelay, PRIntervalTime aTimeout,
195 PRIntervalTime aNow)
197 PRInt32 slack = (PRInt32) (aTimeout - aNow);
198 double smoothSlack = 0;
199 PRUint32 i, filterLength;
200 static PRIntervalTime kFilterFeedbackMaxTicks =
201 PR_MillisecondsToInterval(FILTER_FEEDBACK_MAX);
203 if (slack > 0) {
204 if (slack > (PRInt32)kFilterFeedbackMaxTicks)
205 slack = kFilterFeedbackMaxTicks;
206 } else {
207 if (slack < -(PRInt32)kFilterFeedbackMaxTicks)
208 slack = -(PRInt32)kFilterFeedbackMaxTicks;
210 mDelayLine[mDelayLineCounter & DELAY_LINE_LENGTH_MASK] = slack;
211 if (++mDelayLineCounter < DELAY_LINE_LENGTH) {
212 // Startup mode: accumulate a full delay line before filtering.
213 PR_ASSERT(mTimeoutAdjustment == 0);
214 filterLength = 0;
215 } else {
216 // Past startup: compute number of filter taps based on mMinTimerPeriod.
217 if (mMinTimerPeriod == 0) {
218 mMinTimerPeriod = (aDelay != 0) ? aDelay : 1;
219 } else if (aDelay != 0 && aDelay < mMinTimerPeriod) {
220 mMinTimerPeriod = aDelay;
223 filterLength = (PRUint32) (FILTER_DURATION / mMinTimerPeriod);
224 if (filterLength > DELAY_LINE_LENGTH)
225 filterLength = DELAY_LINE_LENGTH;
226 else if (filterLength < 4)
227 filterLength = 4;
229 for (i = 1; i <= filterLength; i++)
230 smoothSlack += mDelayLine[(mDelayLineCounter-i) & DELAY_LINE_LENGTH_MASK];
231 smoothSlack /= filterLength;
233 // XXXbe do we need amplification? hacking a fudge factor, need testing...
234 mTimeoutAdjustment = (PRInt32) (smoothSlack * 1.5);
237 #ifdef DEBUG_TIMERS
238 PR_LOG(gTimerLog, PR_LOG_DEBUG,
239 ("UpdateFilter: smoothSlack = %g, filterLength = %u\n",
240 smoothSlack, filterLength));
241 #endif
244 /* void Run(); */
245 NS_IMETHODIMP TimerThread::Run()
247 nsAutoLock lock(mLock);
249 while (!mShutdown) {
250 PRIntervalTime waitFor;
252 if (mSleeping) {
253 // Sleep for 0.1 seconds while not firing timers.
254 waitFor = PR_MillisecondsToInterval(100);
255 } else {
256 waitFor = PR_INTERVAL_NO_TIMEOUT;
257 PRIntervalTime now = PR_IntervalNow();
258 nsTimerImpl *timer = nsnull;
260 if (mTimers.Count() > 0) {
261 timer = static_cast<nsTimerImpl*>(mTimers[0]);
263 if (!TIMER_LESS_THAN(now, timer->mTimeout + mTimeoutAdjustment)) {
264 next:
265 // NB: AddRef before the Release under RemoveTimerInternal to avoid
266 // mRefCnt passing through zero, in case all other refs than the one
267 // from mTimers have gone away (the last non-mTimers[i]-ref's Release
268 // must be racing with us, blocked in gThread->RemoveTimer waiting
269 // for TimerThread::mLock, under nsTimerImpl::Release.
271 NS_ADDREF(timer);
272 RemoveTimerInternal(timer);
274 // We release mLock around the Fire call to avoid deadlock.
275 lock.unlock();
277 #ifdef DEBUG_TIMERS
278 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
279 PR_LOG(gTimerLog, PR_LOG_DEBUG,
280 ("Timer thread woke up %dms from when it was supposed to\n",
281 (now >= timer->mTimeout)
282 ? PR_IntervalToMilliseconds(now - timer->mTimeout)
283 : -(PRInt32)PR_IntervalToMilliseconds(timer->mTimeout-now))
286 #endif
288 // We are going to let the call to PostTimerEvent here handle the
289 // release of the timer so that we don't end up releasing the timer
290 // on the TimerThread instead of on the thread it targets.
291 if (NS_FAILED(timer->PostTimerEvent())) {
292 nsrefcnt rc;
293 NS_RELEASE2(timer, rc);
295 // The nsITimer interface requires that its users keep a reference
296 // to the timers they use while those timers are initialized but
297 // have not yet fired. If this ever happens, it is a bug in the
298 // code that created and used the timer.
300 // Further, note that this should never happen even with a
301 // misbehaving user, because nsTimerImpl::Release checks for a
302 // refcount of 1 with an armed timer (a timer whose only reference
303 // is from the timer thread) and when it hits this will remove the
304 // timer from the timer thread and thus destroy the last reference,
305 // preventing this situation from occurring.
306 NS_ASSERTION(rc != 0, "destroyed timer off its target thread!");
308 timer = nsnull;
310 lock.lock();
311 if (mShutdown)
312 break;
314 // Update now, as PostTimerEvent plus the locking may have taken a
315 // tick or two, and we may goto next below.
316 now = PR_IntervalNow();
320 if (mTimers.Count() > 0) {
321 timer = static_cast<nsTimerImpl *>(mTimers[0]);
323 PRIntervalTime timeout = timer->mTimeout + mTimeoutAdjustment;
325 // Don't wait at all (even for PR_INTERVAL_NO_WAIT) if the next timer
326 // is due now or overdue.
327 if (!TIMER_LESS_THAN(now, timeout))
328 goto next;
329 waitFor = timeout - now;
332 #ifdef DEBUG_TIMERS
333 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
334 if (waitFor == PR_INTERVAL_NO_TIMEOUT)
335 PR_LOG(gTimerLog, PR_LOG_DEBUG,
336 ("waiting for PR_INTERVAL_NO_TIMEOUT\n"));
337 else
338 PR_LOG(gTimerLog, PR_LOG_DEBUG,
339 ("waiting for %u\n", PR_IntervalToMilliseconds(waitFor)));
341 #endif
344 mWaiting = PR_TRUE;
345 PR_WaitCondVar(mCondVar, waitFor);
346 mWaiting = PR_FALSE;
349 return NS_OK;
352 nsresult TimerThread::AddTimer(nsTimerImpl *aTimer)
354 nsAutoLock lock(mLock);
356 // Add the timer to our list.
357 PRInt32 i = AddTimerInternal(aTimer);
358 if (i < 0)
359 return NS_ERROR_OUT_OF_MEMORY;
361 // Awaken the timer thread.
362 if (mCondVar && mWaiting && i == 0)
363 PR_NotifyCondVar(mCondVar);
365 return NS_OK;
368 nsresult TimerThread::TimerDelayChanged(nsTimerImpl *aTimer)
370 nsAutoLock lock(mLock);
372 // Our caller has a strong ref to aTimer, so it can't go away here under
373 // ReleaseTimerInternal.
374 RemoveTimerInternal(aTimer);
376 PRInt32 i = AddTimerInternal(aTimer);
377 if (i < 0)
378 return NS_ERROR_OUT_OF_MEMORY;
380 // Awaken the timer thread.
381 if (mCondVar && mWaiting && i == 0)
382 PR_NotifyCondVar(mCondVar);
384 return NS_OK;
387 nsresult TimerThread::RemoveTimer(nsTimerImpl *aTimer)
389 nsAutoLock lock(mLock);
391 // Remove the timer from our array. Tell callers that aTimer was not found
392 // by returning NS_ERROR_NOT_AVAILABLE. Unlike the TimerDelayChanged case
393 // immediately above, our caller may be passing a (now-)weak ref in via the
394 // aTimer param, specifically when nsTimerImpl::Release loses a race with
395 // TimerThread::Run, must wait for the mLock auto-lock here, and during the
396 // wait Run drops the only remaining ref to aTimer via RemoveTimerInternal.
398 if (!RemoveTimerInternal(aTimer))
399 return NS_ERROR_NOT_AVAILABLE;
401 // Awaken the timer thread.
402 if (mCondVar && mWaiting)
403 PR_NotifyCondVar(mCondVar);
405 return NS_OK;
408 // This function must be called from within a lock
409 PRInt32 TimerThread::AddTimerInternal(nsTimerImpl *aTimer)
411 if (mShutdown)
412 return -1;
414 PRIntervalTime now = PR_IntervalNow();
415 PRInt32 count = mTimers.Count();
416 PRInt32 i = 0;
417 for (; i < count; i++) {
418 nsTimerImpl *timer = static_cast<nsTimerImpl *>(mTimers[i]);
420 // Don't break till we have skipped any overdue timers. Do not include
421 // mTimeoutAdjustment here, because we are really trying to avoid calling
422 // TIMER_LESS_THAN(t, u), where the t is now + DELAY_INTERVAL_MAX, u is
423 // now - overdue, and DELAY_INTERVAL_MAX + overdue > DELAY_INTERVAL_LIMIT.
424 // In other words, we want to use now-based time, now adjusted time, even
425 // though "overdue" ultimately depends on adjusted time.
427 // XXX does this hold for TYPE_REPEATING_PRECISE? /be
429 if (TIMER_LESS_THAN(now, timer->mTimeout) &&
430 TIMER_LESS_THAN(aTimer->mTimeout, timer->mTimeout)) {
431 break;
435 if (!mTimers.InsertElementAt(aTimer, i))
436 return -1;
438 aTimer->mArmed = PR_TRUE;
439 NS_ADDREF(aTimer);
440 return i;
443 PRBool TimerThread::RemoveTimerInternal(nsTimerImpl *aTimer)
445 if (!mTimers.RemoveElement(aTimer))
446 return PR_FALSE;
448 ReleaseTimerInternal(aTimer);
449 return PR_TRUE;
452 void TimerThread::ReleaseTimerInternal(nsTimerImpl *aTimer)
454 // Order is crucial here -- see nsTimerImpl::Release.
455 aTimer->mArmed = PR_FALSE;
456 NS_RELEASE(aTimer);
459 void TimerThread::DoBeforeSleep()
461 mSleeping = PR_TRUE;
464 void TimerThread::DoAfterSleep()
466 mSleeping = PR_TRUE; // wake may be notified without preceding sleep notification
467 for (PRInt32 i = 0; i < mTimers.Count(); i ++) {
468 nsTimerImpl *timer = static_cast<nsTimerImpl*>(mTimers[i]);
469 // get and set the delay to cause its timeout to be recomputed
470 PRUint32 delay;
471 timer->GetDelay(&delay);
472 timer->SetDelay(delay);
475 // nuke the stored adjustments, so they get recalibrated
476 mTimeoutAdjustment = 0;
477 mDelayLineCounter = 0;
478 mSleeping = PR_FALSE;
482 /* void observe (in nsISupports aSubject, in string aTopic, in wstring aData); */
483 NS_IMETHODIMP
484 TimerThread::Observe(nsISupports* /* aSubject */, const char *aTopic, const PRUnichar* /* aData */)
486 if (strcmp(aTopic, "sleep_notification") == 0)
487 DoBeforeSleep();
488 else if (strcmp(aTopic, "wake_notification") == 0)
489 DoAfterSleep();
491 return NS_OK;