xref: /aosp_15_r20/external/cronet/net/disk_cache/blockfile/file_ios.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/disk_cache/blockfile/file.h"
6 
7 #include <limits.h>
8 #include <stdint.h>
9 
10 #include <limits>
11 #include <utility>
12 
13 #include "base/check.h"
14 #include "base/functional/bind.h"
15 #include "base/location.h"
16 #include "base/memory/raw_ptr.h"
17 #include "base/task/thread_pool.h"
18 #include "net/base/net_errors.h"
19 #include "net/disk_cache/blockfile/in_flight_io.h"
20 #include "net/disk_cache/disk_cache.h"
21 
22 namespace {
23 
24 // This class represents a single asynchronous IO operation while it is being
25 // bounced between threads.
26 class FileBackgroundIO : public disk_cache::BackgroundIO {
27  public:
28   // Other than the actual parameters for the IO operation (including the
29   // |callback| that must be notified at the end), we need the controller that
30   // is keeping track of all operations. When done, we notify the controller
31   // (we do NOT invoke the callback), in the worker thead that completed the
32   // operation.
FileBackgroundIO(disk_cache::File * file,const void * buf,size_t buf_len,size_t offset,disk_cache::FileIOCallback * callback,disk_cache::InFlightIO * controller)33   FileBackgroundIO(disk_cache::File* file, const void* buf, size_t buf_len,
34                    size_t offset, disk_cache::FileIOCallback* callback,
35                    disk_cache::InFlightIO* controller)
36       : disk_cache::BackgroundIO(controller), callback_(callback), file_(file),
37         buf_(buf), buf_len_(buf_len), offset_(offset) {
38   }
39 
40   FileBackgroundIO(const FileBackgroundIO&) = delete;
41   FileBackgroundIO& operator=(const FileBackgroundIO&) = delete;
42 
callback()43   disk_cache::FileIOCallback* callback() {
44     return callback_;
45   }
46 
file()47   disk_cache::File* file() {
48     return file_;
49   }
50 
51   // Read and Write are the operations that can be performed asynchronously.
52   // The actual parameters for the operation are setup in the constructor of
53   // the object. Both methods should be called from a worker thread, by posting
54   // a task to the WorkerPool (they are RunnableMethods). When finished,
55   // controller->OnIOComplete() is called.
56   void Read();
57   void Write();
58 
59  private:
~FileBackgroundIO()60   ~FileBackgroundIO() override {}
61 
62   raw_ptr<disk_cache::FileIOCallback> callback_;
63 
64   raw_ptr<disk_cache::File> file_;
65   raw_ptr<const void> buf_;
66   size_t buf_len_;
67   size_t offset_;
68 };
69 
70 
71 // The specialized controller that keeps track of current operations.
72 class FileInFlightIO : public disk_cache::InFlightIO {
73  public:
74   FileInFlightIO() = default;
75 
76   FileInFlightIO(const FileInFlightIO&) = delete;
77   FileInFlightIO& operator=(const FileInFlightIO&) = delete;
78 
79   ~FileInFlightIO() override = default;
80 
81   // These methods start an asynchronous operation. The arguments have the same
82   // semantics of the File asynchronous operations, with the exception that the
83   // operation never finishes synchronously.
84   void PostRead(disk_cache::File* file, void* buf, size_t buf_len,
85                 size_t offset, disk_cache::FileIOCallback* callback);
86   void PostWrite(disk_cache::File* file, const void* buf, size_t buf_len,
87                  size_t offset, disk_cache::FileIOCallback* callback);
88 
89  protected:
90   // Invokes the users' completion callback at the end of the IO operation.
91   // |cancel| is true if the actual task posted to the thread is still
92   // queued (because we are inside WaitForPendingIO), and false if said task is
93   // the one performing the call.
94   void OnOperationComplete(disk_cache::BackgroundIO* operation,
95                            bool cancel) override;
96 };
97 
98 // ---------------------------------------------------------------------------
99 
100 // Runs on a worker thread.
Read()101 void FileBackgroundIO::Read() {
102   if (file_->Read(const_cast<void*>(buf_.get()), buf_len_, offset_)) {
103     result_ = static_cast<int>(buf_len_);
104   } else {
105     result_ = net::ERR_CACHE_READ_FAILURE;
106   }
107   NotifyController();
108 }
109 
110 // Runs on a worker thread.
Write()111 void FileBackgroundIO::Write() {
112   bool rv = file_->Write(buf_, buf_len_, offset_);
113 
114   result_ = rv ? static_cast<int>(buf_len_) : net::ERR_CACHE_WRITE_FAILURE;
115   NotifyController();
116 }
117 
118 // ---------------------------------------------------------------------------
119 
PostRead(disk_cache::File * file,void * buf,size_t buf_len,size_t offset,disk_cache::FileIOCallback * callback)120 void FileInFlightIO::PostRead(disk_cache::File *file, void* buf, size_t buf_len,
121                           size_t offset, disk_cache::FileIOCallback *callback) {
122   auto operation = base::MakeRefCounted<FileBackgroundIO>(
123       file, buf, buf_len, offset, callback, this);
124   file->AddRef();  // Balanced on OnOperationComplete()
125 
126   base::ThreadPool::PostTask(
127       FROM_HERE,
128       {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
129       base::BindOnce(&FileBackgroundIO::Read, operation.get()));
130   OnOperationPosted(operation.get());
131 }
132 
PostWrite(disk_cache::File * file,const void * buf,size_t buf_len,size_t offset,disk_cache::FileIOCallback * callback)133 void FileInFlightIO::PostWrite(disk_cache::File* file, const void* buf,
134                            size_t buf_len, size_t offset,
135                            disk_cache::FileIOCallback* callback) {
136   auto operation = base::MakeRefCounted<FileBackgroundIO>(
137       file, buf, buf_len, offset, callback, this);
138   file->AddRef();  // Balanced on OnOperationComplete()
139 
140   base::ThreadPool::PostTask(
141       FROM_HERE,
142       {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
143       base::BindOnce(&FileBackgroundIO::Write, operation.get()));
144   OnOperationPosted(operation.get());
145 }
146 
147 // Runs on the IO thread.
OnOperationComplete(disk_cache::BackgroundIO * operation,bool cancel)148 void FileInFlightIO::OnOperationComplete(disk_cache::BackgroundIO* operation,
149                                          bool cancel) {
150   FileBackgroundIO* op = static_cast<FileBackgroundIO*>(operation);
151 
152   disk_cache::FileIOCallback* callback = op->callback();
153   int bytes = operation->result();
154 
155   // Release the references acquired in PostRead / PostWrite.
156   op->file()->Release();
157   callback->OnFileIOComplete(bytes);
158 }
159 
160 // A static object that will broker all async operations.
161 FileInFlightIO* s_file_operations = nullptr;
162 
163 // Returns the current FileInFlightIO.
GetFileInFlightIO()164 FileInFlightIO* GetFileInFlightIO() {
165   if (!s_file_operations) {
166     s_file_operations = new FileInFlightIO;
167   }
168   return s_file_operations;
169 }
170 
171 // Deletes the current FileInFlightIO.
DeleteFileInFlightIO()172 void DeleteFileInFlightIO() {
173   DCHECK(s_file_operations);
174   delete s_file_operations;
175   s_file_operations = nullptr;
176 }
177 
178 }  // namespace
179 
180 namespace disk_cache {
181 
File(base::File file)182 File::File(base::File file)
183     : init_(true), mixed_(true), base_file_(std::move(file)) {}
184 
Init(const base::FilePath & name)185 bool File::Init(const base::FilePath& name) {
186   if (base_file_.IsValid())
187     return false;
188 
189   int flags = base::File::FLAG_OPEN | base::File::FLAG_READ |
190               base::File::FLAG_WRITE;
191   base_file_.Initialize(name, flags);
192   return base_file_.IsValid();
193 }
194 
IsValid() const195 bool File::IsValid() const {
196   return base_file_.IsValid();
197 }
198 
Read(void * buffer,size_t buffer_len,size_t offset)199 bool File::Read(void* buffer, size_t buffer_len, size_t offset) {
200   DCHECK(base_file_.IsValid());
201   if (buffer_len > static_cast<size_t>(std::numeric_limits<int32_t>::max()) ||
202       offset > static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
203     return false;
204   }
205 
206   int ret = base_file_.Read(offset, static_cast<char*>(buffer), buffer_len);
207   return (static_cast<size_t>(ret) == buffer_len);
208 }
209 
Write(const void * buffer,size_t buffer_len,size_t offset)210 bool File::Write(const void* buffer, size_t buffer_len, size_t offset) {
211   DCHECK(base_file_.IsValid());
212   if (buffer_len > static_cast<size_t>(std::numeric_limits<int32_t>::max()) ||
213       offset > static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
214     return false;
215   }
216 
217   int ret = base_file_.Write(offset, static_cast<const char*>(buffer),
218                              buffer_len);
219   return (static_cast<size_t>(ret) == buffer_len);
220 }
221 
222 // We have to increase the ref counter of the file before performing the IO to
223 // prevent the completion to happen with an invalid handle (if the file is
224 // closed while the IO is in flight).
Read(void * buffer,size_t buffer_len,size_t offset,FileIOCallback * callback,bool * completed)225 bool File::Read(void* buffer, size_t buffer_len, size_t offset,
226                 FileIOCallback* callback, bool* completed) {
227   DCHECK(base_file_.IsValid());
228   if (!callback) {
229     if (completed)
230       *completed = true;
231     return Read(buffer, buffer_len, offset);
232   }
233 
234   if (buffer_len > ULONG_MAX || offset > ULONG_MAX)
235     return false;
236 
237   GetFileInFlightIO()->PostRead(this, buffer, buffer_len, offset, callback);
238 
239   *completed = false;
240   return true;
241 }
242 
Write(const void * buffer,size_t buffer_len,size_t offset,FileIOCallback * callback,bool * completed)243 bool File::Write(const void* buffer, size_t buffer_len, size_t offset,
244                  FileIOCallback* callback, bool* completed) {
245   DCHECK(base_file_.IsValid());
246   if (!callback) {
247     if (completed)
248       *completed = true;
249     return Write(buffer, buffer_len, offset);
250   }
251 
252   return AsyncWrite(buffer, buffer_len, offset, callback, completed);
253 }
254 
SetLength(size_t length)255 bool File::SetLength(size_t length) {
256   DCHECK(base_file_.IsValid());
257   if (length > std::numeric_limits<uint32_t>::max())
258     return false;
259 
260   return base_file_.SetLength(length);
261 }
262 
GetLength()263 size_t File::GetLength() {
264   DCHECK(base_file_.IsValid());
265   int64_t len = base_file_.GetLength();
266 
267   if (len < 0)
268     return 0;
269   if (len > static_cast<int64_t>(std::numeric_limits<uint32_t>::max()))
270     return std::numeric_limits<uint32_t>::max();
271 
272   return static_cast<size_t>(len);
273 }
274 
275 // Static.
WaitForPendingIOForTesting(int * num_pending_io)276 void File::WaitForPendingIOForTesting(int* num_pending_io) {
277   // We may be running unit tests so we should allow be able to reset the
278   // message loop.
279   GetFileInFlightIO()->WaitForPendingIO();
280   DeleteFileInFlightIO();
281 }
282 
283 // Static.
DropPendingIO()284 void File::DropPendingIO() {
285   GetFileInFlightIO()->DropPendingIO();
286   DeleteFileInFlightIO();
287 }
288 
289 File::~File() = default;
290 
platform_file() const291 base::PlatformFile File::platform_file() const {
292   return base_file_.GetPlatformFile();
293 }
294 
AsyncWrite(const void * buffer,size_t buffer_len,size_t offset,FileIOCallback * callback,bool * completed)295 bool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset,
296                       FileIOCallback* callback, bool* completed) {
297   DCHECK(base_file_.IsValid());
298   if (buffer_len > ULONG_MAX || offset > ULONG_MAX)
299     return false;
300 
301   GetFileInFlightIO()->PostWrite(this, buffer, buffer_len, offset, callback);
302 
303   if (completed)
304     *completed = false;
305   return true;
306 }
307 
308 }  // namespace disk_cache
309