#include "net/disk_cache/blockfile/in_flight_io.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_restrictions.h"
namespace disk_cache {
BackgroundIO::BackgroundIO(InFlightIO* controller)
: io_completed_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
controller_(controller) {}
void BackgroundIO::OnIOSignalled() {
if (controller_) {
did_notify_controller_io_signalled_ = true;
controller_->InvokeCallback(this, false);
}
}
void BackgroundIO::Cancel() {
base::AutoLock lock(controller_lock_);
DCHECK(controller_);
controller_ = nullptr;
}
void BackgroundIO::ClearController() {
controller_ = nullptr;
}
BackgroundIO::~BackgroundIO() = default;
InFlightIO::InFlightIO()
: callback_task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()) {
}
InFlightIO::~InFlightIO() = default;
void BackgroundIO::NotifyController() {
base::AutoLock lock(controller_lock_);
if (controller_)
controller_->OnIOComplete(this);
}
void InFlightIO::WaitForPendingIO() {
while (!io_list_.empty()) {
auto it = io_list_.begin();
InvokeCallback(it->get(), true);
}
}
void InFlightIO::DropPendingIO() {
while (!io_list_.empty()) {
auto it = io_list_.begin();
BackgroundIO* operation = it->get();
operation->Cancel();
DCHECK(io_list_.find(operation) != io_list_.end());
io_list_.erase(base::WrapRefCounted(operation));
}
}
void InFlightIO::OnIOComplete(BackgroundIO* operation) {
#if DCHECK_IS_ON()
if (callback_task_runner_->RunsTasksInCurrentSequence()) {
DCHECK(single_thread_ || !running_);
single_thread_ = true;
}
#endif
callback_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&BackgroundIO::OnIOSignalled, operation));
operation->io_completed()->Signal();
}
void InFlightIO::InvokeCallback(BackgroundIO* operation, bool cancel_task) {
{
base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
operation->io_completed()->Wait();
}
running_ = true;
if (cancel_task)
operation->Cancel();
DCHECK(io_list_.find(operation) != io_list_.end());
DCHECK(!operation->HasOneRef());
io_list_.erase(base::WrapRefCounted(operation));
OnOperationComplete(operation, cancel_task);
}
void InFlightIO::OnOperationPosted(BackgroundIO* operation) {
DCHECK(callback_task_runner_->RunsTasksInCurrentSequence());
io_list_.insert(base::WrapRefCounted(operation));
}
}