1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
15 * The Original Code is mozilla.org code.
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998
20 * the Initial Developer. All Rights Reserved.
24 * Alternatively, the contents of this file may be used under the terms of
25 * either of the GNU General Public License Version 2 or later (the "GPL"),
26 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
36 * ***** END LICENSE BLOCK ***** */
39 #include "nsMemoryImpl.h"
40 #include "nsThreadUtils.h"
42 #include "nsIObserverService.h"
43 #include "nsIServiceManager.h"
44 #include "nsISupportsArray.h"
50 #include "nsAlgorithm.h"
51 #include "nsAutoLock.h"
57 #define NS_MEMORY_FLUSHER
59 // Need to implement the nsIMemory::IsLowMemory() predicate
60 #undef NS_MEMORY_FLUSHER
63 #ifdef NS_MEMORY_FLUSHER
67 ////////////////////////////////////////////////////////////////////////////////
68 // Define NS_OUT_OF_MEMORY_TESTER if you want to force memory failures
71 #define NS_OUT_OF_MEMORY_TESTER
74 #ifdef NS_OUT_OF_MEMORY_TESTER
76 // flush memory one in this number of times:
77 #define NS_FLUSH_FREQUENCY 100000
79 // fail allocation one in this number of flushes:
80 #define NS_FAIL_FREQUENCY 10
82 PRUint32 gFlushFreq
= 0;
83 PRUint32 gFailFreq
= 0;
86 mallocator(PRSize size
, PRUint32
& counter
, PRUint32 max
)
88 if (counter
++ >= max
) {
90 NS_ASSERTION(0, "about to fail allocation... watch out");
93 return PR_Malloc(size
);
97 reallocator(void* ptr
, PRSize size
, PRUint32
& counter
, PRUint32 max
)
99 if (counter
++ >= max
) {
101 NS_ASSERTION(0, "about to fail reallocation... watch out");
104 return PR_Realloc(ptr
, size
);
107 #define MALLOC1(s) mallocator(s, gFlushFreq, NS_FLUSH_FREQUENCY)
108 #define REALLOC1(p, s) reallocator(p, s, gFlushFreq, NS_FLUSH_FREQUENCY)
112 #define MALLOC1(s) PR_Malloc(s)
113 #define REALLOC1(p, s) PR_Realloc(p, s)
115 #endif // NS_OUT_OF_MEMORY_TESTER
117 #if defined(XDEBUG_waterson)
118 #define NS_TEST_MEMORY_FLUSHER
121 #ifdef NS_MEMORY_FLUSHER
123 * A class that is used to periodically check the status of the system,
124 * determine if too much memory is in use, and if so, trigger a "memory flush".
126 class MemoryFlusher
: public nsITimerCallback
129 // We don't use the generic macros because we are a special static object
130 NS_IMETHOD
QueryInterface(REFNSIID aIID
, void** aResult
);
131 NS_IMETHOD_(nsrefcnt
) AddRef(void) { return 2; }
132 NS_IMETHOD_(nsrefcnt
) Release(void) { return 1; }
134 NS_DECL_NSITIMERCALLBACK
140 static PRIntervalTime sTimeout
;
141 static PRLock
* sLock
;
142 static PRCondVar
* sCVar
;
145 kTimeout
= 60000 // milliseconds
149 static MemoryFlusher sGlobalMemoryFlusher
;
151 #endif // NS_MEMORY_FLUSHER
153 static nsMemoryImpl sGlobalMemory
;
155 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl
, nsIMemory
)
157 NS_IMETHODIMP_(void*)
158 nsMemoryImpl::Alloc(PRSize size
)
160 return NS_Alloc(size
);
163 NS_IMETHODIMP_(void*)
164 nsMemoryImpl::Realloc(void* ptr
, PRSize size
)
166 return NS_Realloc(ptr
, size
);
170 nsMemoryImpl::Free(void* ptr
)
176 nsMemoryImpl::HeapMinimize(PRBool aImmediate
)
178 return FlushMemory(NS_LITERAL_STRING("heap-minimize").get(), aImmediate
);
182 nsMemoryImpl::IsLowMemory(PRBool
*result
)
186 GlobalMemoryStatus(&stat
);
187 *result
= ((float)stat
.dwAvailPhys
/ stat
.dwTotalPhys
) < 0.1;
188 #elif defined(XP_WIN)
190 GlobalMemoryStatus(&stat
);
191 *result
= ((float)stat
.dwAvailPageFile
/ stat
.dwTotalPageFile
) < 0.1;
200 nsMemoryImpl::InitFlusher()
202 #ifdef NS_MEMORY_FLUSHER
203 return sGlobalMemoryFlusher
.Init();
210 nsMemoryImpl::Create(nsISupports
* outer
, const nsIID
& aIID
, void **aResult
)
212 NS_ENSURE_NO_AGGREGATION(outer
);
213 return sGlobalMemory
.QueryInterface(aIID
, aResult
);
217 nsMemoryImpl::FlushMemory(const PRUnichar
* aReason
, PRBool aImmediate
)
222 // They've asked us to run the flusher *immediately*. We've
223 // got to be on the UI main thread for us to be able to do
225 if (!NS_IsMainThread()) {
226 NS_ERROR("can't synchronously flush memory: not on UI thread");
227 return NS_ERROR_FAILURE
;
231 PRInt32 lastVal
= PR_AtomicSet(&sIsFlushing
, 1);
235 // Run the flushers immediately if we can; otherwise, proxy to the
236 // UI thread an run 'em asynchronously.
238 rv
= RunFlushers(aReason
);
241 sFlushEvent
.mReason
= aReason
;
242 rv
= NS_DispatchToMainThread(&sFlushEvent
, NS_DISPATCH_NORMAL
);
249 nsMemoryImpl::RunFlushers(const PRUnichar
* aReason
)
251 nsCOMPtr
<nsIObserverService
> os
= do_GetService("@mozilla.org/observer-service;1");
253 os
->NotifyObservers(this, "memory-pressure", aReason
);
260 // XXX need NS_IMPL_STATIC_ADDREF/RELEASE
261 NS_IMETHODIMP_(nsrefcnt
) nsMemoryImpl::FlushEvent::AddRef() { return 2; }
262 NS_IMETHODIMP_(nsrefcnt
) nsMemoryImpl::FlushEvent::Release() { return 1; }
263 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl::FlushEvent
, nsIRunnable
)
266 nsMemoryImpl::FlushEvent::Run()
268 sGlobalMemory
.RunFlushers(mReason
);
273 nsMemoryImpl::sIsFlushing
= 0;
275 nsMemoryImpl::FlushEvent
276 nsMemoryImpl::sFlushEvent
;
279 NS_Alloc(PRSize size
)
281 if (size
> PR_INT32_MAX
)
284 void* result
= MALLOC1(size
);
286 // Request an asynchronous flush
287 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE
);
293 NS_Realloc(void* ptr
, PRSize size
)
295 if (size
> PR_INT32_MAX
)
298 void* result
= REALLOC1(ptr
, size
);
299 if (! result
&& size
!= 0) {
300 // Request an asynchronous flush
301 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE
);
312 #ifdef NS_MEMORY_FLUSHER
314 NS_IMPL_QUERY_INTERFACE1(MemoryFlusher
, nsITimerCallback
)
317 MemoryFlusher::Notify(nsITimer
*timer
)
320 sGlobalMemory
.IsLowMemory(&isLowMemory
);
322 #ifdef NS_TEST_MEMORY_FLUSHER
323 // Fire the flusher *every* time
324 isLowMemory
= PR_TRUE
;
328 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("low-memory").get(),
334 MemoryFlusher::Init()
336 nsCOMPtr
<nsITimer
> timer
= do_CreateInstance(NS_TIMER_CONTRACTID
);
337 NS_ENSURE_STATE(timer
);
339 // There is no need to keep a reference to the timer object because we
340 // don't need to kill the timer. It will be killed automatically when
341 // XPCOM is shutdown.
343 return timer
->InitWithCallback(this, kTimeout
,
344 nsITimer::TYPE_REPEATING_SLACK
);
347 #endif // NS_MEMORY_FLUSHER
350 NS_GetMemoryManager(nsIMemory
* *result
)
352 return sGlobalMemory
.QueryInterface(NS_GET_IID(nsIMemory
), (void**) result
);