aio: strengthen memory barriers for bottom half scheduling
[sdk/emulator/qemu.git] / async.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24
25 #include "qemu-common.h"
26 #include "block/aio.h"
27 #include "block/thread-pool.h"
28 #include "qemu/main-loop.h"
29 #include "qemu/atomic.h"
30
31 /***********************************************************/
32 /* bottom halves (can be seen as timers which expire ASAP) */
33
34 struct QEMUBH {
35     AioContext *ctx;
36     QEMUBHFunc *cb;
37     void *opaque;
38     QEMUBH *next;
39     bool scheduled;
40     bool idle;
41     bool deleted;
42 };
43
44 QEMUBH *aio_bh_new(AioContext *ctx, QEMUBHFunc *cb, void *opaque)
45 {
46     QEMUBH *bh;
47     bh = g_new(QEMUBH, 1);
48     *bh = (QEMUBH){
49         .ctx = ctx,
50         .cb = cb,
51         .opaque = opaque,
52     };
53     qemu_mutex_lock(&ctx->bh_lock);
54     bh->next = ctx->first_bh;
55     /* Make sure that the members are ready before putting bh into list */
56     smp_wmb();
57     ctx->first_bh = bh;
58     qemu_mutex_unlock(&ctx->bh_lock);
59     return bh;
60 }
61
62 /* Multiple occurrences of aio_bh_poll cannot be called concurrently */
63 int aio_bh_poll(AioContext *ctx)
64 {
65     QEMUBH *bh, **bhp, *next;
66     int ret;
67
68     ctx->walking_bh++;
69
70     ret = 0;
71     for (bh = ctx->first_bh; bh; bh = next) {
72         /* Make sure that fetching bh happens before accessing its members */
73         smp_read_barrier_depends();
74         next = bh->next;
75         /* The atomic_xchg is paired with the one in qemu_bh_schedule.  The
76          * implicit memory barrier ensures that the callback sees all writes
77          * done by the scheduling thread.  It also ensures that the scheduling
78          * thread sees the zero before bh->cb has run, and thus will call
79          * aio_notify again if necessary.
80          */
81         if (!bh->deleted && atomic_xchg(&bh->scheduled, 0)) {
82             if (!bh->idle)
83                 ret = 1;
84             bh->idle = 0;
85             bh->cb(bh->opaque);
86         }
87     }
88
89     ctx->walking_bh--;
90
91     /* remove deleted bhs */
92     if (!ctx->walking_bh) {
93         qemu_mutex_lock(&ctx->bh_lock);
94         bhp = &ctx->first_bh;
95         while (*bhp) {
96             bh = *bhp;
97             if (bh->deleted) {
98                 *bhp = bh->next;
99                 g_free(bh);
100             } else {
101                 bhp = &bh->next;
102             }
103         }
104         qemu_mutex_unlock(&ctx->bh_lock);
105     }
106
107     return ret;
108 }
109
110 void qemu_bh_schedule_idle(QEMUBH *bh)
111 {
112     bh->idle = 1;
113     /* Make sure that idle & any writes needed by the callback are done
114      * before the locations are read in the aio_bh_poll.
115      */
116     atomic_mb_set(&bh->scheduled, 1);
117 }
118
119 void qemu_bh_schedule(QEMUBH *bh)
120 {
121     AioContext *ctx;
122
123     ctx = bh->ctx;
124     bh->idle = 0;
125     /* The memory barrier implicit in atomic_xchg makes sure that:
126      * 1. idle & any writes needed by the callback are done before the
127      *    locations are read in the aio_bh_poll.
128      * 2. ctx is loaded before scheduled is set and the callback has a chance
129      *    to execute.
130      */
131     if (atomic_xchg(&bh->scheduled, 1) == 0) {
132         aio_notify(ctx);
133     }
134 }
135
136
137 /* This func is async.
138  */
139 void qemu_bh_cancel(QEMUBH *bh)
140 {
141     bh->scheduled = 0;
142 }
143
144 /* This func is async.The bottom half will do the delete action at the finial
145  * end.
146  */
147 void qemu_bh_delete(QEMUBH *bh)
148 {
149     bh->scheduled = 0;
150     bh->deleted = 1;
151 }
152
153 int64_t
154 aio_compute_timeout(AioContext *ctx)
155 {
156     int64_t deadline;
157     int timeout = -1;
158     QEMUBH *bh;
159
160     for (bh = ctx->first_bh; bh; bh = bh->next) {
161         if (!bh->deleted && bh->scheduled) {
162             if (bh->idle) {
163                 /* idle bottom halves will be polled at least
164                  * every 10ms */
165                 timeout = 10000000;
166             } else {
167                 /* non-idle bottom halves will be executed
168                  * immediately */
169                 return 0;
170             }
171         }
172     }
173
174     deadline = timerlistgroup_deadline_ns(&ctx->tlg);
175     if (deadline == 0) {
176         return 0;
177     } else {
178         return qemu_soonest_timeout(timeout, deadline);
179     }
180 }
181
182 static gboolean
183 aio_ctx_prepare(GSource *source, gint    *timeout)
184 {
185     AioContext *ctx = (AioContext *) source;
186
187     /* We assume there is no timeout already supplied */
188     *timeout = qemu_timeout_ns_to_ms(aio_compute_timeout(ctx));
189
190     if (aio_prepare(ctx)) {
191         *timeout = 0;
192     }
193
194     return *timeout == 0;
195 }
196
197 static gboolean
198 aio_ctx_check(GSource *source)
199 {
200     AioContext *ctx = (AioContext *) source;
201     QEMUBH *bh;
202
203     for (bh = ctx->first_bh; bh; bh = bh->next) {
204         if (!bh->deleted && bh->scheduled) {
205             return true;
206         }
207     }
208     return aio_pending(ctx) || (timerlistgroup_deadline_ns(&ctx->tlg) == 0);
209 }
210
211 static gboolean
212 aio_ctx_dispatch(GSource     *source,
213                  GSourceFunc  callback,
214                  gpointer     user_data)
215 {
216     AioContext *ctx = (AioContext *) source;
217
218     assert(callback == NULL);
219     aio_dispatch(ctx);
220     return true;
221 }
222
223 static void
224 aio_ctx_finalize(GSource     *source)
225 {
226     AioContext *ctx = (AioContext *) source;
227
228     thread_pool_free(ctx->thread_pool);
229     aio_set_event_notifier(ctx, &ctx->notifier, NULL);
230     event_notifier_cleanup(&ctx->notifier);
231     rfifolock_destroy(&ctx->lock);
232     qemu_mutex_destroy(&ctx->bh_lock);
233     g_array_free(ctx->pollfds, TRUE);
234     timerlistgroup_deinit(&ctx->tlg);
235 }
236
237 static GSourceFuncs aio_source_funcs = {
238     aio_ctx_prepare,
239     aio_ctx_check,
240     aio_ctx_dispatch,
241     aio_ctx_finalize
242 };
243
244 GSource *aio_get_g_source(AioContext *ctx)
245 {
246     g_source_ref(&ctx->source);
247     return &ctx->source;
248 }
249
250 ThreadPool *aio_get_thread_pool(AioContext *ctx)
251 {
252     if (!ctx->thread_pool) {
253         ctx->thread_pool = thread_pool_new(ctx);
254     }
255     return ctx->thread_pool;
256 }
257
258 void aio_set_dispatching(AioContext *ctx, bool dispatching)
259 {
260     ctx->dispatching = dispatching;
261     if (!dispatching) {
262         /* Write ctx->dispatching before reading e.g. bh->scheduled.
263          * Optimization: this is only needed when we're entering the "unsafe"
264          * phase where other threads must call event_notifier_set.
265          */
266         smp_mb();
267     }
268 }
269
270 void aio_notify(AioContext *ctx)
271 {
272     /* Write e.g. bh->scheduled before reading ctx->dispatching.  */
273     smp_mb();
274     if (!ctx->dispatching) {
275         event_notifier_set(&ctx->notifier);
276     }
277 }
278
279 static void aio_timerlist_notify(void *opaque)
280 {
281     aio_notify(opaque);
282 }
283
284 static void aio_rfifolock_cb(void *opaque)
285 {
286     /* Kick owner thread in case they are blocked in aio_poll() */
287     aio_notify(opaque);
288 }
289
290 AioContext *aio_context_new(Error **errp)
291 {
292     int ret;
293     AioContext *ctx;
294     ctx = (AioContext *) g_source_new(&aio_source_funcs, sizeof(AioContext));
295     ret = event_notifier_init(&ctx->notifier, false);
296     if (ret < 0) {
297         g_source_destroy(&ctx->source);
298         error_setg_errno(errp, -ret, "Failed to initialize event notifier");
299         return NULL;
300     }
301     g_source_set_can_recurse(&ctx->source, true);
302     aio_set_event_notifier(ctx, &ctx->notifier,
303                            (EventNotifierHandler *)
304                            event_notifier_test_and_clear);
305     ctx->pollfds = g_array_new(FALSE, FALSE, sizeof(GPollFD));
306     ctx->thread_pool = NULL;
307     qemu_mutex_init(&ctx->bh_lock);
308     rfifolock_init(&ctx->lock, aio_rfifolock_cb, ctx);
309     timerlistgroup_init(&ctx->tlg, aio_timerlist_notify, ctx);
310
311     return ctx;
312 }
313
314 void aio_context_ref(AioContext *ctx)
315 {
316     g_source_ref(&ctx->source);
317 }
318
319 void aio_context_unref(AioContext *ctx)
320 {
321     g_source_unref(&ctx->source);
322 }
323
324 void aio_context_acquire(AioContext *ctx)
325 {
326     rfifolock_lock(&ctx->lock);
327 }
328
329 void aio_context_release(AioContext *ctx)
330 {
331     rfifolock_unlock(&ctx->lock);
332 }