AvailableMemory.cpp [plain text]
#include "AvailableMemory.h"
#include "Environment.h"
#if BPLATFORM(IOS)
#include "MemoryStatusSPI.h"
#endif
#include "PerProcess.h"
#include "Scavenger.h"
#include "Sizes.h"
#include <mutex>
#if BOS(DARWIN)
#if BPLATFORM(IOS)
#import <algorithm>
#endif
#import <dispatch/dispatch.h>
#import <mach/host_info.h>
#import <mach/mach.h>
#import <mach/mach_error.h>
#import <math.h>
#elif BOS(UNIX)
#include <unistd.h>
#endif
namespace bmalloc {
static const size_t availableMemoryGuess = 512 * bmalloc::MB;
#if BOS(DARWIN)
static size_t memorySizeAccordingToKernel()
{
#if BPLATFORM(IOS_SIMULATOR)
BUNUSED_PARAM(availableMemoryGuess);
return 1024 * bmalloc::MB;
#else
host_basic_info_data_t hostInfo;
mach_port_t host = mach_host_self();
mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count);
mach_port_deallocate(mach_task_self(), host);
if (r != KERN_SUCCESS)
return availableMemoryGuess;
if (hostInfo.max_mem > std::numeric_limits<size_t>::max())
return std::numeric_limits<size_t>::max();
return static_cast<size_t>(hostInfo.max_mem);
#endif
}
#endif
#if BPLATFORM(IOS)
static size_t jetsamLimit()
{
memorystatus_memlimit_properties_t properties;
pid_t pid = getpid();
if (memorystatus_control(MEMORYSTATUS_CMD_GET_MEMLIMIT_PROPERTIES, pid, 0, &properties, sizeof(properties)))
return 840 * bmalloc::MB;
if (properties.memlimit_active < 0)
return std::numeric_limits<size_t>::max();
return static_cast<size_t>(properties.memlimit_active) * bmalloc::MB;
}
#endif
static size_t computeAvailableMemory()
{
#if BOS(DARWIN)
size_t sizeAccordingToKernel = memorySizeAccordingToKernel();
#if BPLATFORM(IOS)
sizeAccordingToKernel = std::min(sizeAccordingToKernel, jetsamLimit());
#endif
size_t multiple = 128 * bmalloc::MB;
return ((sizeAccordingToKernel + multiple - 1) / multiple) * multiple;
#elif BOS(UNIX)
long pages = sysconf(_SC_PHYS_PAGES);
long pageSize = sysconf(_SC_PAGE_SIZE);
if (pages == -1 || pageSize == -1)
return availableMemoryGuess;
return pages * pageSize;
#else
return availableMemoryGuess;
#endif
}
size_t availableMemory()
{
static size_t availableMemory;
static std::once_flag onceFlag;
std::call_once(onceFlag, [] {
availableMemory = computeAvailableMemory();
});
return availableMemory;
}
#if BPLATFORM(IOS)
MemoryStatus memoryStatus()
{
task_vm_info_data_t vmInfo;
mach_msg_type_number_t vmSize = TASK_VM_INFO_COUNT;
size_t memoryFootprint = 0;
if (KERN_SUCCESS == task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)(&vmInfo), &vmSize))
memoryFootprint = static_cast<size_t>(vmInfo.phys_footprint);
double percentInUse = static_cast<double>(memoryFootprint) / static_cast<double>(availableMemory());
double percentAvailableMemoryInUse = std::min(percentInUse, 1.0);
return MemoryStatus(memoryFootprint, percentAvailableMemoryInUse);
}
#endif
}