6702c53fda07ab6423c53cd3fbe80b19a3b934fe
[folly.git] / folly / experimental / io / AsyncIO.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <sys/types.h>
20 #include <libaio.h>
21
22 #include <atomic>
23 #include <cstdint>
24 #include <deque>
25 #include <functional>
26 #include <iosfwd>
27 #include <mutex>
28 #include <utility>
29 #include <vector>
30
31 #include <boost/noncopyable.hpp>
32
33 #include <folly/Portability.h>
34 #include <folly/Range.h>
35 #include <folly/portability/SysUio.h>
36
37 namespace folly {
38
39 /**
40  * An AsyncIOOp represents a pending operation.  You may set a notification
41  * callback or you may use this class's methods directly.
42  *
43  * The op must remain allocated until it is completed or canceled.
44  */
45 class AsyncIOOp : private boost::noncopyable {
46   friend class AsyncIO;
47   friend std::ostream& operator<<(std::ostream& stream, const AsyncIOOp& o);
48
49  public:
50   typedef std::function<void(AsyncIOOp*)> NotificationCallback;
51
52   explicit AsyncIOOp(NotificationCallback cb = NotificationCallback());
53   ~AsyncIOOp();
54
55   enum class State {
56     UNINITIALIZED,
57     INITIALIZED,
58     PENDING,
59     COMPLETED,
60     CANCELED,
61   };
62
63   /**
64    * Initiate a read request.
65    */
66   void pread(int fd, void* buf, size_t size, off_t start);
67   void pread(int fd, Range<unsigned char*> range, off_t start);
68   void preadv(int fd, const iovec* iov, int iovcnt, off_t start);
69
70   /**
71    * Initiate a write request.
72    */
73   void pwrite(int fd, const void* buf, size_t size, off_t start);
74   void pwrite(int fd, Range<const unsigned char*> range, off_t start);
75   void pwritev(int fd, const iovec* iov, int iovcnt, off_t start);
76
77   /**
78    * Return the current operation state.
79    */
80   State state() const { return state_; }
81
82   /**
83    * Reset the operation for reuse.  It is an error to call reset() on
84    * an Op that is still pending.
85    */
86   void reset(NotificationCallback cb = NotificationCallback());
87
88   void setNotificationCallback(NotificationCallback cb) { cb_ = std::move(cb); }
89   const NotificationCallback& notificationCallback() const { return cb_; }
90
91   /**
92    * Retrieve the result of this operation.  Returns >=0 on success,
93    * -errno on failure (that is, using the Linux kernel error reporting
94    * conventions).  Use checkKernelError (folly/Exception.h) on the result to
95    * throw a std::system_error in case of error instead.
96    *
97    * It is an error to call this if the Op hasn't completed.
98    */
99   ssize_t result() const;
100
101  private:
102   void init();
103   void start();
104   void complete(ssize_t result);
105   void cancel();
106
107   NotificationCallback cb_;
108   iocb iocb_;
109   State state_;
110   ssize_t result_;
111 };
112
113 std::ostream& operator<<(std::ostream& stream, const AsyncIOOp& o);
114 std::ostream& operator<<(std::ostream& stream, AsyncIOOp::State state);
115
116 /**
117  * C++ interface around Linux Async IO.
118  */
119 class AsyncIO : private boost::noncopyable {
120  public:
121   typedef AsyncIOOp Op;
122
123   enum PollMode {
124     NOT_POLLABLE,
125     POLLABLE,
126   };
127
128   /**
129    * Create an AsyncIO context capable of holding at most 'capacity' pending
130    * requests at the same time.  As requests complete, others can be scheduled,
131    * as long as this limit is not exceeded.
132    *
133    * Note: the maximum number of allowed concurrent requests is controlled
134    * by the fs.aio-max-nr sysctl, the default value is usually 64K.
135    *
136    * If pollMode is POLLABLE, pollFd() will return a file descriptor that
137    * can be passed to poll / epoll / select and will become readable when
138    * any IOs on this AsyncIO have completed.  If you do this, you must use
139    * pollCompleted() instead of wait() -- do not read from the pollFd()
140    * file descriptor directly.
141    *
142    * You may use the same AsyncIO object from multiple threads, as long as
143    * there is only one concurrent caller of wait() / pollCompleted() / cancel()
144    * (perhaps by always calling it from the same thread, or by providing
145    * appropriate mutual exclusion).  In this case, pending() returns a snapshot
146    * of the current number of pending requests.
147    */
148   explicit AsyncIO(size_t capacity, PollMode pollMode = NOT_POLLABLE);
149   ~AsyncIO();
150
151   /**
152    * Wait for at least minRequests to complete.  Returns the requests that
153    * have completed; the returned range is valid until the next call to
154    * wait().  minRequests may be 0 to not block.
155    */
156   Range<Op**> wait(size_t minRequests);
157
158   /**
159    * Cancel all pending requests and return their number.
160    */
161   size_t cancel();
162
163   /**
164    * Return the number of pending requests.
165    */
166   size_t pending() const { return pending_; }
167
168   /**
169    * Return the maximum number of requests that can be kept outstanding
170    * at any one time.
171    */
172   size_t capacity() const { return capacity_; }
173
174   /**
175    * Return the accumulative number of submitted I/O, since this object
176    * has been created.
177    */
178   size_t totalSubmits() const { return submitted_; }
179
180   /**
181    * If POLLABLE, return a file descriptor that can be passed to poll / epoll
182    * and will become readable when any async IO operations have completed.
183    * If NOT_POLLABLE, return -1.
184    */
185   int pollFd() const { return pollFd_; }
186
187   /**
188    * If POLLABLE, call instead of wait after the file descriptor returned
189    * by pollFd() became readable.  The returned range is valid until the next
190    * call to pollCompleted().
191    */
192   Range<Op**> pollCompleted();
193
194   /**
195    * Submit an op for execution.
196    */
197   void submit(Op* op);
198
199  private:
200   void decrementPending();
201   void initializeContext();
202
203   enum class WaitType { COMPLETE, CANCEL };
204   void doWait(
205       WaitType type,
206       size_t minRequests,
207       size_t maxRequests,
208       std::vector<Op*>* result);
209
210   io_context_t ctx_{nullptr};
211   std::atomic<bool> ctxSet_{false};
212   std::mutex initMutex_;
213
214   std::atomic<size_t> pending_{0};
215   std::atomic<size_t> submitted_{0};
216   const size_t capacity_;
217   int pollFd_{-1};
218   std::vector<Op*> completed_;
219 };
220
221 /**
222  * Wrapper around AsyncIO that allows you to schedule more requests than
223  * the AsyncIO's object capacity.  Other requests are queued and processed
224  * in a FIFO order.
225  */
226 class AsyncIOQueue {
227  public:
228   /**
229    * Create a queue, using the given AsyncIO object.
230    * The AsyncIO object may not be used by anything else until the
231    * queue is destroyed.
232    */
233   explicit AsyncIOQueue(AsyncIO* asyncIO);
234   ~AsyncIOQueue();
235
236   size_t queued() const { return queue_.size(); }
237
238   /**
239    * Submit an op to the AsyncIO queue.  The op will be queued until
240    * the AsyncIO object has room.
241    */
242   void submit(AsyncIOOp* op);
243
244   /**
245    * Submit a delayed op to the AsyncIO queue; this allows you to postpone
246    * creation of the Op (which may require allocating memory, etc) until
247    * the AsyncIO object has room.
248    */
249   typedef std::function<AsyncIOOp*()> OpFactory;
250   void submit(OpFactory op);
251
252  private:
253   void onCompleted(AsyncIOOp* op);
254   void maybeDequeue();
255
256   AsyncIO* asyncIO_;
257
258   std::deque<OpFactory> queue_;
259 };
260
261 }  // namespace folly