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
* The contents of this file are subject to the Mozilla Public License Version
5
* 1.1 (the "License"); you may not use this file except in compliance with
6
* the License. You may obtain a copy of the License at
7
* http://www.mozilla.org/MPL/
9
* Software distributed under the License is distributed on an "AS IS" basis,
10
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11
* for the specific language governing rights and limitations under the
14
* The Original Code is mozilla.org code.
16
* The Initial Developer of the Original Code is Netscape Communications
17
* Corporation. Portions created by the Initial Developer are
18
* Copyright (C) 2001 the Initial Developer. All Rights Reserved.
21
* Stuart Parmenter <pavlov@netscape.com>
23
* Alternatively, the contents of this file may be used under the terms of
24
* either the GNU General Public License Version 2 or later (the "GPL"), or
25
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
26
* in which case the provisions of the GPL or the LGPL are applicable instead
27
* of those above. If you wish to allow use of your version of this file only
28
* under the terms of either the GPL or the LGPL, and not to allow others to
29
* use your version of this file under the terms of the MPL, indicate your
30
* decision by deleting the provisions above and replace them with the notice
31
* and other provisions required by the GPL or the LGPL. If you do not delete
32
* the provisions above, a recipient may use your version of this file under
33
* the terms of any one of the MPL, the GPL or the LGPL.
36
#include "nsTimerImpl.h"
37
#include "TimerThread.h"
39
#include "nsAutoLock.h"
42
#include "nsIObserverService.h"
43
#include "nsIServiceManager.h"
45
NS_IMPL_THREADSAFE_ISUPPORTS3(TimerThread, nsIRunnable, nsISupportsWeakReference, nsIObserver)
47
TimerThread::TimerThread() :
59
TimerThread::~TimerThread()
62
PR_DestroyCondVar(mCondVar);
64
PR_DestroyLock(mLock);
68
PRInt32 n = mTimers.Count();
70
nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[n]);
74
nsCOMPtr<nsIObserverService> observerService = do_GetService("@mozilla.org/observer-service;1");
75
if (observerService) {
76
observerService->RemoveObserver(this, "sleep_notification");
77
observerService->RemoveObserver(this, "wake_notification");
82
nsresult TimerThread::Init()
89
return NS_ERROR_OUT_OF_MEMORY;
91
mCondVar = PR_NewCondVar(mLock);
93
return NS_ERROR_OUT_OF_MEMORY;
96
mEventQueueService = do_GetService("@mozilla.org/event-queue-service;1", &rv);
100
// We hold on to mThread to keep the thread alive.
101
rv = NS_NewThread(getter_AddRefs(mThread),
102
NS_STATIC_CAST(nsIRunnable*, this),
110
nsCOMPtr<nsIObserverService> observerService = do_GetService("@mozilla.org/observer-service;1", &rv);
114
observerService->AddObserver(this, "sleep_notification", PR_TRUE);
115
observerService->AddObserver(this, "wake_notification", PR_TRUE);
120
nsresult TimerThread::Shutdown()
123
return NS_ERROR_NOT_INITIALIZED;
126
nsAutoLock lock(mLock);
130
// notify the cond var so that Run() can return
131
if (mCondVar && mWaiting)
132
PR_NotifyCondVar(mCondVar);
135
for (PRInt32 i = mTimers.Count() - 1; i >= 0; i--) {
136
timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[i]);
137
RemoveTimerInternal(timer);
141
mThread->Join(); // wait for the thread to die
145
// Keep track of how early (positive slack) or late (negative slack) timers
146
// are running, and use the filtered slack number to adaptively estimate how
147
// early timers should fire to be "on time".
148
void TimerThread::UpdateFilter(PRUint32 aDelay, PRIntervalTime aTimeout,
151
PRInt32 slack = (PRInt32) (aTimeout - aNow);
152
double smoothSlack = 0;
153
PRUint32 i, filterLength;
154
static PRIntervalTime kFilterFeedbackMaxTicks =
155
PR_MillisecondsToInterval(FILTER_FEEDBACK_MAX);
158
if (slack > (PRInt32)kFilterFeedbackMaxTicks)
159
slack = kFilterFeedbackMaxTicks;
161
if (slack < -(PRInt32)kFilterFeedbackMaxTicks)
162
slack = -(PRInt32)kFilterFeedbackMaxTicks;
164
mDelayLine[mDelayLineCounter & DELAY_LINE_LENGTH_MASK] = slack;
165
if (++mDelayLineCounter < DELAY_LINE_LENGTH) {
166
// Startup mode: accumulate a full delay line before filtering.
167
PR_ASSERT(mTimeoutAdjustment == 0);
170
// Past startup: compute number of filter taps based on mMinTimerPeriod.
171
if (mMinTimerPeriod == 0) {
172
mMinTimerPeriod = (aDelay != 0) ? aDelay : 1;
173
} else if (aDelay != 0 && aDelay < mMinTimerPeriod) {
174
mMinTimerPeriod = aDelay;
177
filterLength = (PRUint32) (FILTER_DURATION / mMinTimerPeriod);
178
if (filterLength > DELAY_LINE_LENGTH)
179
filterLength = DELAY_LINE_LENGTH;
180
else if (filterLength < 4)
183
for (i = 1; i <= filterLength; i++)
184
smoothSlack += mDelayLine[(mDelayLineCounter-i) & DELAY_LINE_LENGTH_MASK];
185
smoothSlack /= filterLength;
187
// XXXbe do we need amplification? hacking a fudge factor, need testing...
188
mTimeoutAdjustment = (PRInt32) (smoothSlack * 1.5);
192
if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
193
PR_LOG(gTimerLog, PR_LOG_DEBUG,
194
("UpdateFilter: smoothSlack = %g, filterLength = %u\n",
195
smoothSlack, filterLength));
201
NS_IMETHODIMP TimerThread::Run()
203
nsAutoLock lock(mLock);
206
PRIntervalTime waitFor;
209
// Sleep for 0.1 seconds while not firing timers.
210
waitFor = PR_MillisecondsToInterval(100);
212
waitFor = PR_INTERVAL_NO_TIMEOUT;
213
PRIntervalTime now = PR_IntervalNow();
214
nsTimerImpl *timer = nsnull;
216
if (mTimers.Count() > 0) {
217
timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[0]);
219
if (!TIMER_LESS_THAN(now, timer->mTimeout + mTimeoutAdjustment)) {
221
// NB: AddRef before the Release under RemoveTimerInternal to avoid
222
// mRefCnt passing through zero, in case all other refs than the one
223
// from mTimers have gone away (the last non-mTimers[i]-ref's Release
224
// must be racing with us, blocked in gThread->RemoveTimer waiting
225
// for TimerThread::mLock, under nsTimerImpl::Release.
228
RemoveTimerInternal(timer);
230
// We release mLock around the Fire call to avoid deadlock.
234
if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
235
PR_LOG(gTimerLog, PR_LOG_DEBUG,
236
("Timer thread woke up %dms from when it was supposed to\n",
237
(now >= timer->mTimeout)
238
? PR_IntervalToMilliseconds(now - timer->mTimeout)
239
: -(PRInt32)PR_IntervalToMilliseconds(timer->mTimeout-now))
244
// We are going to let the call to PostTimerEvent here handle the
245
// release of the timer so that we don't end up releasing the timer
246
// on the TimerThread instead of on the thread it targets.
247
timer->PostTimerEvent();
254
// Update now, as PostTimerEvent plus the locking may have taken a
255
// tick or two, and we may goto next below.
256
now = PR_IntervalNow();
260
if (mTimers.Count() > 0) {
261
timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[0]);
263
PRIntervalTime timeout = timer->mTimeout + mTimeoutAdjustment;
265
// Don't wait at all (even for PR_INTERVAL_NO_WAIT) if the next timer
266
// is due now or overdue.
267
if (!TIMER_LESS_THAN(now, timeout))
269
waitFor = timeout - now;
273
if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
274
if (waitFor == PR_INTERVAL_NO_TIMEOUT)
275
PR_LOG(gTimerLog, PR_LOG_DEBUG,
276
("waiting for PR_INTERVAL_NO_TIMEOUT\n"));
278
PR_LOG(gTimerLog, PR_LOG_DEBUG,
279
("waiting for %u\n", PR_IntervalToMilliseconds(waitFor)));
285
PR_WaitCondVar(mCondVar, waitFor);
292
nsresult TimerThread::AddTimer(nsTimerImpl *aTimer)
294
nsAutoLock lock(mLock);
296
// Add the timer to our list.
297
PRInt32 i = AddTimerInternal(aTimer);
299
return NS_ERROR_OUT_OF_MEMORY;
301
// Awaken the timer thread.
302
if (mCondVar && mWaiting && i == 0)
303
PR_NotifyCondVar(mCondVar);
308
nsresult TimerThread::TimerDelayChanged(nsTimerImpl *aTimer)
310
nsAutoLock lock(mLock);
312
// Our caller has a strong ref to aTimer, so it can't go away here under
313
// ReleaseTimerInternal.
314
RemoveTimerInternal(aTimer);
316
PRInt32 i = AddTimerInternal(aTimer);
318
return NS_ERROR_OUT_OF_MEMORY;
320
// Awaken the timer thread.
321
if (mCondVar && mWaiting && i == 0)
322
PR_NotifyCondVar(mCondVar);
327
nsresult TimerThread::RemoveTimer(nsTimerImpl *aTimer)
329
nsAutoLock lock(mLock);
331
// Remove the timer from our array. Tell callers that aTimer was not found
332
// by returning NS_ERROR_NOT_AVAILABLE. Unlike the TimerDelayChanged case
333
// immediately above, our caller may be passing a (now-)weak ref in via the
334
// aTimer param, specifically when nsTimerImpl::Release loses a race with
335
// TimerThread::Run, must wait for the mLock auto-lock here, and during the
336
// wait Run drops the only remaining ref to aTimer via RemoveTimerInternal.
338
if (!RemoveTimerInternal(aTimer))
339
return NS_ERROR_NOT_AVAILABLE;
341
// Awaken the timer thread.
342
if (mCondVar && mWaiting)
343
PR_NotifyCondVar(mCondVar);
348
// This function must be called from within a lock
349
PRInt32 TimerThread::AddTimerInternal(nsTimerImpl *aTimer)
351
PRIntervalTime now = PR_IntervalNow();
352
PRInt32 count = mTimers.Count();
354
for (; i < count; i++) {
355
nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[i]);
357
// Don't break till we have skipped any overdue timers. Do not include
358
// mTimeoutAdjustment here, because we are really trying to avoid calling
359
// TIMER_LESS_THAN(t, u), where the t is now + DELAY_INTERVAL_MAX, u is
360
// now - overdue, and DELAY_INTERVAL_MAX + overdue > DELAY_INTERVAL_LIMIT.
361
// In other words, we want to use now-based time, now adjusted time, even
362
// though "overdue" ultimately depends on adjusted time.
364
// XXX does this hold for TYPE_REPEATING_PRECISE? /be
366
if (TIMER_LESS_THAN(now, timer->mTimeout) &&
367
TIMER_LESS_THAN(aTimer->mTimeout, timer->mTimeout)) {
372
if (!mTimers.InsertElementAt(aTimer, i))
375
aTimer->mArmed = PR_TRUE;
380
PRBool TimerThread::RemoveTimerInternal(nsTimerImpl *aTimer)
382
if (!mTimers.RemoveElement(aTimer))
385
// Order is crucial here -- see nsTimerImpl::Release.
386
aTimer->mArmed = PR_FALSE;
391
void TimerThread::DoBeforeSleep()
396
void TimerThread::DoAfterSleep()
398
for (PRInt32 i = 0; i < mTimers.Count(); i ++) {
399
nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[i]);
400
// get and set the delay to cause its timeout to be recomputed
402
timer->GetDelay(&delay);
403
timer->SetDelay(delay);
406
// nuke the stored adjustments, so they get recalibrated
407
mTimeoutAdjustment = 0;
408
mDelayLineCounter = 0;
409
mSleeping = PR_FALSE;
413
/* void observe (in nsISupports aSubject, in string aTopic, in wstring aData); */
415
TimerThread::Observe(nsISupports* /* aSubject */, const char *aTopic, const PRUnichar* /* aData */)
417
if (strcmp(aTopic, "sleep_notification") == 0)
419
else if (strcmp(aTopic, "wake_notification") == 0)