Fixed attemptTreeCall not checking deep-abort status correctly (bug 520492, r=gal).
[mozilla-central.git] / xpcom / threads / nsTimerImpl.cpp
blob6fa8410df074bbef49ffea8443666573703e17f5
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"
43 #include "nsAutoLock.h"
44 #include "nsAutoPtr.h"
45 #include "nsThreadManager.h"
46 #include "nsThreadUtils.h"
47 #include "prmem.h"
49 static PRInt32 gGenerator = 0;
50 static TimerThread* gThread = nsnull;
52 #ifdef DEBUG_TIMERS
53 #include <math.h>
55 double nsTimerImpl::sDeltaSumSquared = 0;
56 double nsTimerImpl::sDeltaSum = 0;
57 double nsTimerImpl::sDeltaNum = 0;
59 static void
60 myNS_MeanAndStdDev(double n, double sumOfValues, double sumOfSquaredValues,
61 double *meanResult, double *stdDevResult)
63 double mean = 0.0, var = 0.0, stdDev = 0.0;
64 if (n > 0.0 && sumOfValues >= 0) {
65 mean = sumOfValues / n;
66 double temp = (n * sumOfSquaredValues) - (sumOfValues * sumOfValues);
67 if (temp < 0.0 || n <= 1)
68 var = 0.0;
69 else
70 var = temp / (n * (n - 1));
71 // for some reason, Windows says sqrt(0.0) is "-1.#J" (?!) so do this:
72 stdDev = var != 0.0 ? sqrt(var) : 0.0;
74 *meanResult = mean;
75 *stdDevResult = stdDev;
77 #endif
79 NS_IMPL_THREADSAFE_QUERY_INTERFACE1(nsTimerImpl, nsITimer)
80 NS_IMPL_THREADSAFE_ADDREF(nsTimerImpl)
82 NS_IMETHODIMP_(nsrefcnt) nsTimerImpl::Release(void)
84 nsrefcnt count;
86 NS_PRECONDITION(0 != mRefCnt, "dup release");
87 count = PR_AtomicDecrement((PRInt32 *)&mRefCnt);
88 NS_LOG_RELEASE(this, count, "nsTimerImpl");
89 if (count == 0) {
90 mRefCnt = 1; /* stabilize */
92 /* enable this to find non-threadsafe destructors: */
93 /* NS_ASSERT_OWNINGTHREAD(nsTimerImpl); */
94 NS_DELETEXPCOM(this);
95 return 0;
98 // If only one reference remains, and mArmed is set, then the ref must be
99 // from the TimerThread::mTimers array, so we Cancel this timer to remove
100 // the mTimers element, and return 0 if Cancel in fact disarmed the timer.
102 // We use an inlined version of nsTimerImpl::Cancel here to check for the
103 // NS_ERROR_NOT_AVAILABLE code returned by gThread->RemoveTimer when this
104 // timer is not found in the mTimers array -- i.e., when the timer was not
105 // in fact armed once we acquired TimerThread::mLock, in spite of mArmed
106 // being true here. That can happen if the armed timer is being fired by
107 // TimerThread::Run as we race and test mArmed just before it is cleared by
108 // the timer thread. If the RemoveTimer call below doesn't find this timer
109 // in the mTimers array, then the last ref to this timer is held manually
110 // and temporarily by the TimerThread, so we should fall through to the
111 // final return and return 1, not 0.
113 // The original version of this thread-based timer code kept weak refs from
114 // TimerThread::mTimers, removing this timer's weak ref in the destructor,
115 // but that leads to double-destructions in the race described above, and
116 // adding mArmed doesn't help, because destructors can't be deferred, once
117 // begun. But by combining reference-counting and a specialized Release
118 // method with "is this timer still in the mTimers array once we acquire
119 // the TimerThread's lock" testing, we defer destruction until we're sure
120 // that only one thread has its hot little hands on this timer.
122 // Note that both approaches preclude a timer creator, and everyone else
123 // except the TimerThread who might have a strong ref, from dropping all
124 // their strong refs without implicitly canceling the timer. Timers need
125 // non-mTimers-element strong refs to stay alive.
127 if (count == 1 && mArmed) {
128 mCanceled = PR_TRUE;
130 NS_ASSERTION(gThread, "An armed timer exists after the thread timer stopped.");
131 if (NS_SUCCEEDED(gThread->RemoveTimer(this)))
132 return 0;
135 return count;
138 nsTimerImpl::nsTimerImpl() :
139 mClosure(nsnull),
140 mCallbackType(CALLBACK_TYPE_UNKNOWN),
141 mFiring(PR_FALSE),
142 mArmed(PR_FALSE),
143 mCanceled(PR_FALSE),
144 mGeneration(0),
145 mDelay(0),
146 mTimeout(0)
148 // XXXbsmedberg: shouldn't this be in Init()?
149 mEventTarget = static_cast<nsIEventTarget*>(NS_GetCurrentThread());
151 mCallback.c = nsnull;
153 #ifdef DEBUG_TIMERS
154 mStart = 0;
155 mStart2 = 0;
156 #endif
159 nsTimerImpl::~nsTimerImpl()
161 ReleaseCallback();
164 //static
165 nsresult
166 nsTimerImpl::Startup()
168 nsresult rv;
170 gThread = new TimerThread();
171 if (!gThread) return NS_ERROR_OUT_OF_MEMORY;
173 NS_ADDREF(gThread);
174 rv = gThread->InitLocks();
176 if (NS_FAILED(rv)) {
177 NS_RELEASE(gThread);
180 return rv;
183 void nsTimerImpl::Shutdown()
185 #ifdef DEBUG_TIMERS
186 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
187 double mean = 0, stddev = 0;
188 myNS_MeanAndStdDev(sDeltaNum, sDeltaSum, sDeltaSumSquared, &mean, &stddev);
190 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("sDeltaNum = %f, sDeltaSum = %f, sDeltaSumSquared = %f\n", sDeltaNum, sDeltaSum, sDeltaSumSquared));
191 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("mean: %fms, stddev: %fms\n", mean, stddev));
193 #endif
195 if (!gThread)
196 return;
198 gThread->Shutdown();
199 NS_RELEASE(gThread);
203 nsresult nsTimerImpl::InitCommon(PRUint32 aType, PRUint32 aDelay)
205 nsresult rv;
207 NS_ENSURE_TRUE(gThread, NS_ERROR_NOT_INITIALIZED);
209 rv = gThread->Init();
210 NS_ENSURE_SUCCESS(rv, rv);
213 * In case of re-Init, both with and without a preceding Cancel, clear the
214 * mCanceled flag and assign a new mGeneration. But first, remove any armed
215 * timer from the timer thread's list.
217 * If we are racing with the timer thread to remove this timer and we lose,
218 * the RemoveTimer call made here will fail to find this timer in the timer
219 * thread's list, and will return false harmlessly. We test mArmed here to
220 * avoid the small overhead in RemoveTimer of locking the timer thread and
221 * checking its list for this timer. It's safe to test mArmed even though
222 * it might be cleared on another thread in the next cycle (or even already
223 * be cleared by another CPU whose store hasn't reached our CPU's cache),
224 * because RemoveTimer is idempotent.
226 if (mArmed)
227 gThread->RemoveTimer(this);
228 mCanceled = PR_FALSE;
229 mGeneration = PR_AtomicIncrement(&gGenerator);
231 mType = (PRUint8)aType;
232 SetDelayInternal(aDelay);
234 return gThread->AddTimer(this);
237 NS_IMETHODIMP nsTimerImpl::InitWithFuncCallback(nsTimerCallbackFunc aFunc,
238 void *aClosure,
239 PRUint32 aDelay,
240 PRUint32 aType)
242 NS_ENSURE_ARG_POINTER(aFunc);
244 ReleaseCallback();
245 mCallbackType = CALLBACK_TYPE_FUNC;
246 mCallback.c = aFunc;
247 mClosure = aClosure;
249 return InitCommon(aType, aDelay);
252 NS_IMETHODIMP nsTimerImpl::InitWithCallback(nsITimerCallback *aCallback,
253 PRUint32 aDelay,
254 PRUint32 aType)
256 NS_ENSURE_ARG_POINTER(aCallback);
258 ReleaseCallback();
259 mCallbackType = CALLBACK_TYPE_INTERFACE;
260 mCallback.i = aCallback;
261 NS_ADDREF(mCallback.i);
263 return InitCommon(aType, aDelay);
266 NS_IMETHODIMP nsTimerImpl::Init(nsIObserver *aObserver,
267 PRUint32 aDelay,
268 PRUint32 aType)
270 NS_ENSURE_ARG_POINTER(aObserver);
272 ReleaseCallback();
273 mCallbackType = CALLBACK_TYPE_OBSERVER;
274 mCallback.o = aObserver;
275 NS_ADDREF(mCallback.o);
277 return InitCommon(aType, aDelay);
280 NS_IMETHODIMP nsTimerImpl::Cancel()
282 mCanceled = PR_TRUE;
284 if (gThread)
285 gThread->RemoveTimer(this);
287 ReleaseCallback();
289 return NS_OK;
292 NS_IMETHODIMP nsTimerImpl::SetDelay(PRUint32 aDelay)
294 if (mCallbackType == CALLBACK_TYPE_UNKNOWN && mType == TYPE_ONE_SHOT) {
295 // This may happen if someone tries to re-use a one-shot timer
296 // by re-setting delay instead of reinitializing the timer.
297 NS_ERROR("nsITimer->SetDelay() called when the "
298 "one-shot timer is not set up.");
299 return NS_ERROR_NOT_INITIALIZED;
302 // If we're already repeating precisely, update mTimeout now so that the
303 // new delay takes effect in the future.
304 if (mTimeout != 0 && mType == TYPE_REPEATING_PRECISE)
305 mTimeout = PR_IntervalNow();
307 SetDelayInternal(aDelay);
309 if (!mFiring && gThread)
310 gThread->TimerDelayChanged(this);
312 return NS_OK;
315 NS_IMETHODIMP nsTimerImpl::GetDelay(PRUint32* aDelay)
317 *aDelay = mDelay;
318 return NS_OK;
321 NS_IMETHODIMP nsTimerImpl::SetType(PRUint32 aType)
323 mType = (PRUint8)aType;
324 // XXX if this is called, we should change the actual type.. this could effect
325 // repeating timers. we need to ensure in Fire() that if mType has changed
326 // during the callback that we don't end up with the timer in the queue twice.
327 return NS_OK;
330 NS_IMETHODIMP nsTimerImpl::GetType(PRUint32* aType)
332 *aType = mType;
333 return NS_OK;
337 NS_IMETHODIMP nsTimerImpl::GetClosure(void** aClosure)
339 *aClosure = mClosure;
340 return NS_OK;
344 NS_IMETHODIMP nsTimerImpl::GetCallback(nsITimerCallback **aCallback)
346 if (mCallbackType == CALLBACK_TYPE_INTERFACE)
347 NS_IF_ADDREF(*aCallback = mCallback.i);
348 else if (mTimerCallbackWhileFiring)
349 NS_ADDREF(*aCallback = mTimerCallbackWhileFiring);
350 else
351 *aCallback = nsnull;
353 return NS_OK;
357 NS_IMETHODIMP nsTimerImpl::GetTarget(nsIEventTarget** aTarget)
359 NS_IF_ADDREF(*aTarget = mEventTarget);
360 return NS_OK;
364 NS_IMETHODIMP nsTimerImpl::SetTarget(nsIEventTarget* aTarget)
366 NS_ENSURE_TRUE(mCallbackType == CALLBACK_TYPE_UNKNOWN,
367 NS_ERROR_ALREADY_INITIALIZED);
369 if (aTarget)
370 mEventTarget = aTarget;
371 else
372 mEventTarget = static_cast<nsIEventTarget*>(NS_GetCurrentThread());
373 return NS_OK;
377 void nsTimerImpl::Fire()
379 if (mCanceled)
380 return;
382 PRIntervalTime now = PR_IntervalNow();
383 #ifdef DEBUG_TIMERS
384 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
385 PRIntervalTime a = now - mStart; // actual delay in intervals
386 PRUint32 b = PR_MillisecondsToInterval(mDelay); // expected delay in intervals
387 PRUint32 d = PR_IntervalToMilliseconds((a > b) ? a - b : b - a); // delta in ms
388 sDeltaSum += d;
389 sDeltaSumSquared += double(d) * double(d);
390 sDeltaNum++;
392 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] expected delay time %4dms\n", this, mDelay));
393 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] actual delay time %4dms\n", this, PR_IntervalToMilliseconds(a)));
394 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] (mType is %d) -------\n", this, mType));
395 PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] delta %4dms\n", this, (a > b) ? (PRInt32)d : -(PRInt32)d));
397 mStart = mStart2;
398 mStart2 = 0;
400 #endif
402 PRIntervalTime timeout = mTimeout;
403 if (mType == TYPE_REPEATING_PRECISE) {
404 // Precise repeating timers advance mTimeout by mDelay without fail before
405 // calling Fire().
406 timeout -= PR_MillisecondsToInterval(mDelay);
408 if (gThread)
409 gThread->UpdateFilter(mDelay, timeout, now);
411 if (mCallbackType == CALLBACK_TYPE_INTERFACE)
412 mTimerCallbackWhileFiring = mCallback.i;
413 mFiring = PR_TRUE;
415 // Handle callbacks that re-init the timer, but avoid leaking.
416 // See bug 330128.
417 CallbackUnion callback = mCallback;
418 PRUintn callbackType = mCallbackType;
419 if (callbackType == CALLBACK_TYPE_INTERFACE)
420 NS_ADDREF(callback.i);
421 else if (callbackType == CALLBACK_TYPE_OBSERVER)
422 NS_ADDREF(callback.o);
423 ReleaseCallback();
425 switch (callbackType) {
426 case CALLBACK_TYPE_FUNC:
427 callback.c(this, mClosure);
428 break;
429 case CALLBACK_TYPE_INTERFACE:
430 callback.i->Notify(this);
431 break;
432 case CALLBACK_TYPE_OBSERVER:
433 callback.o->Observe(static_cast<nsITimer*>(this),
434 NS_TIMER_CALLBACK_TOPIC,
435 nsnull);
436 break;
437 default:;
440 // If the callback didn't re-init the timer, and it's not a one-shot timer,
441 // restore the callback state.
442 if (mCallbackType == CALLBACK_TYPE_UNKNOWN &&
443 mType != TYPE_ONE_SHOT && !mCanceled) {
444 mCallback = callback;
445 mCallbackType = callbackType;
446 } else {
447 // The timer was a one-shot, or the callback was reinitialized.
448 if (callbackType == CALLBACK_TYPE_INTERFACE)
449 NS_RELEASE(callback.i);
450 else if (callbackType == CALLBACK_TYPE_OBSERVER)
451 NS_RELEASE(callback.o);
454 mFiring = PR_FALSE;
455 mTimerCallbackWhileFiring = nsnull;
457 #ifdef DEBUG_TIMERS
458 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
459 PR_LOG(gTimerLog, PR_LOG_DEBUG,
460 ("[this=%p] Took %dms to fire timer callback\n",
461 this, PR_IntervalToMilliseconds(PR_IntervalNow() - now)));
463 #endif
465 // Reschedule REPEATING_SLACK timers, but make sure that we aren't armed
466 // already (which can happen if the callback reinitialized the timer).
467 if (mType == TYPE_REPEATING_SLACK && !mArmed) {
468 SetDelayInternal(mDelay); // force mTimeout to be recomputed.
469 if (gThread)
470 gThread->AddTimer(this);
475 class nsTimerEvent : public nsRunnable {
476 public:
477 NS_IMETHOD Run();
479 nsTimerEvent(nsTimerImpl *timer, PRInt32 generation)
480 : mTimer(timer), mGeneration(generation) {
481 // timer is already addref'd for us
482 MOZ_COUNT_CTOR(nsTimerEvent);
485 #ifdef DEBUG_TIMERS
486 PRIntervalTime mInitTime;
487 #endif
489 private:
490 ~nsTimerEvent() {
491 #ifdef DEBUG
492 if (mTimer)
493 NS_WARNING("leaking reference to nsTimerImpl");
494 #endif
495 MOZ_COUNT_DTOR(nsTimerEvent);
498 nsTimerImpl *mTimer;
499 PRInt32 mGeneration;
502 NS_IMETHODIMP nsTimerEvent::Run()
504 nsRefPtr<nsTimerImpl> timer;
505 timer.swap(mTimer);
507 if (mGeneration != timer->GetGeneration())
508 return NS_OK;
510 #ifdef DEBUG_TIMERS
511 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
512 PRIntervalTime now = PR_IntervalNow();
513 PR_LOG(gTimerLog, PR_LOG_DEBUG,
514 ("[this=%p] time between PostTimerEvent() and Fire(): %dms\n",
515 this, PR_IntervalToMilliseconds(now - mInitTime)));
517 #endif
519 timer->Fire();
521 return NS_OK;
524 nsresult nsTimerImpl::PostTimerEvent()
526 // XXX we may want to reuse this nsTimerEvent in the case of repeating timers.
528 // Since TimerThread addref'd 'this' for us, we don't need to addref here.
529 // We will release in destroyMyEvent. We need to copy the generation number
530 // from this timer into the event, so we can avoid firing a timer that was
531 // re-initialized after being canceled.
533 nsRefPtr<nsTimerEvent> event = new nsTimerEvent(this, mGeneration);
534 if (!event)
535 return NS_ERROR_OUT_OF_MEMORY;
537 #ifdef DEBUG_TIMERS
538 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
539 event->mInitTime = PR_IntervalNow();
541 #endif
543 // If this is a repeating precise timer, we need to calculate the time for
544 // the next timer to fire before we make the callback.
545 if (mType == TYPE_REPEATING_PRECISE) {
546 SetDelayInternal(mDelay);
547 if (gThread) {
548 nsresult rv = gThread->AddTimer(this);
549 if (NS_FAILED(rv))
550 return rv;
554 nsresult rv = mEventTarget->Dispatch(event, NS_DISPATCH_NORMAL);
555 if (NS_FAILED(rv) && gThread)
556 gThread->RemoveTimer(this);
557 return rv;
560 void nsTimerImpl::SetDelayInternal(PRUint32 aDelay)
562 PRIntervalTime delayInterval = PR_MillisecondsToInterval(aDelay);
563 if (delayInterval > DELAY_INTERVAL_MAX) {
564 delayInterval = DELAY_INTERVAL_MAX;
565 aDelay = PR_IntervalToMilliseconds(delayInterval);
568 mDelay = aDelay;
570 PRIntervalTime now = PR_IntervalNow();
571 if (mTimeout == 0 || mType != TYPE_REPEATING_PRECISE)
572 mTimeout = now;
574 mTimeout += delayInterval;
576 #ifdef DEBUG_TIMERS
577 if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
578 if (mStart == 0)
579 mStart = now;
580 else
581 mStart2 = now;
583 #endif
586 // NOT FOR PUBLIC CONSUMPTION!
587 nsresult
588 NS_NewTimer(nsITimer* *aResult, nsTimerCallbackFunc aCallback, void *aClosure,
589 PRUint32 aDelay, PRUint32 aType)
591 nsTimerImpl* timer = new nsTimerImpl();
592 if (timer == nsnull)
593 return NS_ERROR_OUT_OF_MEMORY;
594 NS_ADDREF(timer);
596 nsresult rv = timer->InitWithFuncCallback(aCallback, aClosure,
597 aDelay, aType);
598 if (NS_FAILED(rv)) {
599 NS_RELEASE(timer);
600 return rv;
603 *aResult = timer;
604 return NS_OK;