Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/webgpu/android/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ add_library(${PACKAGE_NAME} SHARED
../cpp/rnwgpu/api/GPUComputePipeline.cpp
../cpp/rnwgpu/api/GPUCanvasContext.cpp
../cpp/rnwgpu/DawnBlobCache.cpp
../cpp/rnwgpu/GpuPurge.cpp
../cpp/rnwgpu/NativeBufferViewRegistry.cpp
../cpp/rnwgpu/AnimationFrames.cpp
../cpp/rnwgpu/RNWebGPUManager.cpp
Expand Down
16 changes: 16 additions & 0 deletions packages/webgpu/android/cpp/cpp-adapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "DawnBlobCache.h"
#include "GPUCanvasContext.h"
#include "GPUDevice.h"
#include "GpuPurge.h"
#include "NativeBufferViewRegistry.h"
#include "RNWebGPUManager.h"
#include "WebGPURuntime.h"
Expand Down Expand Up @@ -70,6 +71,21 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */,
rnwgpu::GPUDevice::flushPipelineCaches();
}

// WebGPUModule's ComponentCallbacks2 (UI thread): what the system says about
// memory, as it says it. GpuPurge decides what calls for a purge.
extern "C" JNIEXPORT void JNICALL
Java_com_webgpu_WebGPUModule_onLowMemoryNative(JNIEnv * /* env */,
jclass /* clazz */) {
rnwgpu::GpuPurge::onLowMemory();
}

extern "C" JNIEXPORT void JNICALL
Java_com_webgpu_WebGPUModule_onTrimMemoryNative(JNIEnv * /* env */,
jclass /* clazz */,
jint level) {
rnwgpu::GpuPurge::onTrimMemory(level);
}

// WebGPUModule.onHostResume and onHostPause (UI thread): animation frames
// follow the host activity, resumed or not.
extern "C" JNIEXPORT void JNICALL
Expand Down
31 changes: 31 additions & 0 deletions packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.webgpu;

import android.content.ComponentCallbacks2;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.hardware.HardwareBuffer;
import android.os.Build;
Expand Down Expand Up @@ -34,18 +36,41 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
System.loadLibrary("react-native-webgpu"); // Load the C++ library
}

// What the system says about memory goes to the native side as it comes,
// which decides when the GPU memory nothing uses goes back to the system
// (see GpuPurge).
private final ComponentCallbacks2 mComponentCallbacks =
new ComponentCallbacks2() {
@Override
public void onConfigurationChanged(Configuration newConfig) {}

@Override
public void onLowMemory() {
onLowMemoryNative();
}

@Override
public void onTrimMemory(int level) {
onTrimMemoryNative(level);
}
};

public WebGPUModule(ReactApplicationContext reactContext) {
super(reactContext);
// Initialize the C++ module
initialize();
// Animation frames follow the host activity: resumed, or not.
setForegroundNative(reactContext.getLifecycleState() == LifecycleState.RESUMED);
reactContext.addLifecycleEventListener(this);
reactContext.getApplicationContext().registerComponentCallbacks(mComponentCallbacks);
}

@Override
public void invalidate() {
getReactApplicationContext().removeLifecycleEventListener(this);
getReactApplicationContext()
.getApplicationContext()
.unregisterComponentCallbacks(mComponentCallbacks);
super.invalidate();
}

Expand All @@ -72,6 +97,12 @@ public void onHostDestroy() {}
@DoNotStrip
private native void flushPipelineCaches();

@DoNotStrip
private static native void onLowMemoryNative();

@DoNotStrip
private static native void onTrimMemoryNative(int level);

/**
* Whether the app is in the foreground: the host activity is resumed (see
* AnimationFrameDispatcher::setForeground). An AChoreographer sends its
Expand Down
22 changes: 22 additions & 0 deletions packages/webgpu/apple/WebGPUModule.mm
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "ApplePlatformContext.h"
#include "DawnBlobCache.h"
#import "GPUCanvasContext.h"
#include "GpuPurge.h"
#import "RNWGUIKit.h"

#import <React/RCTBridge+Private.h>
Expand All @@ -22,6 +23,24 @@ @interface RCTBridge (JSIRuntime)
- (void *)runtime;
@end

#if !TARGET_OS_OSX
// A memory warning goes to the native side as it comes, which decides when the
// GPU memory nothing uses goes back to the system (see GpuPurge). Once for the
// process: devices outlive a React reload.
static void observeMemoryWarnings() {
static dispatch_once_t once;
dispatch_once(&once, ^{
[[NSNotificationCenter defaultCenter]
addObserverForName:UIApplicationDidReceiveMemoryWarningNotification
object:nil
queue:nil
usingBlock:^(NSNotification *) {
rnwgpu::GpuPurge::onMemoryWarning();
}];
});
}
#endif

@implementation WebGPUModule

RCT_EXPORT_MODULE(WebGPUModule)
Expand Down Expand Up @@ -149,6 +168,9 @@ - (void)invalidate {
rnwgpu::DawnBlobCache::setDirectory(
[caches stringByAppendingPathComponent:@"webgpu-dawn"].UTF8String);
}
#if !TARGET_OS_OSX
observeMemoryWarnings();
#endif
webgpuManager = std::make_shared<rnwgpu::RNWebGPUManager>(runtime, jsInvoker,
platformContext);
return @true;
Expand Down
86 changes: 86 additions & 0 deletions packages/webgpu/cpp/rnwgpu/GpuPurge.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#include "GpuPurge.h"

#include <mutex>
#include <system_error>
#include <thread>

#include "GPUDevice.h"

namespace rnwgpu {

namespace {

struct State {
std::mutex mutex;
// Whether the purge thread is alive.
bool running = false;
// Whether a request came in since the thread last started a run.
bool requested = false;
};

// Never destroyed: the purge thread may still use it while the process exits.
State &getState() noexcept {
static auto *state = new State();
return *state;
}

} // namespace

void GpuPurge::request() noexcept {
auto &state = getState();
{
std::lock_guard<std::mutex> lock(state.mutex);
state.requested = true;
if (state.running) {
return;
}
state.running = true;
}
try {
std::thread([] { runRequests(); }).detach();
} catch (const std::system_error &) {
// No thread to be had: nothing is purged.
std::lock_guard<std::mutex> lock(state.mutex);
state.running = false;
}
}

void GpuPurge::onMemoryWarning() noexcept { request(); }

void GpuPurge::onLowMemory() noexcept { request(); }

void GpuPurge::onTrimMemory(int level) noexcept {
if (level >= kTrimMemoryUiHidden) {
request();
}
}

void GpuPurge::runRequests() noexcept {
auto &state = getState();
for (;;) {
{
std::lock_guard<std::mutex> lock(state.mutex);
if (!state.requested) {
state.running = false;
return;
}
state.requested = false;
}
run();
}
}

void GpuPurge::run() {
for (int pass = 0; pass < kMaxPasses; pass++) {
bool pending = GPUDevice::reduceMemoryUsage();
if (pass < kRuntimeThreadPasses) {
pending |= GPUDevice::reduceMemoryUsageOnRuntimeThreads();
}
if (!pending) {
return;
}
std::this_thread::sleep_for(kPassInterval);
}
}

} // namespace rnwgpu
66 changes: 66 additions & 0 deletions packages/webgpu/cpp/rnwgpu/GpuPurge.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#pragma once

#include <chrono>

namespace rnwgpu {

// purgeGpuResources(), which the system also brings about when it is short of
// memory and, on Android, when the app goes to the background: Dawn gives the
// GPU memory it keeps for reuse (the memory of destroyed textures and buffers,
// staging memory) back to the system, for every live device (see
// GPUDevice::reduceMemoryUsage). Nothing alive is affected.
//
// The platform modules only report what the system said (onMemoryWarning,
// onLowMemory, onTrimMemory): whether it calls for a purge is decided here.
//
// request() returns at once. The work runs on a thread of its own, started by
// a request and gone once done; a request made while it runs is served by one
// more run of the same thread, however many came in.
class GpuPurge {
public:
// purgeGpuResources() from JS. Any thread.
static void request() noexcept;

// iOS, UIApplicationDidReceiveMemoryWarningNotification: the system is short
// of memory, and ends the apps that hold the most of it first. Any thread.
static void onMemoryWarning() noexcept;

// Android, ComponentCallbacks.onLowMemory(): the whole system is short of
// memory. Any thread.
static void onLowMemory() noexcept;

// Android, ComponentCallbacks2.onTrimMemory(): purges from
// kTrimMemoryUiHidden, which is each time the app goes to the background.
// Any thread.
static void onTrimMemory(int level) noexcept;

private:
// One run asks Dawn again for as long as it says deletions wait for
// submitted work to complete, this many times at most and this far apart:
// about a second in all.
static constexpr int kMaxPasses = 10;
static constexpr std::chrono::milliseconds kPassInterval{100};

// The passes of a run that also ask the devices only the thread of their
// runtime may use (see GPUDevice::reduceMemoryUsageOnRuntimeThreads). What
// Dawn answers there is not waited for, hence a fixed number: the first lets
// the pending deletions go through, the next free what they leave.
static constexpr int kRuntimeThreadPasses = 3;

// ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN: the app is no longer visible. It
// renders nothing there, and the system ends the processes in the background
// that hold the most memory first. The system sends it each time the app
// leaves the foreground, and it may be all it sends: TRIM_MEMORY_BACKGROUND
// did not come to an app left in the background until it was cached and
// frozen (a Samsung on Android 17). The levels below this one are for an app
// in the foreground, and are no longer sent since Android 14.
static constexpr int kTrimMemoryUiHidden = 20;

// The purge thread: runs until no request is left.
static void runRequests() noexcept;

// One run: the passes over the live devices.
static void run();
};

} // namespace rnwgpu
Loading
Loading