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
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.
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"
48 #include "nsIObserverService.h"
49 #include "nsIServiceManager.h"
50 #include "nsIProxyObjectManager.h"
52 NS_IMPL_THREADSAFE_ISUPPORTS2(TimerThread
, nsIRunnable
, nsIObserver
)
54 TimerThread::TimerThread() :
56 mInitialized(PR_FALSE
),
68 TimerThread::~TimerThread()
71 PR_DestroyCondVar(mCondVar
);
73 PR_DestroyLock(mLock
);
77 NS_ASSERTION(mTimers
.Count() == 0, "Timers remain in TimerThread::~TimerThread");
81 TimerThread::InitLocks()
83 NS_ASSERTION(!mLock
, "InitLocks called twice?");
86 return NS_ERROR_OUT_OF_MEMORY
;
88 mCondVar
= PR_NewCondVar(mLock
);
90 return NS_ERROR_OUT_OF_MEMORY
;
95 nsresult
TimerThread::Init()
97 PR_LOG(gTimerLog
, PR_LOG_DEBUG
, ("TimerThread::Init [%d]\n", mInitialized
));
101 return NS_ERROR_FAILURE
;
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);
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
);
132 mInitialized
= PR_TRUE
;
133 PR_NotifyAllCondVar(mCondVar
);
138 while (!mInitialized
) {
139 PR_WaitCondVar(mCondVar
, PR_INTERVAL_NO_TIMEOUT
);
145 return NS_ERROR_FAILURE
;
150 nsresult
TimerThread::Shutdown()
152 PR_LOG(gTimerLog
, PR_LOG_DEBUG
, ("TimerThread::Shutdown begin\n"));
155 return NS_ERROR_NOT_INITIALIZED
;
159 nsAutoLock
lock(mLock
);
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.
173 PRBool rv
= timers
.AppendElements(mTimers
);
174 NS_ASSERTION(rv
, "Could not copy timers array, remaining timers will not be released");
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"));
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
,
197 PRInt32 slack
= (PRInt32
) (aTimeout
- aNow
);
198 double smoothSlack
= 0;
199 PRUint32 i
, filterLength
;
200 static PRIntervalTime kFilterFeedbackMaxTicks
=
201 PR_MillisecondsToInterval(FILTER_FEEDBACK_MAX
);
204 if (slack
> (PRInt32
)kFilterFeedbackMaxTicks
)
205 slack
= kFilterFeedbackMaxTicks
;
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);
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)
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);
238 PR_LOG(gTimerLog
, PR_LOG_DEBUG
,
239 ("UpdateFilter: smoothSlack = %g, filterLength = %u\n",
240 smoothSlack
, filterLength
));
245 NS_IMETHODIMP
TimerThread::Run()
247 nsAutoLock
lock(mLock
);
250 PRIntervalTime waitFor
;
253 // Sleep for 0.1 seconds while not firing timers.
254 waitFor
= PR_MillisecondsToInterval(100);
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
)) {
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.
272 RemoveTimerInternal(timer
);
274 // We release mLock around the Fire call to avoid deadlock.
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
))
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())) {
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!");
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
))
329 waitFor
= timeout
- now
;
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"));
338 PR_LOG(gTimerLog
, PR_LOG_DEBUG
,
339 ("waiting for %u\n", PR_IntervalToMilliseconds(waitFor
)));
345 PR_WaitCondVar(mCondVar
, waitFor
);
352 nsresult
TimerThread::AddTimer(nsTimerImpl
*aTimer
)
354 nsAutoLock
lock(mLock
);
356 // Add the timer to our list.
357 PRInt32 i
= AddTimerInternal(aTimer
);
359 return NS_ERROR_OUT_OF_MEMORY
;
361 // Awaken the timer thread.
362 if (mCondVar
&& mWaiting
&& i
== 0)
363 PR_NotifyCondVar(mCondVar
);
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
);
378 return NS_ERROR_OUT_OF_MEMORY
;
380 // Awaken the timer thread.
381 if (mCondVar
&& mWaiting
&& i
== 0)
382 PR_NotifyCondVar(mCondVar
);
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
);
408 // This function must be called from within a lock
409 PRInt32
TimerThread::AddTimerInternal(nsTimerImpl
*aTimer
)
414 PRIntervalTime now
= PR_IntervalNow();
415 PRInt32 count
= mTimers
.Count();
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
)) {
435 if (!mTimers
.InsertElementAt(aTimer
, i
))
438 aTimer
->mArmed
= PR_TRUE
;
443 PRBool
TimerThread::RemoveTimerInternal(nsTimerImpl
*aTimer
)
445 if (!mTimers
.RemoveElement(aTimer
))
448 ReleaseTimerInternal(aTimer
);
452 void TimerThread::ReleaseTimerInternal(nsTimerImpl
*aTimer
)
454 // Order is crucial here -- see nsTimerImpl::Release.
455 aTimer
->mArmed
= PR_FALSE
;
459 void TimerThread::DoBeforeSleep()
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
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); */
484 TimerThread::Observe(nsISupports
* /* aSubject */, const char *aTopic
, const PRUnichar
* /* aData */)
486 if (strcmp(aTopic
, "sleep_notification") == 0)
488 else if (strcmp(aTopic
, "wake_notification") == 0)