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)
62 const char* kHighMark
= "/sys/kernel/high_watermark";
64 // Need to implement the nsIMemory::IsLowMemory() predicate
65 #undef NS_MEMORY_FLUSHER
68 #ifdef NS_MEMORY_FLUSHER
72 ////////////////////////////////////////////////////////////////////////////////
73 // Define NS_OUT_OF_MEMORY_TESTER if you want to force memory failures
76 #define NS_OUT_OF_MEMORY_TESTER
79 #ifdef NS_OUT_OF_MEMORY_TESTER
81 // flush memory one in this number of times:
82 #define NS_FLUSH_FREQUENCY 100000
84 // fail allocation one in this number of flushes:
85 #define NS_FAIL_FREQUENCY 10
87 PRUint32 gFlushFreq
= 0;
88 PRUint32 gFailFreq
= 0;
91 mallocator(PRSize size
, PRUint32
& counter
, PRUint32 max
)
93 if (counter
++ >= max
) {
95 NS_ASSERTION(0, "about to fail allocation... watch out");
98 return PR_Malloc(size
);
102 reallocator(void* ptr
, PRSize size
, PRUint32
& counter
, PRUint32 max
)
104 if (counter
++ >= max
) {
106 NS_ASSERTION(0, "about to fail reallocation... watch out");
109 return PR_Realloc(ptr
, size
);
112 #define MALLOC1(s) mallocator(s, gFlushFreq, NS_FLUSH_FREQUENCY)
113 #define REALLOC1(p, s) reallocator(p, s, gFlushFreq, NS_FLUSH_FREQUENCY)
117 #define MALLOC1(s) PR_Malloc(s)
118 #define REALLOC1(p, s) PR_Realloc(p, s)
120 #endif // NS_OUT_OF_MEMORY_TESTER
122 #if defined(XDEBUG_waterson)
123 #define NS_TEST_MEMORY_FLUSHER
126 #ifdef NS_MEMORY_FLUSHER
128 * A class that is used to periodically check the status of the system,
129 * determine if too much memory is in use, and if so, trigger a "memory flush".
131 class MemoryFlusher
: public nsITimerCallback
134 // We don't use the generic macros because we are a special static object
135 NS_IMETHOD
QueryInterface(REFNSIID aIID
, void** aResult
);
136 NS_IMETHOD_(nsrefcnt
) AddRef(void) { return 2; }
137 NS_IMETHOD_(nsrefcnt
) Release(void) { return 1; }
139 NS_DECL_NSITIMERCALLBACK
145 static PRIntervalTime sTimeout
;
146 static PRLock
* sLock
;
147 static PRCondVar
* sCVar
;
150 kTimeout
= 60000 // milliseconds
154 static MemoryFlusher sGlobalMemoryFlusher
;
156 #endif // NS_MEMORY_FLUSHER
158 static nsMemoryImpl sGlobalMemory
;
160 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl
, nsIMemory
)
162 NS_IMETHODIMP_(void*)
163 nsMemoryImpl::Alloc(PRSize size
)
165 return NS_Alloc(size
);
168 NS_IMETHODIMP_(void*)
169 nsMemoryImpl::Realloc(void* ptr
, PRSize size
)
171 return NS_Realloc(ptr
, size
);
175 nsMemoryImpl::Free(void* ptr
)
181 nsMemoryImpl::HeapMinimize(PRBool aImmediate
)
183 return FlushMemory(NS_LITERAL_STRING("heap-minimize").get(), aImmediate
);
187 nsMemoryImpl::IsLowMemory(PRBool
*result
)
191 GlobalMemoryStatus(&stat
);
192 *result
= ((float)stat
.dwAvailPhys
/ stat
.dwTotalPhys
) < 0.1;
193 #elif defined(XP_WIN)
195 GlobalMemoryStatus(&stat
);
196 *result
= ((float)stat
.dwAvailPageFile
/ stat
.dwTotalPageFile
) < 0.1;
197 #elif defined(NS_OSSO)
198 int fd
= open (kHighMark
, O_RDONLY
);
206 *result
= (c
== '1');
215 nsMemoryImpl::InitFlusher()
217 #ifdef NS_MEMORY_FLUSHER
218 return sGlobalMemoryFlusher
.Init();
225 nsMemoryImpl::Create(nsISupports
* outer
, const nsIID
& aIID
, void **aResult
)
227 NS_ENSURE_NO_AGGREGATION(outer
);
228 return sGlobalMemory
.QueryInterface(aIID
, aResult
);
232 nsMemoryImpl::FlushMemory(const PRUnichar
* aReason
, PRBool aImmediate
)
237 // They've asked us to run the flusher *immediately*. We've
238 // got to be on the UI main thread for us to be able to do
240 if (!NS_IsMainThread()) {
241 NS_ERROR("can't synchronously flush memory: not on UI thread");
242 return NS_ERROR_FAILURE
;
246 PRInt32 lastVal
= PR_AtomicSet(&sIsFlushing
, 1);
250 // Run the flushers immediately if we can; otherwise, proxy to the
251 // UI thread an run 'em asynchronously.
253 rv
= RunFlushers(aReason
);
256 sFlushEvent
.mReason
= aReason
;
257 rv
= NS_DispatchToMainThread(&sFlushEvent
, NS_DISPATCH_NORMAL
);
264 nsMemoryImpl::RunFlushers(const PRUnichar
* aReason
)
266 nsCOMPtr
<nsIObserverService
> os
= do_GetService("@mozilla.org/observer-service;1");
268 os
->NotifyObservers(this, "memory-pressure", aReason
);
275 // XXX need NS_IMPL_STATIC_ADDREF/RELEASE
276 NS_IMETHODIMP_(nsrefcnt
) nsMemoryImpl::FlushEvent::AddRef() { return 2; }
277 NS_IMETHODIMP_(nsrefcnt
) nsMemoryImpl::FlushEvent::Release() { return 1; }
278 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl::FlushEvent
, nsIRunnable
)
281 nsMemoryImpl::FlushEvent::Run()
283 sGlobalMemory
.RunFlushers(mReason
);
288 nsMemoryImpl::sIsFlushing
= 0;
290 nsMemoryImpl::FlushEvent
291 nsMemoryImpl::sFlushEvent
;
294 NS_Alloc(PRSize size
)
296 void* result
= MALLOC1(size
);
298 // Request an asynchronous flush
299 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE
);
305 NS_Realloc(void* ptr
, PRSize size
)
307 void* result
= REALLOC1(ptr
, size
);
308 if (! result
&& size
!= 0) {
309 // Request an asynchronous flush
310 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE
);
321 #ifdef NS_MEMORY_FLUSHER
323 NS_IMPL_QUERY_INTERFACE1(MemoryFlusher
, nsITimerCallback
)
326 MemoryFlusher::Notify(nsITimer
*timer
)
329 sGlobalMemory
.IsLowMemory(&isLowMemory
);
331 #ifdef NS_TEST_MEMORY_FLUSHER
332 // Fire the flusher *every* time
333 isLowMemory
= PR_TRUE
;
337 sGlobalMemory
.FlushMemory(NS_LITERAL_STRING("low-memory").get(),
343 MemoryFlusher::Init()
345 nsCOMPtr
<nsITimer
> timer
= do_CreateInstance(NS_TIMER_CONTRACTID
);
346 NS_ENSURE_STATE(timer
);
348 // There is no need to keep a reference to the timer object because we
349 // don't need to kill the timer. It will be killed automatically when
350 // XPCOM is shutdown.
352 return timer
->InitWithCallback(this, kTimeout
,
353 nsITimer::TYPE_REPEATING_SLACK
);
356 #endif // NS_MEMORY_FLUSHER
359 NS_GetMemoryManager(nsIMemory
* *result
)
361 return sGlobalMemory
.QueryInterface(NS_GET_IID(nsIMemory
), (void**) result
);