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