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
58 #elif defined (NS_OSSO)
61 // Need to implement the nsIMemory::IsLowMemory() predicate
62 #undef NS_MEMORY_FLUSHER
65 #ifdef NS_MEMORY_FLUSHER
69 ////////////////////////////////////////////////////////////////////////////////
70 // Define NS_OUT_OF_MEMORY_TESTER if you want to force memory failures
73 #define NS_OUT_OF_MEMORY_TESTER
76 #ifdef NS_OUT_OF_MEMORY_TESTER
78 // flush memory one in this number of times:
79 #define NS_FLUSH_FREQUENCY 100000
81 // fail allocation one in this number of flushes:
82 #define NS_FAIL_FREQUENCY 10
84 PRUint32 gFlushFreq
= 0;
85 PRUint32 gFailFreq
= 0;
88 mallocator(PRSize size
, PRUint32
& counter
, PRUint32 max
)
90 if (counter
++ >= max
) {
92 NS_ASSERTION(0, "about to fail allocation... watch out");
95 return PR_Malloc(size
);
99 reallocator(void* ptr
, PRSize size
, PRUint32
& counter
, PRUint32 max
)
101 if (counter
++ >= max
) {
103 NS_ASSERTION(0, "about to fail reallocation... watch out");
106 return PR_Realloc(ptr
, size
);
109 #define MALLOC1(s) mallocator(s, gFlushFreq, NS_FLUSH_FREQUENCY)
110 #define REALLOC1(p, s) reallocator(p, s, gFlushFreq, NS_FLUSH_FREQUENCY)
114 #define MALLOC1(s) PR_Malloc(s)
115 #define REALLOC1(p, s) PR_Realloc(p, s)
117 #endif // NS_OUT_OF_MEMORY_TESTER
119 #if defined(XDEBUG_waterson)
120 #define NS_TEST_MEMORY_FLUSHER
123 #ifdef NS_MEMORY_FLUSHER
125 * A class that is used to periodically check the status of the system,
126 * determine if too much memory is in use, and if so, trigger a "memory flush".
128 class MemoryFlusher
: public nsITimerCallback
131 // We don't use the generic macros because we are a special static object
132 NS_IMETHOD
QueryInterface(REFNSIID aIID
, void** aResult
);
133 NS_IMETHOD_(nsrefcnt
) AddRef(void) { return 2; }
134 NS_IMETHOD_(nsrefcnt
) Release(void) { return 1; }
136 NS_DECL_NSITIMERCALLBACK
142 static PRIntervalTime sTimeout
;
143 static PRLock
* sLock
;
144 static PRCondVar
* sCVar
;
147 kTimeout
= 60000 // milliseconds
151 static MemoryFlusher sGlobalMemoryFlusher
;
153 #endif // NS_MEMORY_FLUSHER
155 static nsMemoryImpl sGlobalMemory
;
157 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl
, nsIMemory
)
159 NS_IMETHODIMP_(void*)
160 nsMemoryImpl::Alloc(PRSize size
)
162 return NS_Alloc(size
);
165 NS_IMETHODIMP_(void*)
166 nsMemoryImpl::Realloc(void* ptr
, PRSize size
)
168 return NS_Realloc(ptr
, size
);
172 nsMemoryImpl::Free(void* ptr
)
178 nsMemoryImpl::HeapMinimize(PRBool aImmediate
)
180 return FlushMemory(NS_LITERAL_STRING("heap-minimize").get(), aImmediate
);
184 nsMemoryImpl::IsLowMemory(PRBool
*result
)
188 GlobalMemoryStatus(&stat
);
189 *result
= ((float)stat
.dwAvailPhys
/ stat
.dwTotalPhys
) < 0.1;
190 #elif defined(XP_WIN)
192 GlobalMemoryStatus(&stat
);
193 *result
= ((float)stat
.dwAvailPageFile
/ stat
.dwTotalPageFile
) < 0.1;
194 #elif defined(NS_OSSO)
195 osso_mem_usage_t usage
;
196 osso_mem_get_usage(&usage
);
198 // According to the docs, low memory limit isn't set if it is
199 // zero, or if it is greater than 100%.
200 if (usage
.low
== 0 || usage
.low
> usage
.total
)
203 *result
= (PRBool
) usage
.low
<= usage
.used
;
212 nsMemoryImpl::InitFlusher()
214 #ifdef NS_MEMORY_FLUSHER
215 return sGlobalMemoryFlusher
.Init();
222 nsMemoryImpl::Create(nsISupports
* outer
, const nsIID
& aIID
, void **aResult
)
224 NS_ENSURE_NO_AGGREGATION(outer
);
225 return sGlobalMemory
.QueryInterface(aIID
, aResult
);
229 nsMemoryImpl::FlushMemory(const PRUnichar
* aReason
, PRBool aImmediate
)
234 // They've asked us to run the flusher *immediately*. We've
235 // got to be on the UI main thread for us to be able to do
237 if (!NS_IsMainThread()) {
238 NS_ERROR("can't synchronously flush memory: not on UI thread");
239 return NS_ERROR_FAILURE
;
243 PRInt32 lastVal
= PR_AtomicSet(&sIsFlushing
, 1);
247 // Run the flushers immediately if we can; otherwise, proxy to the
248 // UI thread an run 'em asynchronously.
250 rv
= RunFlushers(aReason
);
253 sFlushEvent
.mReason
= aReason
;
254 rv
= NS_DispatchToMainThread(&sFlushEvent
, NS_DISPATCH_NORMAL
);
261 nsMemoryImpl::RunFlushers(const PRUnichar
* aReason
)
263 nsCOMPtr
<nsIObserverService
> os
= do_GetService("@mozilla.org/observer-service;1");
265 os
->NotifyObservers(this, "memory-pressure", aReason
);
272 // XXX need NS_IMPL_STATIC_ADDREF/RELEASE
273 NS_IMETHODIMP_(nsrefcnt
) nsMemoryImpl::FlushEvent::AddRef() { return 2; }
274 NS_IMETHODIMP_(nsrefcnt
) nsMemoryImpl::FlushEvent::Release() { return 1; }
275 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl::FlushEvent
, nsIRunnable
)
278 nsMemoryImpl::FlushEvent::Run()
280 sGlobalMemory
.RunFlushers(mReason
);
285 nsMemoryImpl::sIsFlushing
= 0;
287 nsMemoryImpl::FlushEvent
288 nsMemoryImpl::sFlushEvent
;
291 NS_Alloc(PRSize size
)
293 void* result
= MALLOC1(size
);
295 // Request an asynchronous flush
296 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE
);
302 NS_Realloc(void* ptr
, PRSize size
)
304 void* result
= REALLOC1(ptr
, size
);
305 if (! result
&& size
!= 0) {
306 // Request an asynchronous flush
307 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE
);
318 #ifdef NS_MEMORY_FLUSHER
320 NS_IMPL_QUERY_INTERFACE1(MemoryFlusher
, nsITimerCallback
)
323 MemoryFlusher::Notify(nsITimer
*timer
)
326 sGlobalMemory
.IsLowMemory(&isLowMemory
);
328 #ifdef NS_TEST_MEMORY_FLUSHER
329 // Fire the flusher *every* time
330 isLowMemory
= PR_TRUE
;
334 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("low-memory").get(),
340 MemoryFlusher::Init()
342 nsCOMPtr
<nsITimer
> timer
= do_CreateInstance(NS_TIMER_CONTRACTID
);
343 NS_ENSURE_STATE(timer
);
345 // There is no need to keep a reference to the timer object because we
346 // don't need to kill the timer. It will be killed automatically when
347 // XPCOM is shutdown.
349 return timer
->InitWithCallback(this, kTimeout
,
350 nsITimer::TYPE_REPEATING_SLACK
);
353 #endif // NS_MEMORY_FLUSHER
356 NS_GetMemoryManager(nsIMemory
* *result
)
358 return sGlobalMemory
.QueryInterface(NS_GET_IID(nsIMemory
), (void**) result
);