xref: /linux/kernel/sched/wait.c (revision 0694c8f58a541d56e3c71a9cacd24155f9463702)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Generic waiting primitives.
4  *
5  * (C) 2004 Nadia Yvette Chambers, Oracle
6  */
7 #include "sched.h"
8 #include <linux/wait_bit.h>
9 
10 void __init_waitqueue_head(struct wait_queue_head *wq_head, const char *name, struct lock_class_key *key)
11 {
12 	spin_lock_init(&wq_head->lock);
13 	lockdep_set_class_and_name(&wq_head->lock, key, name);
14 	INIT_LIST_HEAD(&wq_head->head);
15 }
16 
17 EXPORT_SYMBOL(__init_waitqueue_head);
18 
19 void add_wait_queue(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry)
20 {
21 	unsigned long flags;
22 
23 	wq_entry->flags &= ~WQ_FLAG_EXCLUSIVE;
24 	spin_lock_irqsave(&wq_head->lock, flags);
25 	__add_wait_queue(wq_head, wq_entry);
26 	spin_unlock_irqrestore(&wq_head->lock, flags);
27 }
28 EXPORT_SYMBOL(add_wait_queue);
29 
30 void add_wait_queue_exclusive(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry)
31 {
32 	unsigned long flags;
33 
34 	wq_entry->flags |= WQ_FLAG_EXCLUSIVE;
35 	spin_lock_irqsave(&wq_head->lock, flags);
36 	__add_wait_queue_entry_tail(wq_head, wq_entry);
37 	spin_unlock_irqrestore(&wq_head->lock, flags);
38 }
39 EXPORT_SYMBOL(add_wait_queue_exclusive);
40 
41 void add_wait_queue_priority(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry)
42 {
43 	unsigned long flags;
44 
45 	wq_entry->flags |= WQ_FLAG_PRIORITY;
46 	spin_lock_irqsave(&wq_head->lock, flags);
47 	__add_wait_queue(wq_head, wq_entry);
48 	spin_unlock_irqrestore(&wq_head->lock, flags);
49 }
50 EXPORT_SYMBOL_GPL(add_wait_queue_priority);
51 
52 int add_wait_queue_priority_exclusive(struct wait_queue_head *wq_head,
53 				      struct wait_queue_entry *wq_entry)
54 {
55 	struct list_head *head = &wq_head->head;
56 
57 	guard(spinlock_irqsave)(&wq_head->lock);
58 
59 	if (!list_empty(head) &&
60 	    (list_first_entry(head, typeof(*wq_entry), entry)->flags & WQ_FLAG_PRIORITY))
61 		return -EBUSY;
62 
63 	wq_entry->flags |= WQ_FLAG_EXCLUSIVE | WQ_FLAG_PRIORITY;
64 	list_add(&wq_entry->entry, head);
65 	return 0;
66 }
67 EXPORT_SYMBOL_GPL(add_wait_queue_priority_exclusive);
68 
69 void remove_wait_queue(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry)
70 {
71 	unsigned long flags;
72 
73 	spin_lock_irqsave(&wq_head->lock, flags);
74 	__remove_wait_queue(wq_head, wq_entry);
75 	spin_unlock_irqrestore(&wq_head->lock, flags);
76 }
77 EXPORT_SYMBOL(remove_wait_queue);
78 
79 /*
80  * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
81  * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
82  * number) then we wake that number of exclusive tasks, and potentially all
83  * the non-exclusive tasks. Normally, exclusive tasks will be at the end of
84  * the list and any non-exclusive tasks will be woken first. A priority task
85  * may be at the head of the list, and can consume the event without any other
86  * tasks being woken if it's also an exclusive task.
87  *
88  * An exclusive waiter that returns >0 promises to handle the event. Pollers
89  * (EPOLLEXCLUSIVE) can't promise that, since userspace may never consume it.
90  * They use WQ_FLAG_POLL_EXCLUSIVE instead: only one of them is woken, but they
91  * never count against nr_exclusive or stop the walk.
92  *
93  * There are circumstances in which we can try to wake a task which has already
94  * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
95  * zero in this (rare) case, and we handle it by continuing to scan the queue.
96  */
97 static int __wake_up_common(struct wait_queue_head *wq_head, unsigned int mode,
98 			int nr_exclusive, int wake_flags, void *key)
99 {
100 	wait_queue_entry_t *curr, *next;
101 	bool poll_woken = false;
102 
103 	lockdep_assert_held(&wq_head->lock);
104 
105 	list_for_each_entry_safe(curr, next, &wq_head->head, entry) {
106 		unsigned flags = curr->flags;
107 		int ret;
108 
109 		if ((flags & WQ_FLAG_POLL_EXCLUSIVE) && poll_woken)
110 			continue;
111 		ret = curr->func(curr, mode, wake_flags, key);
112 		if (ret < 0)
113 			break;
114 		if (!ret)
115 			continue;
116 		if (flags & WQ_FLAG_POLL_EXCLUSIVE)
117 			poll_woken = nr_exclusive > 0;
118 		else if ((flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
119 			break;
120 	}
121 
122 	return nr_exclusive;
123 }
124 
125 static int __wake_up_common_lock(struct wait_queue_head *wq_head, unsigned int mode,
126 			int nr_exclusive, int wake_flags, void *key)
127 {
128 	unsigned long flags;
129 	int remaining;
130 
131 	spin_lock_irqsave(&wq_head->lock, flags);
132 	remaining = __wake_up_common(wq_head, mode, nr_exclusive, wake_flags,
133 			key);
134 	spin_unlock_irqrestore(&wq_head->lock, flags);
135 
136 	return nr_exclusive - remaining;
137 }
138 
139 /**
140  * __wake_up - wake up threads blocked on a waitqueue.
141  * @wq_head: the waitqueue
142  * @mode: which threads
143  * @nr_exclusive: how many wake-one or wake-many threads to wake up
144  * @key: is directly passed to the wakeup function
145  *
146  * If this function wakes up a task, it executes a full memory barrier
147  * before accessing the task state.  Returns the number of exclusive
148  * tasks that were awaken.
149  */
150 int __wake_up(struct wait_queue_head *wq_head, unsigned int mode,
151 	      int nr_exclusive, void *key)
152 {
153 	return __wake_up_common_lock(wq_head, mode, nr_exclusive, 0, key);
154 }
155 EXPORT_SYMBOL(__wake_up);
156 
157 void __wake_up_on_current_cpu(struct wait_queue_head *wq_head, unsigned int mode, void *key)
158 {
159 	__wake_up_common_lock(wq_head, mode, 1, WF_CURRENT_CPU, key);
160 }
161 
162 /*
163  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
164  */
165 void __wake_up_locked(struct wait_queue_head *wq_head, unsigned int mode, int nr)
166 {
167 	__wake_up_common(wq_head, mode, nr, 0, NULL);
168 }
169 EXPORT_SYMBOL_GPL(__wake_up_locked);
170 
171 void __wake_up_locked_key(struct wait_queue_head *wq_head, unsigned int mode, void *key)
172 {
173 	__wake_up_common(wq_head, mode, 1, 0, key);
174 }
175 EXPORT_SYMBOL_GPL(__wake_up_locked_key);
176 
177 /**
178  * __wake_up_sync_key - wake up threads blocked on a waitqueue.
179  * @wq_head: the waitqueue
180  * @mode: which threads
181  * @key: opaque value to be passed to wakeup targets
182  *
183  * Passes WF_SYNC to waitqueue wake functions. The default wake function
184  * forwards it to the scheduler; see WF_SYNC for the hint's semantics.
185  *
186  * If this function wakes up a task, it executes a full memory barrier
187  * before accessing the task state.
188  */
189 void __wake_up_sync_key(struct wait_queue_head *wq_head, unsigned int mode,
190 			void *key)
191 {
192 	if (unlikely(!wq_head))
193 		return;
194 
195 	__wake_up_common_lock(wq_head, mode, 1, WF_SYNC, key);
196 }
197 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
198 
199 /**
200  * __wake_up_locked_sync_key - wake up a thread blocked on a locked waitqueue.
201  * @wq_head: the waitqueue
202  * @mode: which threads
203  * @key: opaque value to be passed to wakeup targets
204  *
205  * Same as __wake_up_sync_key(), but called with @wq_head->lock held.
206  */
207 void __wake_up_locked_sync_key(struct wait_queue_head *wq_head,
208 			       unsigned int mode, void *key)
209 {
210         __wake_up_common(wq_head, mode, 1, WF_SYNC, key);
211 }
212 EXPORT_SYMBOL_GPL(__wake_up_locked_sync_key);
213 
214 /*
215  * __wake_up_sync - see __wake_up_sync_key()
216  */
217 void __wake_up_sync(struct wait_queue_head *wq_head, unsigned int mode)
218 {
219 	__wake_up_sync_key(wq_head, mode, NULL);
220 }
221 EXPORT_SYMBOL_GPL(__wake_up_sync);	/* For internal use only */
222 
223 void __wake_up_pollfree(struct wait_queue_head *wq_head)
224 {
225 	__wake_up(wq_head, TASK_NORMAL, 0, poll_to_key(EPOLLHUP | POLLFREE));
226 	/* POLLFREE must have cleared the queue. */
227 	WARN_ON_ONCE(waitqueue_active(wq_head));
228 }
229 
230 /*
231  * Note: we use "set_current_state()" _after_ the wait-queue add,
232  * because we need a memory barrier there on SMP, so that any
233  * wake-function that tests for the wait-queue being active
234  * will be guaranteed to see waitqueue addition _or_ subsequent
235  * tests in this thread will see the wakeup having taken place.
236  *
237  * The spin_unlock() itself is semi-permeable and only protects
238  * one way (it only protects stuff inside the critical region and
239  * stops them from bleeding out - it would still allow subsequent
240  * loads to move into the critical region).
241  */
242 void
243 prepare_to_wait(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry, int state)
244 {
245 	unsigned long flags;
246 
247 	wq_entry->flags &= ~WQ_FLAG_EXCLUSIVE;
248 	spin_lock_irqsave(&wq_head->lock, flags);
249 	if (list_empty(&wq_entry->entry))
250 		__add_wait_queue(wq_head, wq_entry);
251 	set_current_state(state);
252 	spin_unlock_irqrestore(&wq_head->lock, flags);
253 }
254 EXPORT_SYMBOL(prepare_to_wait);
255 
256 /* Returns true if we are the first waiter in the queue, false otherwise. */
257 bool
258 prepare_to_wait_exclusive(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry, int state)
259 {
260 	unsigned long flags;
261 	bool was_empty = false;
262 
263 	wq_entry->flags |= WQ_FLAG_EXCLUSIVE;
264 	spin_lock_irqsave(&wq_head->lock, flags);
265 	if (list_empty(&wq_entry->entry)) {
266 		was_empty = list_empty(&wq_head->head);
267 		__add_wait_queue_entry_tail(wq_head, wq_entry);
268 	}
269 	set_current_state(state);
270 	spin_unlock_irqrestore(&wq_head->lock, flags);
271 	return was_empty;
272 }
273 EXPORT_SYMBOL(prepare_to_wait_exclusive);
274 
275 void init_wait_entry(struct wait_queue_entry *wq_entry, int flags)
276 {
277 	wq_entry->flags = flags;
278 	wq_entry->private = current;
279 	wq_entry->func = autoremove_wake_function;
280 	INIT_LIST_HEAD(&wq_entry->entry);
281 }
282 EXPORT_SYMBOL(init_wait_entry);
283 
284 long prepare_to_wait_event(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry, int state)
285 {
286 	unsigned long flags;
287 	long ret = 0;
288 
289 	spin_lock_irqsave(&wq_head->lock, flags);
290 	if (signal_pending_state(state, current)) {
291 		/*
292 		 * Exclusive waiter must not fail if it was selected by wakeup,
293 		 * it should "consume" the condition we were waiting for.
294 		 *
295 		 * The caller will recheck the condition and return success if
296 		 * we were already woken up, we can not miss the event because
297 		 * wakeup locks/unlocks the same wq_head->lock.
298 		 *
299 		 * But we need to ensure that set-condition + wakeup after that
300 		 * can't see us, it should wake up another exclusive waiter if
301 		 * we fail.
302 		 */
303 		list_del_init(&wq_entry->entry);
304 		ret = -ERESTARTSYS;
305 	} else {
306 		if (list_empty(&wq_entry->entry)) {
307 			if (wq_entry->flags & WQ_FLAG_EXCLUSIVE)
308 				__add_wait_queue_entry_tail(wq_head, wq_entry);
309 			else
310 				__add_wait_queue(wq_head, wq_entry);
311 		}
312 		set_current_state(state);
313 	}
314 	spin_unlock_irqrestore(&wq_head->lock, flags);
315 
316 	return ret;
317 }
318 EXPORT_SYMBOL(prepare_to_wait_event);
319 
320 /*
321  * Note! These two wait functions are entered with the
322  * wait-queue lock held (and interrupts off in the _irq
323  * case), so there is no race with testing the wakeup
324  * condition in the caller before they add the wait
325  * entry to the wake queue.
326  */
327 int do_wait_intr(wait_queue_head_t *wq, wait_queue_entry_t *wait)
328 {
329 	if (likely(list_empty(&wait->entry)))
330 		__add_wait_queue_entry_tail(wq, wait);
331 
332 	set_current_state(TASK_INTERRUPTIBLE);
333 	if (signal_pending(current))
334 		return -ERESTARTSYS;
335 
336 	spin_unlock(&wq->lock);
337 	schedule();
338 	spin_lock(&wq->lock);
339 
340 	return 0;
341 }
342 EXPORT_SYMBOL(do_wait_intr);
343 
344 int do_wait_intr_irq(wait_queue_head_t *wq, wait_queue_entry_t *wait)
345 {
346 	if (likely(list_empty(&wait->entry)))
347 		__add_wait_queue_entry_tail(wq, wait);
348 
349 	set_current_state(TASK_INTERRUPTIBLE);
350 	if (signal_pending(current))
351 		return -ERESTARTSYS;
352 
353 	spin_unlock_irq(&wq->lock);
354 	schedule();
355 	spin_lock_irq(&wq->lock);
356 
357 	return 0;
358 }
359 EXPORT_SYMBOL(do_wait_intr_irq);
360 
361 /**
362  * finish_wait - clean up after waiting in a queue
363  * @wq_head: waitqueue waited on
364  * @wq_entry: wait descriptor
365  *
366  * Sets current thread back to running state and removes
367  * the wait descriptor from the given waitqueue if still
368  * queued.
369  */
370 void finish_wait(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry)
371 {
372 	unsigned long flags;
373 
374 	__set_current_state(TASK_RUNNING);
375 	/*
376 	 * We can check for list emptiness outside the lock
377 	 * IFF:
378 	 *  - we use the "careful" check that verifies both
379 	 *    the next and prev pointers, so that there cannot
380 	 *    be any half-pending updates in progress on other
381 	 *    CPU's that we haven't seen yet (and that might
382 	 *    still change the stack area.
383 	 * and
384 	 *  - all other users take the lock (ie we can only
385 	 *    have _one_ other CPU that looks at or modifies
386 	 *    the list).
387 	 */
388 	if (!list_empty_careful(&wq_entry->entry)) {
389 		spin_lock_irqsave(&wq_head->lock, flags);
390 		list_del_init(&wq_entry->entry);
391 		spin_unlock_irqrestore(&wq_head->lock, flags);
392 	}
393 }
394 EXPORT_SYMBOL(finish_wait);
395 
396 int autoremove_wake_function(struct wait_queue_entry *wq_entry, unsigned mode, int sync, void *key)
397 {
398 	int ret = default_wake_function(wq_entry, mode, sync, key);
399 
400 	if (ret)
401 		list_del_init_careful(&wq_entry->entry);
402 
403 	return ret;
404 }
405 EXPORT_SYMBOL(autoremove_wake_function);
406 
407 /*
408  * DEFINE_WAIT_FUNC(wait, woken_wake_func);
409  *
410  * add_wait_queue(&wq_head, &wait);
411  * for (;;) {
412  *     if (condition)
413  *         break;
414  *
415  *     // in wait_woken()			// in woken_wake_function()
416  *
417  *     p->state = mode;				wq_entry->flags |= WQ_FLAG_WOKEN;
418  *     smp_mb(); // A				try_to_wake_up():
419  *     if (!(wq_entry->flags & WQ_FLAG_WOKEN))	   <full barrier>
420  *         schedule()				   if (p->state & mode)
421  *     p->state = TASK_RUNNING;			      p->state = TASK_RUNNING;
422  *     wq_entry->flags &= ~WQ_FLAG_WOKEN;	~~~~~~~~~~~~~~~~~~
423  *     smp_mb(); // B				condition = true;
424  * }						smp_mb(); // C
425  * remove_wait_queue(&wq_head, &wait);		wq_entry->flags |= WQ_FLAG_WOKEN;
426  */
427 long wait_woken(struct wait_queue_entry *wq_entry, unsigned mode, long timeout)
428 {
429 	/*
430 	 * The below executes an smp_mb(), which matches with the full barrier
431 	 * executed by the try_to_wake_up() in woken_wake_function() such that
432 	 * either we see the store to wq_entry->flags in woken_wake_function()
433 	 * or woken_wake_function() sees our store to current->state.
434 	 */
435 	set_current_state(mode); /* A */
436 	if (!(wq_entry->flags & WQ_FLAG_WOKEN) && !kthread_should_stop_or_park())
437 		timeout = schedule_timeout(timeout);
438 	__set_current_state(TASK_RUNNING);
439 
440 	/*
441 	 * The below executes an smp_mb(), which matches with the smp_mb() (C)
442 	 * in woken_wake_function() such that either we see the wait condition
443 	 * being true or the store to wq_entry->flags in woken_wake_function()
444 	 * follows ours in the coherence order.
445 	 */
446 	smp_store_mb(wq_entry->flags, wq_entry->flags & ~WQ_FLAG_WOKEN); /* B */
447 
448 	return timeout;
449 }
450 EXPORT_SYMBOL(wait_woken);
451 
452 int woken_wake_function(struct wait_queue_entry *wq_entry, unsigned mode, int sync, void *key)
453 {
454 	/* Pairs with the smp_store_mb() in wait_woken(). */
455 	smp_mb(); /* C */
456 	wq_entry->flags |= WQ_FLAG_WOKEN;
457 
458 	return default_wake_function(wq_entry, mode, sync, key);
459 }
460 EXPORT_SYMBOL(woken_wake_function);
461 
462 int woken_wake_bit_function(struct wait_queue_entry *wq_entry, unsigned mode, int sync, void *arg)
463 {
464 	struct wait_bit_key *key = __var_wake_key(wq_entry, arg);
465 	if (!key)
466 		return 0;
467 
468 	/* Pairs with the smp_store_mb() in wait_woken(). */
469 	smp_mb(); /* C */
470 	wq_entry->flags |= WQ_FLAG_WOKEN;
471 
472 	return default_wake_function(wq_entry, mode, sync, key);
473 }
474 EXPORT_SYMBOL(woken_wake_bit_function);
475