Back to index

lightning-sunbird  0.9+nobinonly
TimerThread.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
00002  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00003  *
00004  * ***** BEGIN LICENSE BLOCK *****
00005  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00006  *
00007  * The contents of this file are subject to the Mozilla Public License Version
00008  * 1.1 (the "License"); you may not use this file except in compliance with
00009  * the License. You may obtain a copy of the License at
00010  * http://www.mozilla.org/MPL/
00011  *
00012  * Software distributed under the License is distributed on an "AS IS" basis,
00013  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00014  * for the specific language governing rights and limitations under the
00015  * License.
00016  *
00017  * The Original Code is mozilla.org code.
00018  *
00019  * The Initial Developer of the Original Code is
00020  * Netscape Communications Corporation.
00021  * Portions created by the Initial Developer are Copyright (C) 2001
00022  * the Initial Developer. All Rights Reserved.
00023  *
00024  * Contributor(s):
00025  *   Stuart Parmenter <pavlov@netscape.com>
00026  *
00027  * Alternatively, the contents of this file may be used under the terms of
00028  * either of the GNU General Public License Version 2 or later (the "GPL"),
00029  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00030  * in which case the provisions of the GPL or the LGPL are applicable instead
00031  * of those above. If you wish to allow use of your version of this file only
00032  * under the terms of either the GPL or the LGPL, and not to allow others to
00033  * use your version of this file under the terms of the MPL, indicate your
00034  * decision by deleting the provisions above and replace them with the notice
00035  * and other provisions required by the GPL or the LGPL. If you do not delete
00036  * the provisions above, a recipient may use your version of this file under
00037  * the terms of any one of the MPL, the GPL or the LGPL.
00038  *
00039  * ***** END LICENSE BLOCK ***** */
00040 
00041 #include "nsTimerImpl.h"
00042 #include "TimerThread.h"
00043 
00044 #include "nsAutoLock.h"
00045 #include "pratom.h"
00046 
00047 #include "nsIObserverService.h"
00048 #include "nsIServiceManager.h"
00049 
00050 NS_IMPL_THREADSAFE_ISUPPORTS2(TimerThread, nsIRunnable, nsIObserver)
00051 
00052 TimerThread::TimerThread() :
00053   mInitInProgress(0),
00054   mInitialized(PR_FALSE),
00055   mLock(nsnull),
00056   mCondVar(nsnull),
00057   mShutdown(PR_FALSE),
00058   mWaiting(PR_FALSE),
00059   mSleeping(PR_FALSE),
00060   mDelayLineCounter(0),
00061   mMinTimerPeriod(0),
00062   mTimeoutAdjustment(0)
00063 {
00064 }
00065 
00066 TimerThread::~TimerThread()
00067 {
00068   if (mCondVar)
00069     PR_DestroyCondVar(mCondVar);
00070   if (mLock)
00071     PR_DestroyLock(mLock);
00072 
00073   mThread = nsnull;
00074 
00075   PRInt32 n = mTimers.Count();
00076   while (--n >= 0) {
00077     nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[n]);
00078     NS_RELEASE(timer);
00079   }
00080 }
00081 
00082 nsresult
00083 TimerThread::InitLocks()
00084 {
00085   NS_ASSERTION(!mLock, "InitLocks called twice?");
00086   mLock = PR_NewLock();
00087   if (!mLock)
00088     return NS_ERROR_OUT_OF_MEMORY;
00089 
00090   mCondVar = PR_NewCondVar(mLock);
00091   if (!mCondVar)
00092     return NS_ERROR_OUT_OF_MEMORY;
00093 
00094   return NS_OK;
00095 }
00096 
00097 nsresult TimerThread::Init()
00098 {
00099   if (mInitialized) {
00100     if (!mThread)
00101       return NS_ERROR_FAILURE;
00102 
00103     return NS_OK;
00104   }
00105 
00106   if (PR_AtomicSet(&mInitInProgress, 1) == 0) {
00107     nsresult rv;
00108 
00109     mEventQueueService = do_GetService("@mozilla.org/event-queue-service;1", &rv);
00110     if (NS_SUCCEEDED(rv)) {
00111       nsCOMPtr<nsIObserverService> observerService
00112         (do_GetService("@mozilla.org/observer-service;1", &rv));
00113 
00114       if (NS_SUCCEEDED(rv)) {
00115         // We hold on to mThread to keep the thread alive.
00116         rv = NS_NewThread(getter_AddRefs(mThread),
00117                           NS_STATIC_CAST(nsIRunnable*, this),
00118                           0,
00119                           PR_JOINABLE_THREAD,
00120                           PR_PRIORITY_NORMAL,
00121                           PR_GLOBAL_THREAD);
00122 
00123         if (NS_FAILED(rv)) {
00124           mThread = nsnull;
00125         }
00126         else {
00127           // We'll be released at xpcom shutdown
00128           observerService->AddObserver(this, "sleep_notification", PR_FALSE);
00129           observerService->AddObserver(this, "wake_notification", PR_FALSE);
00130         }
00131       }
00132     }
00133 
00134     PR_Lock(mLock);
00135     mInitialized = PR_TRUE;
00136     PR_NotifyAllCondVar(mCondVar);
00137     PR_Unlock(mLock);
00138   }
00139   else {
00140     PR_Lock(mLock);
00141     while (!mInitialized) {
00142       PR_WaitCondVar(mCondVar, PR_INTERVAL_NO_TIMEOUT);
00143     }
00144     PR_Unlock(mLock);
00145   }
00146 
00147   if (!mThread)
00148     return NS_ERROR_FAILURE;
00149 
00150   return NS_OK;
00151 }
00152 
00153 nsresult TimerThread::Shutdown()
00154 {
00155   if (!mThread)
00156     return NS_ERROR_NOT_INITIALIZED;
00157 
00158   {   // lock scope
00159     nsAutoLock lock(mLock);
00160 
00161     mShutdown = PR_TRUE;
00162 
00163     // notify the cond var so that Run() can return
00164     if (mCondVar && mWaiting)
00165       PR_NotifyCondVar(mCondVar);
00166 
00167     nsTimerImpl *timer;
00168     for (PRInt32 i = mTimers.Count() - 1; i >= 0; i--) {
00169       timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[i]);
00170       RemoveTimerInternal(timer);
00171     }
00172   }
00173 
00174   mThread->Join();    // wait for the thread to die
00175   return NS_OK;
00176 }
00177 
00178 // Keep track of how early (positive slack) or late (negative slack) timers
00179 // are running, and use the filtered slack number to adaptively estimate how
00180 // early timers should fire to be "on time".
00181 void TimerThread::UpdateFilter(PRUint32 aDelay, PRIntervalTime aTimeout,
00182                                PRIntervalTime aNow)
00183 {
00184   PRInt32 slack = (PRInt32) (aTimeout - aNow);
00185   double smoothSlack = 0;
00186   PRUint32 i, filterLength;
00187   static PRIntervalTime kFilterFeedbackMaxTicks =
00188     PR_MillisecondsToInterval(FILTER_FEEDBACK_MAX);
00189 
00190   if (slack > 0) {
00191     if (slack > (PRInt32)kFilterFeedbackMaxTicks)
00192       slack = kFilterFeedbackMaxTicks;
00193   } else {
00194     if (slack < -(PRInt32)kFilterFeedbackMaxTicks)
00195       slack = -(PRInt32)kFilterFeedbackMaxTicks;
00196   }
00197   mDelayLine[mDelayLineCounter & DELAY_LINE_LENGTH_MASK] = slack;
00198   if (++mDelayLineCounter < DELAY_LINE_LENGTH) {
00199     // Startup mode: accumulate a full delay line before filtering.
00200     PR_ASSERT(mTimeoutAdjustment == 0);
00201     filterLength = 0;
00202   } else {
00203     // Past startup: compute number of filter taps based on mMinTimerPeriod.
00204     if (mMinTimerPeriod == 0) {
00205       mMinTimerPeriod = (aDelay != 0) ? aDelay : 1;
00206     } else if (aDelay != 0 && aDelay < mMinTimerPeriod) {
00207       mMinTimerPeriod = aDelay;
00208     }
00209 
00210     filterLength = (PRUint32) (FILTER_DURATION / mMinTimerPeriod);
00211     if (filterLength > DELAY_LINE_LENGTH)
00212       filterLength = DELAY_LINE_LENGTH;
00213     else if (filterLength < 4)
00214       filterLength = 4;
00215 
00216     for (i = 1; i <= filterLength; i++)
00217       smoothSlack += mDelayLine[(mDelayLineCounter-i) & DELAY_LINE_LENGTH_MASK];
00218     smoothSlack /= filterLength;
00219 
00220     // XXXbe do we need amplification?  hacking a fudge factor, need testing...
00221     mTimeoutAdjustment = (PRInt32) (smoothSlack * 1.5);
00222   }
00223 
00224 #ifdef DEBUG_TIMERS
00225   if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
00226     PR_LOG(gTimerLog, PR_LOG_DEBUG,
00227            ("UpdateFilter: smoothSlack = %g, filterLength = %u\n",
00228             smoothSlack, filterLength));
00229   }
00230 #endif
00231 }
00232 
00233 /* void Run(); */
00234 NS_IMETHODIMP TimerThread::Run()
00235 {
00236   nsAutoLock lock(mLock);
00237 
00238   while (!mShutdown) {
00239     PRIntervalTime waitFor;
00240 
00241     if (mSleeping) {
00242       // Sleep for 0.1 seconds while not firing timers.
00243       waitFor = PR_MillisecondsToInterval(100);
00244     } else {
00245       waitFor = PR_INTERVAL_NO_TIMEOUT;
00246       PRIntervalTime now = PR_IntervalNow();
00247       nsTimerImpl *timer = nsnull;
00248 
00249       if (mTimers.Count() > 0) {
00250         timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[0]);
00251 
00252         if (!TIMER_LESS_THAN(now, timer->mTimeout + mTimeoutAdjustment)) {
00253     next:
00254           // NB: AddRef before the Release under RemoveTimerInternal to avoid
00255           // mRefCnt passing through zero, in case all other refs than the one
00256           // from mTimers have gone away (the last non-mTimers[i]-ref's Release
00257           // must be racing with us, blocked in gThread->RemoveTimer waiting
00258           // for TimerThread::mLock, under nsTimerImpl::Release.
00259 
00260           NS_ADDREF(timer);
00261           RemoveTimerInternal(timer);
00262 
00263           // We release mLock around the Fire call to avoid deadlock.
00264           lock.unlock();
00265 
00266 #ifdef DEBUG_TIMERS
00267           if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
00268             PR_LOG(gTimerLog, PR_LOG_DEBUG,
00269                    ("Timer thread woke up %dms from when it was supposed to\n",
00270                     (now >= timer->mTimeout)
00271                     ? PR_IntervalToMilliseconds(now - timer->mTimeout)
00272                     : -(PRInt32)PR_IntervalToMilliseconds(timer->mTimeout-now))
00273                   );
00274           }
00275 #endif
00276 
00277           // We are going to let the call to PostTimerEvent here handle the
00278           // release of the timer so that we don't end up releasing the timer
00279           // on the TimerThread instead of on the thread it targets.
00280           timer->PostTimerEvent();
00281           timer = nsnull;
00282 
00283           lock.lock();
00284           if (mShutdown)
00285             break;
00286 
00287           // Update now, as PostTimerEvent plus the locking may have taken a
00288           // tick or two, and we may goto next below.
00289           now = PR_IntervalNow();
00290         }
00291       }
00292 
00293       if (mTimers.Count() > 0) {
00294         timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[0]);
00295 
00296         PRIntervalTime timeout = timer->mTimeout + mTimeoutAdjustment;
00297 
00298         // Don't wait at all (even for PR_INTERVAL_NO_WAIT) if the next timer
00299         // is due now or overdue.
00300         if (!TIMER_LESS_THAN(now, timeout))
00301           goto next;
00302         waitFor = timeout - now;
00303       }
00304 
00305 #ifdef DEBUG_TIMERS
00306       if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) {
00307         if (waitFor == PR_INTERVAL_NO_TIMEOUT)
00308           PR_LOG(gTimerLog, PR_LOG_DEBUG,
00309                  ("waiting for PR_INTERVAL_NO_TIMEOUT\n"));
00310         else
00311           PR_LOG(gTimerLog, PR_LOG_DEBUG,
00312                  ("waiting for %u\n", PR_IntervalToMilliseconds(waitFor)));
00313       }
00314 #endif
00315     }
00316 
00317     mWaiting = PR_TRUE;
00318     PR_WaitCondVar(mCondVar, waitFor);
00319     mWaiting = PR_FALSE;
00320   }
00321 
00322   return NS_OK;
00323 }
00324 
00325 nsresult TimerThread::AddTimer(nsTimerImpl *aTimer)
00326 {
00327   nsAutoLock lock(mLock);
00328 
00329   // Add the timer to our list.
00330   PRInt32 i = AddTimerInternal(aTimer);
00331   if (i < 0)
00332     return NS_ERROR_OUT_OF_MEMORY;
00333 
00334   // Awaken the timer thread.
00335   if (mCondVar && mWaiting && i == 0)
00336     PR_NotifyCondVar(mCondVar);
00337 
00338   return NS_OK;
00339 }
00340 
00341 nsresult TimerThread::TimerDelayChanged(nsTimerImpl *aTimer)
00342 {
00343   nsAutoLock lock(mLock);
00344 
00345   // Our caller has a strong ref to aTimer, so it can't go away here under
00346   // ReleaseTimerInternal.
00347   RemoveTimerInternal(aTimer);
00348 
00349   PRInt32 i = AddTimerInternal(aTimer);
00350   if (i < 0)
00351     return NS_ERROR_OUT_OF_MEMORY;
00352 
00353   // Awaken the timer thread.
00354   if (mCondVar && mWaiting && i == 0)
00355     PR_NotifyCondVar(mCondVar);
00356 
00357   return NS_OK;
00358 }
00359 
00360 nsresult TimerThread::RemoveTimer(nsTimerImpl *aTimer)
00361 {
00362   nsAutoLock lock(mLock);
00363 
00364   // Remove the timer from our array.  Tell callers that aTimer was not found
00365   // by returning NS_ERROR_NOT_AVAILABLE.  Unlike the TimerDelayChanged case
00366   // immediately above, our caller may be passing a (now-)weak ref in via the
00367   // aTimer param, specifically when nsTimerImpl::Release loses a race with
00368   // TimerThread::Run, must wait for the mLock auto-lock here, and during the
00369   // wait Run drops the only remaining ref to aTimer via RemoveTimerInternal.
00370 
00371   if (!RemoveTimerInternal(aTimer))
00372     return NS_ERROR_NOT_AVAILABLE;
00373 
00374   // Awaken the timer thread.
00375   if (mCondVar && mWaiting)
00376     PR_NotifyCondVar(mCondVar);
00377 
00378   return NS_OK;
00379 }
00380 
00381 // This function must be called from within a lock
00382 PRInt32 TimerThread::AddTimerInternal(nsTimerImpl *aTimer)
00383 {
00384   PRIntervalTime now = PR_IntervalNow();
00385   PRInt32 count = mTimers.Count();
00386   PRInt32 i = 0;
00387   for (; i < count; i++) {
00388     nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl *, mTimers[i]);
00389 
00390     // Don't break till we have skipped any overdue timers.  Do not include
00391     // mTimeoutAdjustment here, because we are really trying to avoid calling
00392     // TIMER_LESS_THAN(t, u), where the t is now + DELAY_INTERVAL_MAX, u is
00393     // now - overdue, and DELAY_INTERVAL_MAX + overdue > DELAY_INTERVAL_LIMIT.
00394     // In other words, we want to use now-based time, now adjusted time, even
00395     // though "overdue" ultimately depends on adjusted time.
00396 
00397     // XXX does this hold for TYPE_REPEATING_PRECISE?  /be
00398 
00399     if (TIMER_LESS_THAN(now, timer->mTimeout) &&
00400         TIMER_LESS_THAN(aTimer->mTimeout, timer->mTimeout)) {
00401       break;
00402     }
00403   }
00404 
00405   if (!mTimers.InsertElementAt(aTimer, i))
00406     return -1;
00407 
00408   aTimer->mArmed = PR_TRUE;
00409   NS_ADDREF(aTimer);
00410   return i;
00411 }
00412 
00413 PRBool TimerThread::RemoveTimerInternal(nsTimerImpl *aTimer)
00414 {
00415   if (!mTimers.RemoveElement(aTimer))
00416     return PR_FALSE;
00417 
00418   // Order is crucial here -- see nsTimerImpl::Release.
00419   aTimer->mArmed = PR_FALSE;
00420   NS_RELEASE(aTimer);
00421   return PR_TRUE;
00422 }
00423 
00424 void TimerThread::DoBeforeSleep()
00425 {
00426   mSleeping = PR_TRUE;
00427 }
00428 
00429 void TimerThread::DoAfterSleep()
00430 {
00431   mSleeping = PR_TRUE; // wake may be notified without preceding sleep notification
00432   for (PRInt32 i = 0; i < mTimers.Count(); i ++) {
00433     nsTimerImpl *timer = NS_STATIC_CAST(nsTimerImpl*, mTimers[i]);
00434     // get and set the delay to cause its timeout to be recomputed
00435     PRUint32 delay;
00436     timer->GetDelay(&delay);
00437     timer->SetDelay(delay);
00438   }
00439 
00440   // nuke the stored adjustments, so they get recalibrated
00441   mTimeoutAdjustment = 0;
00442   mDelayLineCounter = 0;
00443   mSleeping = PR_FALSE;
00444 }
00445 
00446 
00447 /* void observe (in nsISupports aSubject, in string aTopic, in wstring aData); */
00448 NS_IMETHODIMP
00449 TimerThread::Observe(nsISupports* /* aSubject */, const char *aTopic, const PRUnichar* /* aData */)
00450 {
00451   if (strcmp(aTopic, "sleep_notification") == 0)
00452     DoBeforeSleep();
00453   else if (strcmp(aTopic, "wake_notification") == 0)
00454     DoAfterSleep();
00455 
00456   return NS_OK;
00457 }