]> git.sesse.net Git - bcachefs-tools-debian/blob - include/linux/closure.h
a9de6d9334af2316e0709139f819799cd6b401eb
[bcachefs-tools-debian] / include / linux / closure.h
1 #ifndef _LINUX_CLOSURE_H
2 #define _LINUX_CLOSURE_H
3
4 #include <linux/llist.h>
5 #include <linux/sched.h>
6 #include <linux/workqueue.h>
7
8 /*
9  * Closure is perhaps the most overused and abused term in computer science, but
10  * since I've been unable to come up with anything better you're stuck with it
11  * again.
12  *
13  * What are closures?
14  *
15  * They embed a refcount. The basic idea is they count "things that are in
16  * progress" - in flight bios, some other thread that's doing something else -
17  * anything you might want to wait on.
18  *
19  * The refcount may be manipulated with closure_get() and closure_put().
20  * closure_put() is where many of the interesting things happen, when it causes
21  * the refcount to go to 0.
22  *
23  * Closures can be used to wait on things both synchronously and asynchronously,
24  * and synchronous and asynchronous use can be mixed without restriction. To
25  * wait synchronously, use closure_sync() - you will sleep until your closure's
26  * refcount hits 1.
27  *
28  * To wait asynchronously, use
29  *   continue_at(cl, next_function, workqueue);
30  *
31  * passing it, as you might expect, the function to run when nothing is pending
32  * and the workqueue to run that function out of.
33  *
34  * continue_at() also, critically, requires a 'return' immediately following the
35  * location where this macro is referenced, to return to the calling function.
36  * There's good reason for this.
37  *
38  * To use safely closures asynchronously, they must always have a refcount while
39  * they are running owned by the thread that is running them. Otherwise, suppose
40  * you submit some bios and wish to have a function run when they all complete:
41  *
42  * foo_endio(struct bio *bio)
43  * {
44  *      closure_put(cl);
45  * }
46  *
47  * closure_init(cl);
48  *
49  * do_stuff();
50  * closure_get(cl);
51  * bio1->bi_endio = foo_endio;
52  * bio_submit(bio1);
53  *
54  * do_more_stuff();
55  * closure_get(cl);
56  * bio2->bi_endio = foo_endio;
57  * bio_submit(bio2);
58  *
59  * continue_at(cl, complete_some_read, system_wq);
60  *
61  * If closure's refcount started at 0, complete_some_read() could run before the
62  * second bio was submitted - which is almost always not what you want! More
63  * importantly, it wouldn't be possible to say whether the original thread or
64  * complete_some_read()'s thread owned the closure - and whatever state it was
65  * associated with!
66  *
67  * So, closure_init() initializes a closure's refcount to 1 - and when a
68  * closure_fn is run, the refcount will be reset to 1 first.
69  *
70  * Then, the rule is - if you got the refcount with closure_get(), release it
71  * with closure_put() (i.e, in a bio->bi_endio function). If you have a refcount
72  * on a closure because you called closure_init() or you were run out of a
73  * closure - _always_ use continue_at(). Doing so consistently will help
74  * eliminate an entire class of particularly pernicious races.
75  *
76  * Lastly, you might have a wait list dedicated to a specific event, and have no
77  * need for specifying the condition - you just want to wait until someone runs
78  * closure_wake_up() on the appropriate wait list. In that case, just use
79  * closure_wait(). It will return either true or false, depending on whether the
80  * closure was already on a wait list or not - a closure can only be on one wait
81  * list at a time.
82  *
83  * Parents:
84  *
85  * closure_init() takes two arguments - it takes the closure to initialize, and
86  * a (possibly null) parent.
87  *
88  * If parent is non null, the new closure will have a refcount for its lifetime;
89  * a closure is considered to be "finished" when its refcount hits 0 and the
90  * function to run is null. Hence
91  *
92  * continue_at(cl, NULL, NULL);
93  *
94  * returns up the (spaghetti) stack of closures, precisely like normal return
95  * returns up the C stack. continue_at() with non null fn is better thought of
96  * as doing a tail call.
97  *
98  * All this implies that a closure should typically be embedded in a particular
99  * struct (which its refcount will normally control the lifetime of), and that
100  * struct can very much be thought of as a stack frame.
101  */
102
103 struct closure;
104 struct closure_syncer;
105 typedef void (closure_fn) (struct closure *);
106
107 struct closure_waitlist {
108         struct llist_head       list;
109 };
110
111 enum closure_state {
112         /*
113          * CLOSURE_WAITING: Set iff the closure is on a waitlist. Must be set by
114          * the thread that owns the closure, and cleared by the thread that's
115          * waking up the closure.
116          *
117          * The rest are for debugging and don't affect behaviour:
118          *
119          * CLOSURE_RUNNING: Set when a closure is running (i.e. by
120          * closure_init() and when closure_put() runs then next function), and
121          * must be cleared before remaining hits 0. Primarily to help guard
122          * against incorrect usage and accidentally transferring references.
123          * continue_at() and closure_return() clear it for you, if you're doing
124          * something unusual you can use closure_set_dead() which also helps
125          * annotate where references are being transferred.
126          */
127
128         CLOSURE_BITS_START      = (1U << 27),
129         CLOSURE_DESTRUCTOR      = (1U << 27),
130         CLOSURE_WAITING         = (1U << 29),
131         CLOSURE_RUNNING         = (1U << 31),
132 };
133
134 #define CLOSURE_GUARD_MASK                                      \
135         ((CLOSURE_DESTRUCTOR|CLOSURE_WAITING|CLOSURE_RUNNING) << 1)
136
137 #define CLOSURE_REMAINING_MASK          (CLOSURE_BITS_START - 1)
138 #define CLOSURE_REMAINING_INITIALIZER   (1|CLOSURE_RUNNING)
139
140 struct closure {
141         union {
142                 struct {
143                         struct workqueue_struct *wq;
144                         struct closure_syncer   *s;
145                         struct llist_node       list;
146                         closure_fn              *fn;
147                 };
148                 struct work_struct      work;
149         };
150
151         struct closure          *parent;
152
153         atomic_t                remaining;
154
155 #ifdef CONFIG_DEBUG_CLOSURES
156 #define CLOSURE_MAGIC_DEAD      0xc054dead
157 #define CLOSURE_MAGIC_ALIVE     0xc054a11e
158
159         unsigned                magic;
160         struct list_head        all;
161         unsigned long           ip;
162         unsigned long           waiting_on;
163 #endif
164 };
165
166 void closure_sub(struct closure *cl, int v);
167 void closure_put(struct closure *cl);
168 void __closure_wake_up(struct closure_waitlist *list);
169 bool closure_wait(struct closure_waitlist *list, struct closure *cl);
170 void __closure_sync(struct closure *cl);
171
172 /**
173  * closure_sync - sleep until a closure a closure has nothing left to wait on
174  *
175  * Sleeps until the refcount hits 1 - the thread that's running the closure owns
176  * the last refcount.
177  */
178 static inline void closure_sync(struct closure *cl)
179 {
180         if ((atomic_read(&cl->remaining) & CLOSURE_REMAINING_MASK) != 1)
181                 __closure_sync(cl);
182 }
183
184 #ifdef CONFIG_DEBUG_CLOSURES
185
186 void closure_debug_create(struct closure *cl);
187 void closure_debug_destroy(struct closure *cl);
188
189 #else
190
191 static inline void closure_debug_create(struct closure *cl) {}
192 static inline void closure_debug_destroy(struct closure *cl) {}
193
194 #endif
195
196 static inline void closure_set_ip(struct closure *cl)
197 {
198 #ifdef CONFIG_DEBUG_CLOSURES
199         cl->ip = _THIS_IP_;
200 #endif
201 }
202
203 static inline void closure_set_ret_ip(struct closure *cl)
204 {
205 #ifdef CONFIG_DEBUG_CLOSURES
206         cl->ip = _RET_IP_;
207 #endif
208 }
209
210 static inline void closure_set_waiting(struct closure *cl, unsigned long f)
211 {
212 #ifdef CONFIG_DEBUG_CLOSURES
213         cl->waiting_on = f;
214 #endif
215 }
216
217 static inline void closure_set_stopped(struct closure *cl)
218 {
219         atomic_sub(CLOSURE_RUNNING, &cl->remaining);
220 }
221
222 static inline void set_closure_fn(struct closure *cl, closure_fn *fn,
223                                   struct workqueue_struct *wq)
224 {
225         closure_set_ip(cl);
226         cl->fn = fn;
227         cl->wq = wq;
228         /* between atomic_dec() in closure_put() */
229         smp_mb__before_atomic();
230 }
231
232 static inline void closure_queue(struct closure *cl)
233 {
234         struct workqueue_struct *wq = cl->wq;
235
236         if (wq) {
237                 INIT_WORK(&cl->work, cl->work.func);
238                 queue_work(wq, &cl->work);
239         } else
240                 cl->fn(cl);
241 }
242
243 /**
244  * closure_get - increment a closure's refcount
245  */
246 static inline void closure_get(struct closure *cl)
247 {
248 #ifdef CONFIG_DEBUG_CLOSURES
249         BUG_ON((atomic_inc_return(&cl->remaining) &
250                 CLOSURE_REMAINING_MASK) <= 1);
251 #else
252         atomic_inc(&cl->remaining);
253 #endif
254 }
255
256 /**
257  * closure_init - Initialize a closure, setting the refcount to 1
258  * @cl:         closure to initialize
259  * @parent:     parent of the new closure. cl will take a refcount on it for its
260  *              lifetime; may be NULL.
261  */
262 static inline void closure_init(struct closure *cl, struct closure *parent)
263 {
264         cl->fn = NULL;
265         cl->parent = parent;
266         if (parent)
267                 closure_get(parent);
268
269         atomic_set(&cl->remaining, CLOSURE_REMAINING_INITIALIZER);
270
271         closure_debug_create(cl);
272         closure_set_ip(cl);
273 }
274
275 static inline void closure_init_stack(struct closure *cl)
276 {
277         memset(cl, 0, sizeof(struct closure));
278         atomic_set(&cl->remaining, CLOSURE_REMAINING_INITIALIZER);
279 }
280
281 /**
282  * closure_wake_up - wake up all closures on a wait list.
283  */
284 static inline void closure_wake_up(struct closure_waitlist *list)
285 {
286         smp_mb();
287         __closure_wake_up(list);
288 }
289
290 #define continue_at_noreturn(_cl, _fn, _wq)                             \
291 do {                                                                    \
292         set_closure_fn(_cl, _fn, _wq);                                  \
293         closure_sub(_cl, CLOSURE_RUNNING + 1);                          \
294 } while (0)
295
296 /**
297  * continue_at - jump to another function with barrier
298  *
299  * After @cl is no longer waiting on anything (i.e. all outstanding refs have
300  * been dropped with closure_put()), it will resume execution at @fn running out
301  * of @wq (or, if @wq is NULL, @fn will be called by closure_put() directly).
302  *
303  * NOTE: This macro expands to a return in the calling function!
304  *
305  * This is because after calling continue_at() you no longer have a ref on @cl,
306  * and whatever @cl owns may be freed out from under you - a running closure fn
307  * has a ref on its own closure which continue_at() drops.
308  */
309 #define continue_at(_cl, _fn, _wq)                                      \
310 do {                                                                    \
311         continue_at_noreturn(_cl, _fn, _wq);                            \
312         return;                                                         \
313 } while (0)
314
315 /**
316  * closure_return - finish execution of a closure
317  *
318  * This is used to indicate that @cl is finished: when all outstanding refs on
319  * @cl have been dropped @cl's ref on its parent closure (as passed to
320  * closure_init()) will be dropped, if one was specified - thus this can be
321  * thought of as returning to the parent closure.
322  */
323 #define closure_return(_cl)     continue_at((_cl), NULL, NULL)
324
325 /**
326  * continue_at_nobarrier - jump to another function without barrier
327  *
328  * Causes @fn to be executed out of @cl, in @wq context (or called directly if
329  * @wq is NULL).
330  *
331  * NOTE: like continue_at(), this macro expands to a return in the caller!
332  *
333  * The ref the caller of continue_at_nobarrier() had on @cl is now owned by @fn,
334  * thus it's not safe to touch anything protected by @cl after a
335  * continue_at_nobarrier().
336  */
337 #define continue_at_nobarrier(_cl, _fn, _wq)                            \
338 do {                                                                    \
339         closure_set_ip(_cl);                                            \
340         if (_wq) {                                                      \
341                 INIT_WORK(&(_cl)->work, (void *) _fn);                  \
342                 queue_work((_wq), &(_cl)->work);                        \
343         } else {                                                        \
344                 (_fn)(_cl);                                             \
345         }                                                               \
346         return;                                                         \
347 } while (0)
348
349 #define closure_return_with_destructor_noreturn(_cl, _destructor)       \
350 do {                                                                    \
351         set_closure_fn(_cl, _destructor, NULL);                         \
352         closure_sub(_cl, CLOSURE_RUNNING - CLOSURE_DESTRUCTOR + 1);     \
353 } while (0)
354
355 /**
356  * closure_return - finish execution of a closure, with destructor
357  *
358  * Works like closure_return(), except @destructor will be called when all
359  * outstanding refs on @cl have been dropped; @destructor may be used to safely
360  * free the memory occupied by @cl, and it is called with the ref on the parent
361  * closure still held - so @destructor could safely return an item to a
362  * freelist protected by @cl's parent.
363  */
364 #define closure_return_with_destructor(_cl, _destructor)                \
365 do {                                                                    \
366         closure_return_with_destructor_noreturn(_cl, _destructor);      \
367         return;                                                         \
368 } while (0)
369
370 /**
371  * closure_call - execute @fn out of a new, uninitialized closure
372  *
373  * Typically used when running out of one closure, and we want to run @fn
374  * asynchronously out of a new closure - @parent will then wait for @cl to
375  * finish.
376  */
377 static inline void closure_call(struct closure *cl, closure_fn fn,
378                                 struct workqueue_struct *wq,
379                                 struct closure *parent)
380 {
381         closure_init(cl, parent);
382         continue_at_nobarrier(cl, fn, wq);
383 }
384
385 #define __closure_wait_event(waitlist, _cond)                           \
386 do {                                                                    \
387         struct closure cl;                                              \
388                                                                         \
389         closure_init_stack(&cl);                                        \
390                                                                         \
391         while (1) {                                                     \
392                 closure_wait(waitlist, &cl);                            \
393                 if (_cond)                                              \
394                         break;                                          \
395                 closure_sync(&cl);                                      \
396         }                                                               \
397         closure_wake_up(waitlist);                                      \
398         closure_sync(&cl);                                              \
399 } while (0)
400
401 #define closure_wait_event(waitlist, _cond)                             \
402 do {                                                                    \
403         if (!(_cond))                                                   \
404                 __closure_wait_event(waitlist, _cond);                  \
405 } while (0)
406
407 #endif /* _LINUX_CLOSURE_H */