Low RAM Configuration

Android supports devices with 512 MB of RAM. This documentation is intended to help OEMs optimize and configure Android kernel 4.4 for low-memory devices. Several of these optimizations are generic enough that they can be applied to previous releases as well.

Android kernel 4.4 platform optimizations

Improved memory management

  • Validated memory-saving kernel configurations: Swap to zram.
  • Kill cached processes if about to be uncached and too large.
  • Don't allow large services to put themselves back into the A Services classification (so they can't cause the launcher to be killed).
  • Kill processes (even ordinarily unkillable ones such as the current IME) that get too large in idle maintenance.
  • Serialize the launch of background services.
  • Tune memory use of low-RAM devices: tighter out-of-memory (OOM) adjustment levels, smaller graphics caches.

Reduced system memory

  • Trimmed system_server and System UI processes (saved several megabytes).
  • Preload dex caches in Dalvik (saved several megabytes).
  • Validated JIT-off option (saves up to 1.5 MB per process).
  • Reduced per-process font cache overhead.
  • Introduced ArrayMap/ArraySet and used extensively in framework as a lighter-footprint replacement for HashMap/HashSet.

Procstats

Added a developer option to show memory state and app memory usage ranked by how often they run and the amount of memory consumed.

API

Added ActivityManager.isLowRamDevice() to allow apps to detect when running on low-memory devices and choose to disable large-RAM features.

Memory tracking

Added memtrack HAL to track graphics memory allocations, additional information in dumpsys meminfo, clarified summaries in meminfo (for example, reported free RAM includes RAM of cached processes, so that OEMs don't try to optimize the wrong thing).

Build-time configuration

Low RAM Device flag

The ActivityManager.isLowRamDevice() flag determines if apps should turn off specific memory-intensive features that work poorly on low-memory devices.

For 512 MB devices, this flag is expected to return true. It can be enabled by the following system property in the device makefile.

PRODUCT_PROPERTY_OVERRIDES += ro.config.low_ram=true

Launcher Configs

The default wallpaper setup on launcher shouldn't use live wallpaper. Low-memory devices shouldn't pre-install any live wallpapers.

Kernel configuration

Tuning kernel/ActivityManager to reduce direct reclaim

Direct reclaim happens when a process or the kernel tries to allocate a page of memory (either directly or due to faulting in a new page) and the kernel has used all available free memory. This requires the kernel to block the allocation while it frees up a page. This in turn often requires disk I/O to flush out a dirty file-backed page or wait for lowmemorykiller to kill a process. This can result in extra I/O in any thread, including a UI thread.

To avoid direct reclaim, the kernel has watermarks that trigger kswapd or background reclaim. This is a thread that tries to free up pages so the next time a real thread allocates, it can succeed quickly.

The default threshold to trigger background reclaim is fairly low, around 2 MB on a 2 GB device and 636 KB on a 512 MB device. The kernel reclaims only a few megabytes of memory in background reclaim. This means any process that quickly allocates more than a few megabytes is going to quickly hit direct reclaim.

Support for a kernel tunable is added in the Android-3.4 kernel branch as patch 92189d47f66c67e5fd92eafaa287e153197a454f ("add extra free kbytes tunable"). Cherry-picking this patch to a device's kernel allows ActivityManager to tell the kernel to try to keep three full-screen 32 bpp buffers of memory free.

These thresholds can be configured with the config.xml framework.

<!-- Device configuration setting the /proc/sys/vm/extra_free_kbytes tunable
in the kernel (if it exists).  A high value will increase the amount of memory
that the kernel tries to keep free, reducing allocation time and causing the
lowmemorykiller to kill earlier.  A low value allows more memory to be used by
processes but may cause more allocations to block waiting on disk I/O or
lowmemorykiller.  Overrides the default value chosen by ActivityManager based
on screen size.  0 prevents keeping any extra memory over what the kernel keeps
by default.  -1 keeps the default. -->
<integer name="config_extraFreeKbytesAbsolute">-1</integer>
<!-- Device configuration adjusting the /proc/sys/vm/extra_free_kbytes
tunable in the kernel (if it exists).  0 uses the default value chosen by
ActivityManager.  A positive value  will increase the amount of memory that the
kernel tries to keep free, reducing allocation time and causing the
lowmemorykiller to kill earlier.  A negative value allows more memory to be
used by processes but may cause more allocations to block waiting on disk I/O
or lowmemorykiller.  Directly added to the default value chosen by
ActivityManager based on screen size. -->
<integer name="config_extraFreeKbytesAdjust">0</integer>

Tuning LowMemoryKiller

ActivityManager configures the thresholds of the LowMemoryKiller to match its expectation of the working set of file-backed pages (cached pages) required to run the processes in each priority level bucket. If a device has high requirements for the working set, for example if the vendor UI requires more memory or if more services have been added, the thresholds can be increased.

The thresholds can be reduced if too much memory is being reserved for file-backed pages, so that background processes are being killed long before disk thrashing would occur due to the cache getting too small.

<!-- Device configuration setting the minfree tunable in the lowmemorykiller
in the kernel.  A high value will cause the lowmemorykiller to fire earlier,
keeping more memory in the file cache and preventing I/O thrashing, but
allowing fewer processes to stay in memory.  A low value will keep more
processes in memory but may cause thrashing if set too low.  Overrides the
default value chosen by ActivityManager based on screen size and total memory
for the largest lowmemorykiller bucket, and scaled proportionally to the
smaller buckets.  -1 keeps the default. -->
<integer name="config_lowMemoryKillerMinFreeKbytesAbsolute">-1</integer>
<!-- Device configuration adjusting the minfree tunable in the
lowmemorykiller in the kernel.  A high value will cause the lowmemorykiller to
fire earlier, keeping more memory in the file cache and preventing I/O
thrashing, but allowing fewer processes to stay in memory.  A low value will
keep more processes in memory but may cause thrashing if set too low.  Directly
added to the default value chosen by          ActivityManager based on screen
size and total memory for the largest lowmemorykiller bucket, and scaled
proportionally to the smaller buckets. 0 keeps the default. -->
<integer name="config_lowMemoryKillerMinFreeKbytesAdjust">0</integer>

Swap to zram

zram swap can increase the amount of memory available in the system by compressing memory pages and putting them in a dynamically allocated swap area of memory. Since this is trading off CPU time for a small increase in memory, you should be careful about measuring the performance impact zram swap has on your system.

Android handles swap to zram at several levels:

  • First, the following kernel options must be enabled to use zram swap effectively:
    • CONFIG_SWAP
    • CONFIG_CGROUP_MEM_RES_CTLR
    • CONFIG_CGROUP_MEM_RES_CTLR_SWAP
    • CONFIG_ZRAM
  • Then, you should add a line that looks like this to your fstab:
    /dev/block/zram0 none swap defaults zramsize=<size in bytes>,swapprio=<swap partition priority>
    
    • zramsize is mandatory and indicates how much uncompressed memory you want the zram area to hold. Compression ratios in the 30-50% range are usually observed.
    • swapprio is only needed if you don't have more than one swap area.

    Label the associated block device as a swap_block_device in the device-specific sepolicy/file_contexts so that it's treated properly by SELinux.

    /dev/block/zram0 u:object_r:swap_block_device:s0
    
  • By default, the Linux kernel swaps in eight pages of memory at a time. When using zram, the incremental cost of reading one page at a time is negligible and may help if the device is under extreme memory pressure. To read only one page at a time, add the following to your init.rc:
    write /proc/sys/vm/page-cluster 0
    
  • In your init.rc after the mount_all /fstab.X line, add:
    swapon_all /fstab.X
    
  • The memory cgroups are automatically configured at boot time if the feature is enabled in the kernel.
  • If memory cgroups are available, ActivityManager marks lower-priority threads as being more swappable than other threads. If memory is needed, the Android kernel starts migrating memory pages to zram swap, giving a higher priority to the memory pages that have been marked by ActivityManager.

Carveouts, Ion, and contiguous memory allocation (CMA)

On low-memory devices, it's important to be mindful about carveouts, especially those that aren't fully used, such as a carveout for secure video playback. There are several solutions to minimize the impact of your carveout regions that depend on the exact requirements of your hardware.

If hardware permits discontiguous memory allocations, the Ion system heap allows memory allocations from system memory, eliminating the need for a carveout. Ion also attempts to make large allocations to eliminate translation lookaside buffer (TLB) pressure on peripherals. If memory regions must be contiguous or confined to a specific address range, the CMA can be used.

This creates a carveout that the system can also use for movable pages. When the region is needed, movable pages are migrated out of it, allowing the system to use a large carveout for other purposes when it's free. You can use CMA directly with the Ion CMA heap.

App optimization tips

  • Review Manage your app's memory and these blog posts:
  • Remove any unused assets from preinstalled apps using development/tools/findunused (this should help make the app smaller).
  • Use the PNG format for assets, especially when they have transparent areas.
  • If writing native code, use calloc() rather than malloc/memset.
  • Don't enable code that writes Parcel data to disk and reads it later.
  • Use SSP filtering instead of subscribing to every package installed. Add filtering like this:
    <data android:scheme="package" android:ssp="com.android.pkg1" />
    <data android:scheme="package" android:ssp="com.myapp.act1" />
    

Understand the various process states in Android

State Meaning Details
SERVICE
SERVICE_RESTARTING
Apps that run in the background for app-related reasons. SERVICESERVICE_RESTARTING are the most common problems apps have when they run in the background too much. Use %duration * pss or %duration as a "badness" metric. Ideally, these apps shouldn't be running at all.
IMPORTANT_FOREGROUND
RECEIVER
Apps running in the background (not directly interacting with the user). These add memory load to the system. Use the (%duration * pss) "badness" value to order these processes. However, many of these apps run for good reasons. The size of pss is an important part of their memory load.
PERSISTENT Persistent system process. Track pss to watch for these processes getting too large.
TOP The process the user is currently interacting with. pss is the important metric here, showing how much memory load the app creates while in use.
HOME
CACHED_EMPTY
The processes the system is keeping around in case they are needed again. These processes can be freely killed at any time and recreated if needed. The memory state (normal, moderate, low, critical) is computed based on how many of these processes the system is running. The key metric for these processes is the pss. In this state, these processes should decrease their memory footprint as much as possible to allow for the maximum total number of processes to be kept around. In this state, a well behaved app generally has a significantly smaller pss footprint than it does in the TOP state.
CACHED_ACTIVITY
CACHED_ACTIVITY_CLIENT
When compared with TOP, these show how well an app releases memory into the background. Excluding CACHED_EMPTY state makes this data better, because it removes situations when the process has started for some reasons besides interacting with the user. This eliminates dealing with the UI overhead CACHED_EMPTY gets when user-related activities.

Analysis

Analyzing app startup time

To analyze your app's startup time, run $ adb shell am start -P or --start-profiler and start your app. The profiler starts after the process is forked from the zygote and before any code is loaded into the fork.

Analyzing using bug reports

Bug reports contain several services, including batterystats, netstats, procstats, and usagestats, which can be used for debugging. Reports can include lines like this:

------ CHECKIN BATTERYSTATS (dumpsys batterystats --checkin) ------
7,0,h,-2558644,97,1946288161,3,2,0,340,4183
7,0,h,-2553041,97,1946288161,3,2,0,340,4183

Checking for any persistent processes

To check for any persistent processes, reboot the device and check the processes. Then, run the device for a few hours and check the processes again. There shouldn't be any long-running processes between the two checks.

Running longevity tests

To run longevity tests, run the device for longer durations and track the memory of the processes to determine if it increases or stays constant. Then create canonical use cases and run longevity tests on these scenarios.