blob: 0e0593416f93a595a4f197ccae32cbec79522825 [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_STORAGE_LIB_BACKGROUND_LOOP_BACKGROUND_LOOP_H_
#define SRC_STORAGE_LIB_BACKGROUND_LOOP_BACKGROUND_LOOP_H_
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/loop.h>
#include <lib/async/dispatcher.h>
#include <atomic>
#include <string_view>
#include <thread>
namespace storage {
// Runs an `async::Loop` on a dedicated background `std::thread` and ensures that the loop is
// always shut down on that background thread rather than on the caller's thread.
//
// Why this class exists instead of using `async::Loop` directly:
//
// 1. Off-thread `async::Loop::Shutdown()` / `~Loop()` races with in-flight handlers:
// `async_loop_shutdown()` sets the loop state to `ASYNC_LOOP_SHUTDOWN` *before* waking and
// joining worker threads started with `StartThread()`. Any code concurrently executing on the
// worker thread (for example, a FIDL request handler calling `fidl::BindServer()` or
// `async::PostTask()`) immediately receives `ZX_ERR_BAD_STATE`, which causes
// `fidl::BindServer()` to `ZX_PANIC`.
//
// 2. Posting `loop.Shutdown()` onto a `StartThread()` thread deadlocks:
// `StartThread()` records the worker thread in the loop's internal thread list, and
// `async_loop_shutdown()` calls `thrd_join()` on every thread in that list. Calling `Shutdown()`
// from a thread created by `StartThread()` attempts to join itself and deadlocks (or trips a
// debug assertion).
//
// 3. `StartThread()` + `PostTask(Quit)` + `JoinThreads()` cancels remaining work on the wrong
// thread:
// Quitting and joining the worker thread avoids concurrent execution during
// `ASYNC_LOOP_SHUTDOWN`, but `async::Loop::Quit()` does not transition the loop to
// `ASYNC_LOOP_SHUTDOWN`, so the worker thread exits without calling `async_loop_cancel_all()`.
// When `~Loop()` subsequently runs on the caller's thread, `async_loop_shutdown()` invokes
// cancellation callbacks (and any destructors they trigger, such as FIDL unbind handlers) on the
// caller's thread instead of the dispatcher's thread, and without the loop's default dispatcher
// set.
//
// Why this class constructs its own `std::thread`:
//
// By spawning our own `std::thread` instead of calling `async::Loop::StartThread()`, the loop's
// internal thread list remains empty. The background thread sets itself as the default dispatcher,
// runs `loop_.Run()`, and immediately calls `loop_.Shutdown()` once `Run()` returns. Calling
// `BackgroundLoop::Shutdown()` (or destroying the `BackgroundLoop`) posts `loop_.Quit()` to the
// loop and joins the `std::thread`. This guarantees that:
// - No handler runs concurrently with `ASYNC_LOOP_SHUTDOWN`, because `loop_.Run()` has already
// returned before `loop_.Shutdown()` is called.
// - `loop_.Shutdown()` does not self-join, because `StartThread()` was never called.
// - `async_loop_cancel_all()` executes on the background thread itself while
// `async_get_default_dispatcher() == dispatcher()`.
// - `~Loop()` on the owner's thread is a no-op because the loop is already shut down.
//
// Lifetime and destruction ordering:
//
// Any object that posts cleanup tasks to `dispatcher()` in its destructor (for example,
// `fs::SynchronousVfs` or `trace::TraceProviderWithFdio`) must be destroyed before `Shutdown()`
// runs. Conversely, any object accessed by callbacks running on the background thread must outlive
// `Shutdown()`.
class BackgroundLoop {
public:
// Creates an `async::Loop` and starts a background `std::thread` running it. If `thread_name` is
// non-empty, sets `ZX_PROP_NAME` on the background thread. Construction is infallible: under
// `-fno-exceptions`, failing to spawn the background thread aborts the process.
explicit BackgroundLoop(std::string_view thread_name = {});
BackgroundLoop(const BackgroundLoop&) = delete;
BackgroundLoop& operator=(const BackgroundLoop&) = delete;
BackgroundLoop(BackgroundLoop&&) = delete;
BackgroundLoop& operator=(BackgroundLoop&&) = delete;
// Shuts down the loop on the background thread and joins it if not already shut down.
~BackgroundLoop();
// Posts `Quit()` to the background thread and joins it. Once `Run()` exits, the background thread
// calls `loop_.Shutdown()` (canceling any remaining pending waits/tasks on the background thread)
// before exiting.
//
// Safe to call multiple times, and safe even if `Quit()` was already called from the background
// thread. Must not be called from the background thread itself or concurrently from multiple
// threads.
void Shutdown();
// Signals the loop to exit `Run()` and proceed to `loop_.Shutdown()` on the background thread.
// Must only be called from a task/handler running on the background thread itself.
void Quit();
async_dispatcher_t* dispatcher() const { return loop_.dispatcher(); }
private:
async::Loop loop_{&kAsyncLoopConfigNeverAttachToThread};
// Stored separately from `thread_` because `Quit()` runs on the background thread concurrently
// with `thread_.join()` in `Shutdown()`, and `std::thread::get_id()` is not safe to call
// concurrently with the non-const `std::thread::join()`.
std::atomic<std::thread::id> worker_tid_;
std::thread thread_;
};
} // namespace storage
#endif // SRC_STORAGE_LIB_BACKGROUND_LOOP_BACKGROUND_LOOP_H_