blob: 7d790f7341d6c8d594ad6a536e91e09df7934154 [file]
/*
* Copyright (C) 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEMORY_BUDGET_MANAGER_H
#define ANDROID_MEMORY_BUDGET_MANAGER_H
#include <stdint.h>
#include <sys/cdefs.h>
#include <android/looper.h>
#if !defined(__INTRODUCED_IN)
#define __INTRODUCED_IN(__api_level) /* nothing */
#endif
__BEGIN_DECLS
/**
* Returns the memory usage for the current package against its budget.
*
* @return A positive memory usage value on success. Returns a negative errno code
* on failure. The error code can be any error returned from read(2), -EINVAL
* in case we encounter an error converting the current usage value from a
* string into an integer, -ENOTSUP if memory budgets are not supported or
* -EPERM when called from an isolated process.
*/
int64_t AMemoryBudgetManager_getPackageCurrentUsageBytes(void) __INTRODUCED_IN(38);
/**
* Returns the memory usage for the current process against its budget.
*
* @return A positive memory usage value on success. Returns a negative errno code
* on failure. The error code can be any error returned from read(2), -EINVAL
* in case we encounter an error converting the current usage value from a
* string into an integer or -ENOTSUP if memory budgets are not supported.
*/
int64_t AMemoryBudgetManager_getProcessCurrentUsageBytes(void) __INTRODUCED_IN(38);
/**
* Obtains a file descriptor that can be monitored for package memory budget breaches.
*
* The returned file descriptor is tied to the underlying cgroup v2 memory events.
* It can be added to an existing `epoll` instance (or used with `select`/`poll`).
* The FD will become readable (EPOLLIN/EPOLLPRI) when the package exceeds its
* memory budget and is subjected to internal reclaim pressure.
*
* When the package is in excess of its memory budget, multiple events may be read,
* potentially in close succession. It is the reader's responsibility to debounce
* these events to keep from being overwhelmed. For instance, apps may consider
* reading at most one event per some unit of time.
*
* When the package is in excess of its memory budget, any runtime memory
* allocation may result in direct reclaim and further exacerbate the pressure.
* As such, upon waking from the epoll wait for this FD, you must avoid making
* further significant memory allocations.
*
* Application code can help ease memory pressure by discarding memory
* allocations that are not strictly necessary to perform its functions.
* For instance: trim and downsize caches of Bitmaps or network responses,
* unmap/close files that are not currently necessary, or avoid prefetching
* and preprocessing content.
*
* Such work done in response to this event should be quick to offer
* immediate relief. Conversely, performing long computation or interim
* allocations in order to free memory may do more harm than good.
*
* @return A valid file descriptor on success. The caller takes ownership of this
* file descriptor and must close it using `close()` when it is no longer
* needed. Returns a negative errno code such as -ENOTSUP if memory budgets
* are not supported or any error that open(2) can return, including
* -EPERM when called from an isolated process.
*/
int AMemoryBudgetManager_getPackageMemoryEventsFd(void) __INTRODUCED_IN(38);
/**
* Obtains a file descriptor that can be monitored for process memory budget breaches.
*
* The returned file descriptor is tied to the underlying cgroup v2 memory events.
* It can be added to an existing `epoll` instance (or used with `select`/`poll`).
* The FD will become readable (EPOLLIN/EPOLLPRI) when the process exceeds its
* memory budget and is subjected to internal reclaim pressure.
*
* When the process is in excess of its memory budget, multiple events may be read,
* potentially in close succession. It is the reader's responsibility to debounce
* these events to keep from being overwhelmed. For instance, apps may consider
* reading at most one event per some unit of time.
*
* When the process is in excess of its memory budget, any runtime memory
* allocation may result in direct reclaim and further exacerbate the pressure.
* As such, upon waking from the epoll wait for this FD, you must avoid making
* further significant memory allocations.
*
* Application code can help ease memory pressure by discarding memory
* allocations that are not strictly necessary to perform its functions.
* For instance: trim and downsize caches of Bitmaps or network responses,
* unmap/close files that are not currently necessary, or avoid prefetching
* and preprocessing content.
*
* Such work done in response to this event should be quick to offer
* immediate relief. Conversely, performing long computation or interim
* allocations in order to free memory may do more harm than good.
*
* @return A valid file descriptor on success. The caller takes ownership of this
* file descriptor and must close it using `close()` when it is no longer
* needed. Returns a negative errno code such as -ENOTSUP if memory budgets
* are not supported or any error that open(2) can return.
*/
int AMemoryBudgetManager_getProcessMemoryEventsFd(void) __INTRODUCED_IN(38);
/**
* Bitmask definitions for targeted memory.events monitoring scopes.
*
* See AMemoryBudgetManagerWatcher_onEventsCallback and AMemoryBudgetManagerWatcher_create
*
* Introduced in API 38.
*/
typedef enum __attribute__((flag_enum)) AMemoryBudgetWatcherEventMask : int32_t {
/** Monitor memory.events bound to the entire application package UID. */
AMEMORY_BUDGET_MANAGER_EVENT_PACKAGE = 1 << 0,
/** Monitor memory.events bound strictly to the calling process PID. */
AMEMORY_BUDGET_MANAGER_EVENT_PROCESS = 1 << 1
} AMemoryBudgetWatcherEventMask;
/**
* Container for parsed cgroup v2 memory.events.
*
* For process cgroups, this corresponds to events affecting this process.
* For package cgroups, this is the sum of all events affecting processes
* that belong to this application.
*
* Introduced in API 38.
*/
typedef struct AMemoryBudgetEvent {
/**
* The number of times reclaim was triggered for the cgroup when usage
* was below the 'low' boundary.
*/
int64_t low;
/**
* The number of times processes in the cgroup were throttled and forced
* to perform direct reclaim because the 'high' boundary was exceeded.
*/
int64_t high;
/**
* The number of times the cgroup's memory usage reached the 'max' boundary,
* triggering direct reclaim.
*/
int64_t max;
/**
* The number of times memory allocation was about to fail because the cgroup
* reached its limit.
*/
int64_t oom;
/**
* The number of processes in this cgroup or its subtree killed by the OOM killer.
*/
int64_t oom_kill;
/**
* The number of times the entire cgroup was terminated collectively by the
* OOM group killer.
*/
int64_t oom_group_kill;
} AMemoryBudgetEvent;
/**
* Opaque handle representing an active memory event watching loop.
*
* Introduced in API 38.
*/
typedef struct AMemoryBudgetWatcher AMemoryBudgetWatcher;
/**
* User callback triggered upon encountering memory budget
* pressures. See AMemoryBudgetWatcher_create.
*
* @param event_mask Bitmask indicating which cgroup boundaries breached
* (Package vs Process). Only one of AMEMORY_BUDGET_MANAGER_EVENT_PACKAGE
* or AMEMORY_BUDGET_MANAGER_EVENT_PROCESS will be set per callback
* invocation.
* @param events Pointer to parsed, immutable snapshot capturing event sequence
* counters. Pointer is only valid for the duration of the callback.
* @param userdata Optional context pointer provided by the user during
* initialization.
*
* Introduced in API 38.
*/
typedef void (*AMemoryBudgetWatcher_onEventsCallback)(
int32_t event_mask,
const AMemoryBudgetEvent* _Nonnull event,
void* _Nullable userdata
);
/**
* Helper function to monitor memory.events. The user callback will be called
* at most once every debounce_millis MS. When done monitoring events, the user
* should call AMemoryBudgetWatcher_destroy.
*
* @param looper The looper which we will use to monitor memory.events.
* @param event_mask Combined mask of flags from AMemoryBudgetManagerWatcherEventMask.
* @param debounce_millis Minimum time window in milliseconds separating adjacent
* callback triggers. Events from different FDs are debounced
* separately. For example, if both package and process memory
* events are requested, you may receive callbacks for each of
* those events within debounce_millis but you will never
* receive a callback for the same memory event within
* debounce_millis.
* @param callback The executable function target to run on budget breaches.
* @param userdata User-supplied pointer passed back cleanly into the execution
* context.
* @return A configured context watcher instance handle, or NULL if initialization
* fails.
*
* Introduced in API 38.
*/
AMemoryBudgetWatcher* _Nullable AMemoryBudgetWatcher_create(
ALooper* _Nonnull looper,
int32_t event_mask,
uint32_t debounce_millis,
AMemoryBudgetWatcher_onEventsCallback _Nonnull callback,
void* _Nullable userdata
) __INTRODUCED_IN(38);
/**
* Halts monitoring memory.events and reclaims allocated system structures.
* This is safe to call at any time, including from AMemoryBudgetWatcher_onEventsCallback.
*
* @param watcher Non-null tracker handle returned from an earlier call to
* AMemoryBudgetWatcher_create.
*
* Introduced in API 38.
*/
void AMemoryBudgetWatcher_destroy(
AMemoryBudgetWatcher* _Nonnull watcher
) __INTRODUCED_IN(38);
/**
* Parses the contents of a memory.events file descriptor into AMemoryBudgetEvent
* structure.
*
* This function handles low-level processing for advanced engines integrated into custom
* memory.events monitoring architectures. It is not required if using
* AMemoryBudgetWatcher_create
*
* @param fd Open, readable native file descriptor bound to a cgroup v2
* memory.events target.
* @param out_event Output struct filled with parsed sequence variables upon
* success.
* @return 0 on success, -EINVAL in case of an error parsing the fd contents, or a negative error
* code mirroring standard Linux errno which can come from read(2).
*
* Introduced in API 38.
*/
int AMemoryBudgetEvent_parseEvents(
int fd,
AMemoryBudgetEvent* _Nonnull out_event
) __INTRODUCED_IN(38);
// LINT.IfChange(AMemoryBudgetResult)
/**
* Result codes for:
* - AMemoryBudgetManager_setPackageBudgetBytes,
* - AMemoryBudgetManager_setProcessBudgetBytes,
* - AMemoryBudgetManager_getPackageBudgetBytes,
* - AMemoryBudgetManager_getProcessBudgetBytes,
* - AMemoryBudgetManager_clearPackageBudget,
* - AMemoryBudgetManager_clearProcessBudget.
*
* Introduced in API 38.
*/
typedef enum AMemoryBudgetResult : int32_t {
/** Operation completed successfully. */
AMEMORY_BUDGET_RESULT_SUCCESS = 0,
/** Memory limit is disabled. */
AMEMORY_BUDGET_RESULT_LIMIT_IS_DISABLED = -1,
/** Invalid argument (e.g., negative budget value). */
AMEMORY_BUDGET_RESULT_ERROR_INVALID_ARGUMENT = -2,
/**
* Permission denied (e.g., caller doesn't have privileges, or called from an isolated
* process).
*/
AMEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED = -3,
/** The requested budget exceeds either the manifest or physical system memory limit. */
AMEMORY_BUDGET_RESULT_ERROR_EXCEEDS_LIMIT = -4,
/** Error reading the package or process budget. */
AMEMORY_BUDGET_RESULT_ERROR_READING_BUDGET = -5,
} AMemoryBudgetResult;
// LINT.ThenChange(//frameworks/base/services/core/java/com/android/server/am/MemoryBudgetManagerService.java:MemoryBudgetStatus)
/**
* Converts an {@link AMemoryBudgetResult} code to a user-readable string.
*
* @param result The result code to convert.
* @return A UTF-8 encoded static string description of the result code, or "Unknown
* AMemoryBudgetResult" if the code is unrecognized.
*
* Introduced in API 38.
*/
const char* _Nonnull AMemoryBudgetManager_resultToString(
AMemoryBudgetResult result
) __INTRODUCED_IN(38);
/**
* Sets the requested memory budget for this app package. The budget is subject
* to manifest and system limits.
*
* @param budget_bytes The requested budget in bytes
* @return an {@link AMemoryBudgetResult} indicating success or failure.
* Returns AMEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED if the calling process is
* isolated.
*
* Introduced in API 38.
*/
AMemoryBudgetResult AMemoryBudgetManager_setPackageBudgetBytes(
uint64_t budget_bytes
) __INTRODUCED_IN(38);
/**
* Sets the requested memory budget for this app process. The budget is subject
* to manifest and system limits.
*
* @param budget_bytes The requested budget in bytes
* @return an {@link AMemoryBudgetResult} indicating success or failure.
* Returns AMEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED if the calling process is
* isolated.
*
* Introduced in API 38.
*/
AMemoryBudgetResult AMemoryBudgetManager_setProcessBudgetBytes(
uint64_t budget_bytes
) __INTRODUCED_IN(38);
/**
* Gets the memory budget in bytes currently in effect for the package.
*
* @param budget_bytes Non-null pointer to which we will write the current budget.
* The value pointed to by budget_bytes is only updated if this function
* returns AMEMORY_BUDGET_RESULT_SUCCESS.
*
* @return AMEMORY_BUDGET_RESULT_SUCCESS on success, AMEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED
* when called from an isolated process or negative status on failure
* (e.g., AMEMORY_BUDGET_RESULT_LIMIT_IS_DISABLED).
*
* Introduced in API 38.
*/
AMemoryBudgetResult AMemoryBudgetManager_getPackageBudgetBytes(
uint64_t* _Nonnull budget_bytes
) __INTRODUCED_IN(38);
/**
* Gets the memory budget in bytes currently in effect for the process.
*
* @param budget_bytes Non-null pointer to which we will write the current budget.
* The value pointed to by budget_bytes is only updated if this function
* returns AMEMORY_BUDGET_RESULT_SUCCESS.
*
* @return AMEMORY_BUDGET_RESULT_SUCCESS on success, or a negative status or error
* on failure (e.g., AMEMORY_BUDGET_RESULT_LIMIT_IS_DISABLED).
*
* Introduced in API 38.
*/
AMemoryBudgetResult AMemoryBudgetManager_getProcessBudgetBytes(
uint64_t* _Nonnull budget_bytes
) __INTRODUCED_IN(38);
/**
* Clear the dynamic budget on the current package. It is not an error if there is no
* dynamic budget. Any manifest budget or system ceiling that was masked by the dynamic
* budget is resumed.
*
* @return AMEMORY_BUDGET_RESULT_SUCCESS success, or AMEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED
* when called from an isolated process.
*
* Introduced in API 38.
*/
AMemoryBudgetResult AMemoryBudgetManager_clearPackageBudget(void) __INTRODUCED_IN(38);
/**
* Clear the dynamic budget on the current process. It is not an error if there is no
* dynamic budget. Any manifest budget or system ceiling that was masked by the dynamic
* budget is resumed.
*
* @return AMEMORY_BUDGET_RESULT_SUCCESS success, or AMEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED
* when called from an isolated process.
*
* Introduced in API 38.
*/
AMemoryBudgetResult AMemoryBudgetManager_clearProcessBudget(void) __INTRODUCED_IN(38);
__END_DECLS
#endif // ANDROID_MEMORY_BUDGET_MANAGER_H