blob: d29b773b863f5b359c4327765deb2341b6d3b070 [file] [log] [blame]
Kent Overstreetcafe5632013-03-23 16:11:31 -07001#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, is a macro that returns the calling function.
35 * There's good reason for this.
36 *
37 * To use safely closures asynchronously, they must always have a refcount while
38 * they are running owned by the thread that is running them. Otherwise, suppose
39 * you submit some bios and wish to have a function run when they all complete:
40 *
41 * foo_endio(struct bio *bio, int error)
42 * {
43 * closure_put(cl);
44 * }
45 *
46 * closure_init(cl);
47 *
48 * do_stuff();
49 * closure_get(cl);
50 * bio1->bi_endio = foo_endio;
51 * bio_submit(bio1);
52 *
53 * do_more_stuff();
54 * closure_get(cl);
55 * bio2->bi_endio = foo_endio;
56 * bio_submit(bio2);
57 *
58 * continue_at(cl, complete_some_read, system_wq);
59 *
60 * If closure's refcount started at 0, complete_some_read() could run before the
61 * second bio was submitted - which is almost always not what you want! More
62 * importantly, it wouldn't be possible to say whether the original thread or
63 * complete_some_read()'s thread owned the closure - and whatever state it was
64 * associated with!
65 *
66 * So, closure_init() initializes a closure's refcount to 1 - and when a
67 * closure_fn is run, the refcount will be reset to 1 first.
68 *
69 * Then, the rule is - if you got the refcount with closure_get(), release it
70 * with closure_put() (i.e, in a bio->bi_endio function). If you have a refcount
71 * on a closure because you called closure_init() or you were run out of a
72 * closure - _always_ use continue_at(). Doing so consistently will help
73 * eliminate an entire class of particularly pernicious races.
74 *
75 * For a closure to wait on an arbitrary event, we need to introduce waitlists:
76 *
77 * struct closure_waitlist list;
78 * closure_wait_event(list, cl, condition);
79 * closure_wake_up(wait_list);
80 *
81 * These work analagously to wait_event() and wake_up() - except that instead of
82 * operating on the current thread (for wait_event()) and lists of threads, they
83 * operate on an explicit closure and lists of closures.
84 *
85 * Because it's a closure we can now wait either synchronously or
86 * asynchronously. closure_wait_event() returns the current value of the
87 * condition, and if it returned false continue_at() or closure_sync() can be
88 * used to wait for it to become true.
89 *
90 * It's useful for waiting on things when you can't sleep in the context in
91 * which you must check the condition (perhaps a spinlock held, or you might be
92 * beneath generic_make_request() - in which case you can't sleep on IO).
93 *
94 * closure_wait_event() will wait either synchronously or asynchronously,
95 * depending on whether the closure is in blocking mode or not. You can pick a
96 * mode explicitly with closure_wait_event_sync() and
97 * closure_wait_event_async(), which do just what you might expect.
98 *
99 * Lastly, you might have a wait list dedicated to a specific event, and have no
100 * need for specifying the condition - you just want to wait until someone runs
101 * closure_wake_up() on the appropriate wait list. In that case, just use
102 * closure_wait(). It will return either true or false, depending on whether the
103 * closure was already on a wait list or not - a closure can only be on one wait
104 * list at a time.
105 *
106 * Parents:
107 *
108 * closure_init() takes two arguments - it takes the closure to initialize, and
109 * a (possibly null) parent.
110 *
111 * If parent is non null, the new closure will have a refcount for its lifetime;
112 * a closure is considered to be "finished" when its refcount hits 0 and the
113 * function to run is null. Hence
114 *
115 * continue_at(cl, NULL, NULL);
116 *
117 * returns up the (spaghetti) stack of closures, precisely like normal return
118 * returns up the C stack. continue_at() with non null fn is better thought of
119 * as doing a tail call.
120 *
121 * All this implies that a closure should typically be embedded in a particular
122 * struct (which its refcount will normally control the lifetime of), and that
123 * struct can very much be thought of as a stack frame.
124 *
125 * Locking:
126 *
127 * Closures are based on work items but they can be thought of as more like
128 * threads - in that like threads and unlike work items they have a well
129 * defined lifetime; they are created (with closure_init()) and eventually
130 * complete after a continue_at(cl, NULL, NULL).
131 *
132 * Suppose you've got some larger structure with a closure embedded in it that's
133 * used for periodically doing garbage collection. You only want one garbage
134 * collection happening at a time, so the natural thing to do is protect it with
135 * a lock. However, it's difficult to use a lock protecting a closure correctly
136 * because the unlock should come after the last continue_to() (additionally, if
137 * you're using the closure asynchronously a mutex won't work since a mutex has
138 * to be unlocked by the same process that locked it).
139 *
140 * So to make it less error prone and more efficient, we also have the ability
141 * to use closures as locks:
142 *
143 * closure_init_unlocked();
144 * closure_trylock();
145 *
146 * That's all we need for trylock() - the last closure_put() implicitly unlocks
147 * it for you. But for closure_lock(), we also need a wait list:
148 *
149 * struct closure_with_waitlist frobnicator_cl;
150 *
151 * closure_init_unlocked(&frobnicator_cl);
152 * closure_lock(&frobnicator_cl);
153 *
154 * A closure_with_waitlist embeds a closure and a wait list - much like struct
155 * delayed_work embeds a work item and a timer_list. The important thing is, use
156 * it exactly like you would a regular closure and closure_put() will magically
157 * handle everything for you.
Kent Overstreetcafe5632013-03-23 16:11:31 -0700158 */
159
160struct closure;
161typedef void (closure_fn) (struct closure *);
162
163struct closure_waitlist {
164 struct llist_head list;
165};
166
167enum closure_type {
168 TYPE_closure = 0,
169 TYPE_closure_with_waitlist = 1,
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700170 MAX_CLOSURE_TYPE = 1,
Kent Overstreetcafe5632013-03-23 16:11:31 -0700171};
172
173enum closure_state {
174 /*
Kent Overstreetcafe5632013-03-23 16:11:31 -0700175 * CLOSURE_WAITING: Set iff the closure is on a waitlist. Must be set by
176 * the thread that owns the closure, and cleared by the thread that's
177 * waking up the closure.
178 *
179 * CLOSURE_SLEEPING: Must be set before a thread uses a closure to sleep
180 * - indicates that cl->task is valid and closure_put() may wake it up.
181 * Only set or cleared by the thread that owns the closure.
182 *
Kent Overstreetcafe5632013-03-23 16:11:31 -0700183 * The rest are for debugging and don't affect behaviour:
184 *
185 * CLOSURE_RUNNING: Set when a closure is running (i.e. by
186 * closure_init() and when closure_put() runs then next function), and
187 * must be cleared before remaining hits 0. Primarily to help guard
188 * against incorrect usage and accidentally transferring references.
189 * continue_at() and closure_return() clear it for you, if you're doing
190 * something unusual you can use closure_set_dead() which also helps
191 * annotate where references are being transferred.
192 *
193 * CLOSURE_STACK: Sanity check - remaining should never hit 0 on a
194 * closure with this flag set
195 */
196
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700197 CLOSURE_BITS_START = (1 << 23),
198 CLOSURE_DESTRUCTOR = (1 << 23),
199 CLOSURE_WAITING = (1 << 25),
200 CLOSURE_SLEEPING = (1 << 27),
Kent Overstreetcafe5632013-03-23 16:11:31 -0700201 CLOSURE_RUNNING = (1 << 29),
202 CLOSURE_STACK = (1 << 31),
203};
204
205#define CLOSURE_GUARD_MASK \
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700206 ((CLOSURE_DESTRUCTOR|CLOSURE_WAITING|CLOSURE_SLEEPING| \
207 CLOSURE_RUNNING|CLOSURE_STACK) << 1)
Kent Overstreetcafe5632013-03-23 16:11:31 -0700208
209#define CLOSURE_REMAINING_MASK (CLOSURE_BITS_START - 1)
210#define CLOSURE_REMAINING_INITIALIZER (1|CLOSURE_RUNNING)
211
212struct closure {
213 union {
214 struct {
215 struct workqueue_struct *wq;
216 struct task_struct *task;
217 struct llist_node list;
218 closure_fn *fn;
219 };
220 struct work_struct work;
221 };
222
223 struct closure *parent;
224
225 atomic_t remaining;
226
227 enum closure_type type;
228
229#ifdef CONFIG_BCACHE_CLOSURES_DEBUG
230#define CLOSURE_MAGIC_DEAD 0xc054dead
231#define CLOSURE_MAGIC_ALIVE 0xc054a11e
232
233 unsigned magic;
234 struct list_head all;
235 unsigned long ip;
236 unsigned long waiting_on;
237#endif
238};
239
240struct closure_with_waitlist {
241 struct closure cl;
242 struct closure_waitlist wait;
243};
244
Kent Overstreetcafe5632013-03-23 16:11:31 -0700245extern unsigned invalid_closure_type(void);
246
247#define __CLOSURE_TYPE(cl, _t) \
248 __builtin_types_compatible_p(typeof(cl), struct _t) \
249 ? TYPE_ ## _t : \
250
251#define __closure_type(cl) \
252( \
253 __CLOSURE_TYPE(cl, closure) \
254 __CLOSURE_TYPE(cl, closure_with_waitlist) \
Kent Overstreetcafe5632013-03-23 16:11:31 -0700255 invalid_closure_type() \
256)
257
258void closure_sub(struct closure *cl, int v);
259void closure_put(struct closure *cl);
Kent Overstreetcafe5632013-03-23 16:11:31 -0700260void __closure_wake_up(struct closure_waitlist *list);
261bool closure_wait(struct closure_waitlist *list, struct closure *cl);
262void closure_sync(struct closure *cl);
263
264bool closure_trylock(struct closure *cl, struct closure *parent);
265void __closure_lock(struct closure *cl, struct closure *parent,
266 struct closure_waitlist *wait_list);
267
Kent Overstreetcafe5632013-03-23 16:11:31 -0700268#ifdef CONFIG_BCACHE_CLOSURES_DEBUG
269
Kent Overstreet07e86cc2013-03-25 11:46:43 -0700270void closure_debug_init(void);
Kent Overstreetcafe5632013-03-23 16:11:31 -0700271void closure_debug_create(struct closure *cl);
272void closure_debug_destroy(struct closure *cl);
273
274#else
275
Kent Overstreet07e86cc2013-03-25 11:46:43 -0700276static inline void closure_debug_init(void) {}
Kent Overstreetcafe5632013-03-23 16:11:31 -0700277static inline void closure_debug_create(struct closure *cl) {}
278static inline void closure_debug_destroy(struct closure *cl) {}
279
280#endif
281
282static inline void closure_set_ip(struct closure *cl)
283{
284#ifdef CONFIG_BCACHE_CLOSURES_DEBUG
285 cl->ip = _THIS_IP_;
286#endif
287}
288
289static inline void closure_set_ret_ip(struct closure *cl)
290{
291#ifdef CONFIG_BCACHE_CLOSURES_DEBUG
292 cl->ip = _RET_IP_;
293#endif
294}
295
296static inline void closure_get(struct closure *cl)
297{
298#ifdef CONFIG_BCACHE_CLOSURES_DEBUG
299 BUG_ON((atomic_inc_return(&cl->remaining) &
300 CLOSURE_REMAINING_MASK) <= 1);
301#else
302 atomic_inc(&cl->remaining);
303#endif
304}
305
306static inline void closure_set_stopped(struct closure *cl)
307{
308 atomic_sub(CLOSURE_RUNNING, &cl->remaining);
309}
310
Kent Overstreetcafe5632013-03-23 16:11:31 -0700311static inline bool closure_is_unlocked(struct closure *cl)
312{
313 return atomic_read(&cl->remaining) == -1;
314}
315
316static inline void do_closure_init(struct closure *cl, struct closure *parent,
317 bool running)
318{
Kent Overstreetcafe5632013-03-23 16:11:31 -0700319 cl->parent = parent;
320 if (parent)
321 closure_get(parent);
322
323 if (running) {
324 closure_debug_create(cl);
325 atomic_set(&cl->remaining, CLOSURE_REMAINING_INITIALIZER);
326 } else
327 atomic_set(&cl->remaining, -1);
328
329 closure_set_ip(cl);
330}
331
332/*
333 * Hack to get at the embedded closure if there is one, by doing an unsafe cast:
334 * the result of __closure_type() is thrown away, it's used merely for type
335 * checking.
336 */
337#define __to_internal_closure(cl) \
338({ \
339 BUILD_BUG_ON(__closure_type(*cl) > MAX_CLOSURE_TYPE); \
340 (struct closure *) cl; \
341})
342
343#define closure_init_type(cl, parent, running) \
344do { \
345 struct closure *_cl = __to_internal_closure(cl); \
346 _cl->type = __closure_type(*(cl)); \
347 do_closure_init(_cl, parent, running); \
348} while (0)
349
350/**
Kent Overstreetcafe5632013-03-23 16:11:31 -0700351 * closure_init() - Initialize a closure, setting the refcount to 1
352 * @cl: closure to initialize
353 * @parent: parent of the new closure. cl will take a refcount on it for its
354 * lifetime; may be NULL.
355 */
356#define closure_init(cl, parent) \
Kent Overstreeta5ae4302013-09-10 19:16:31 -0700357 closure_init_type(cl, parent, true)
Kent Overstreetcafe5632013-03-23 16:11:31 -0700358
359static inline void closure_init_stack(struct closure *cl)
360{
361 memset(cl, 0, sizeof(struct closure));
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700362 atomic_set(&cl->remaining, CLOSURE_REMAINING_INITIALIZER|CLOSURE_STACK);
Kent Overstreetcafe5632013-03-23 16:11:31 -0700363}
364
365/**
366 * closure_init_unlocked() - Initialize a closure but leave it unlocked.
367 * @cl: closure to initialize
368 *
369 * For when the closure will be used as a lock. The closure may not be used
370 * until after a closure_lock() or closure_trylock().
371 */
372#define closure_init_unlocked(cl) \
373do { \
374 memset((cl), 0, sizeof(*(cl))); \
375 closure_init_type(cl, NULL, false); \
376} while (0)
377
378/**
379 * closure_lock() - lock and initialize a closure.
380 * @cl: the closure to lock
381 * @parent: the new parent for this closure
382 *
383 * The closure must be of one of the types that has a waitlist (otherwise we
384 * wouldn't be able to sleep on contention).
385 *
386 * @parent has exactly the same meaning as in closure_init(); if non null, the
387 * closure will take a reference on @parent which will be released when it is
388 * unlocked.
389 */
390#define closure_lock(cl, parent) \
391 __closure_lock(__to_internal_closure(cl), parent, &(cl)->wait)
392
Kent Overstreetcafe5632013-03-23 16:11:31 -0700393static inline void __closure_end_sleep(struct closure *cl)
394{
395 __set_current_state(TASK_RUNNING);
396
397 if (atomic_read(&cl->remaining) & CLOSURE_SLEEPING)
398 atomic_sub(CLOSURE_SLEEPING, &cl->remaining);
399}
400
401static inline void __closure_start_sleep(struct closure *cl)
402{
403 closure_set_ip(cl);
404 cl->task = current;
405 set_current_state(TASK_UNINTERRUPTIBLE);
406
407 if (!(atomic_read(&cl->remaining) & CLOSURE_SLEEPING))
408 atomic_add(CLOSURE_SLEEPING, &cl->remaining);
409}
410
411/**
Kent Overstreetcafe5632013-03-23 16:11:31 -0700412 * closure_wake_up() - wake up all closures on a wait list.
413 */
414static inline void closure_wake_up(struct closure_waitlist *list)
415{
416 smp_mb();
417 __closure_wake_up(list);
418}
419
420/*
421 * Wait on an event, synchronously or asynchronously - analogous to wait_event()
422 * but for closures.
423 *
424 * The loop is oddly structured so as to avoid a race; we must check the
425 * condition again after we've added ourself to the waitlist. We know if we were
426 * already on the waitlist because closure_wait() returns false; thus, we only
427 * schedule or break if closure_wait() returns false. If it returns true, we
428 * just loop again - rechecking the condition.
429 *
430 * The __closure_wake_up() is necessary because we may race with the event
431 * becoming true; i.e. we see event false -> wait -> recheck condition, but the
432 * thread that made the event true may have called closure_wake_up() before we
433 * added ourself to the wait list.
434 *
435 * We have to call closure_sync() at the end instead of just
436 * __closure_end_sleep() because a different thread might've called
437 * closure_wake_up() before us and gotten preempted before they dropped the
438 * refcount on our closure. If this was a stack allocated closure, that would be
439 * bad.
440 */
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700441#define closure_wait_event(list, cl, condition) \
Kent Overstreetcafe5632013-03-23 16:11:31 -0700442({ \
Kent Overstreetcafe5632013-03-23 16:11:31 -0700443 typeof(condition) ret; \
444 \
445 while (1) { \
446 ret = (condition); \
447 if (ret) { \
448 __closure_wake_up(list); \
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700449 closure_sync(cl); \
Kent Overstreetcafe5632013-03-23 16:11:31 -0700450 break; \
451 } \
452 \
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700453 __closure_start_sleep(cl); \
Kent Overstreetcafe5632013-03-23 16:11:31 -0700454 \
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700455 if (!closure_wait(list, cl)) \
Kent Overstreetcafe5632013-03-23 16:11:31 -0700456 schedule(); \
Kent Overstreetcafe5632013-03-23 16:11:31 -0700457 } \
458 \
459 ret; \
460})
461
Kent Overstreetfaadf0c2013-11-01 18:03:08 -0700462static inline void closure_queue(struct closure *cl)
463{
464 struct workqueue_struct *wq = cl->wq;
465 if (wq) {
466 INIT_WORK(&cl->work, cl->work.func);
467 BUG_ON(!queue_work(wq, &cl->work));
468 } else
469 cl->fn(cl);
470}
Kent Overstreetcafe5632013-03-23 16:11:31 -0700471
472static inline void set_closure_fn(struct closure *cl, closure_fn *fn,
473 struct workqueue_struct *wq)
474{
475 BUG_ON(object_is_on_stack(cl));
476 closure_set_ip(cl);
477 cl->fn = fn;
478 cl->wq = wq;
479 /* between atomic_dec() in closure_put() */
480 smp_mb__before_atomic_dec();
481}
482
483#define continue_at(_cl, _fn, _wq) \
484do { \
485 set_closure_fn(_cl, _fn, _wq); \
486 closure_sub(_cl, CLOSURE_RUNNING + 1); \
487 return; \
488} while (0)
489
490#define closure_return(_cl) continue_at((_cl), NULL, NULL)
491
492#define continue_at_nobarrier(_cl, _fn, _wq) \
493do { \
494 set_closure_fn(_cl, _fn, _wq); \
Kent Overstreeta34a8bf2013-10-24 17:07:04 -0700495 closure_queue(_cl); \
Kent Overstreetcafe5632013-03-23 16:11:31 -0700496 return; \
497} while (0)
498
499#define closure_return_with_destructor(_cl, _destructor) \
500do { \
501 set_closure_fn(_cl, _destructor, NULL); \
502 closure_sub(_cl, CLOSURE_RUNNING - CLOSURE_DESTRUCTOR + 1); \
503 return; \
504} while (0)
505
506static inline void closure_call(struct closure *cl, closure_fn fn,
507 struct workqueue_struct *wq,
508 struct closure *parent)
509{
510 closure_init(cl, parent);
511 continue_at_nobarrier(cl, fn, wq);
512}
513
514static inline void closure_trylock_call(struct closure *cl, closure_fn fn,
515 struct workqueue_struct *wq,
516 struct closure *parent)
517{
518 if (closure_trylock(cl, parent))
519 continue_at_nobarrier(cl, fn, wq);
520}
521
522#endif /* _LINUX_CLOSURE_H */