xref: /linux/kernel/futex/requeue.c (revision 59fff63cc2b75dcfe08f9eeb4b2187d73e53843d)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 #include <linux/sched/signal.h>
4 
5 #include "futex.h"
6 #include "../locking/rtmutex_common.h"
7 
8 /*
9  * On PREEMPT_RT, the hash bucket lock is a 'sleeping' spinlock with an
10  * underlying rtmutex. The task which is about to be requeued could have
11  * just woken up (timeout, signal). After the wake up the task has to
12  * acquire hash bucket lock, which is held by the requeue code.  As a task
13  * can only be blocked on _ONE_ rtmutex at a time, the proxy lock blocking
14  * and the hash bucket lock blocking would collide and corrupt state.
15  *
16  * On !PREEMPT_RT this is not a problem and everything could be serialized
17  * on hash bucket lock, but aside of having the benefit of common code,
18  * this allows to avoid doing the requeue when the task is already on the
19  * way out and taking the hash bucket lock of the original uaddr1 when the
20  * requeue has been completed.
21  *
22  * The following state transitions are valid:
23  *
24  * On the waiter side:
25  *   Q_REQUEUE_PI_NONE		-> Q_REQUEUE_PI_IGNORE
26  *   Q_REQUEUE_PI_IN_PROGRESS	-> Q_REQUEUE_PI_WAIT
27  *
28  * On the requeue side:
29  *   Q_REQUEUE_PI_NONE		-> Q_REQUEUE_PI_INPROGRESS
30  *   Q_REQUEUE_PI_IN_PROGRESS	-> Q_REQUEUE_PI_DONE/LOCKED
31  *   Q_REQUEUE_PI_IN_PROGRESS	-> Q_REQUEUE_PI_NONE (requeue failed)
32  *   Q_REQUEUE_PI_WAIT		-> Q_REQUEUE_PI_DONE/LOCKED
33  *   Q_REQUEUE_PI_WAIT		-> Q_REQUEUE_PI_IGNORE (requeue failed)
34  *
35  * The requeue side ignores a waiter with state Q_REQUEUE_PI_IGNORE as this
36  * signals that the waiter is already on the way out. It also means that
37  * the waiter is still on the 'wait' futex, i.e. uaddr1.
38  *
39  * The waiter side signals early wakeup to the requeue side either through
40  * setting state to Q_REQUEUE_PI_IGNORE or to Q_REQUEUE_PI_WAIT depending
41  * on the current state. In case of Q_REQUEUE_PI_IGNORE it can immediately
42  * proceed to take the hash bucket lock of uaddr1. If it set state to WAIT,
43  * which means the wakeup is interleaving with a requeue in progress it has
44  * to wait for the requeue side to change the state. Either to DONE/LOCKED
45  * or to IGNORE. DONE/LOCKED means the waiter q is now on the uaddr2 futex
46  * and either blocked (DONE) or has acquired it (LOCKED). IGNORE is set by
47  * the requeue side when the requeue attempt failed via deadlock detection
48  * and therefore the waiter q is still on the uaddr1 futex.
49  */
50 enum {
51 	Q_REQUEUE_PI_NONE		=  0,
52 	Q_REQUEUE_PI_IGNORE,
53 	Q_REQUEUE_PI_IN_PROGRESS,
54 	Q_REQUEUE_PI_WAIT,
55 	Q_REQUEUE_PI_DONE,
56 	Q_REQUEUE_PI_LOCKED,
57 };
58 
59 const struct futex_q futex_q_init = {
60 	/* list gets initialized in futex_queue()*/
61 	.key		= FUTEX_KEY_INIT,
62 	.bitset		= FUTEX_BITSET_MATCH_ANY,
63 	.requeue_state	= ATOMIC_INIT(Q_REQUEUE_PI_NONE),
64 };
65 
66 /**
67  * requeue_futex() - Requeue a futex_q from one hb to another
68  * @q:		the futex_q to requeue
69  * @hb1:	the source hash_bucket
70  * @hb2:	the target hash_bucket
71  * @key2:	the new key for the requeued futex_q
72  */
73 static inline
74 void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
75 		   struct futex_hash_bucket *hb2, union futex_key *key2)
76 {
77 
78 	/*
79 	 * If key1 and key2 hash to the same bucket, no need to
80 	 * requeue.
81 	 */
82 	if (likely(&hb1->chain != &hb2->chain)) {
83 		plist_del(&q->list, &hb1->chain);
84 		futex_hb_waiters_dec(hb1);
85 		futex_hb_waiters_inc(hb2);
86 		plist_add(&q->list, &hb2->chain);
87 		q->lock_ptr = &hb2->lock;
88 	}
89 	q->key = *key2;
90 }
91 
92 static inline bool futex_requeue_pi_prepare(struct futex_q *q,
93 					    struct futex_pi_state *pi_state)
94 {
95 	int old, new;
96 
97 	/*
98 	 * Set state to Q_REQUEUE_PI_IN_PROGRESS unless an early wakeup has
99 	 * already set Q_REQUEUE_PI_IGNORE to signal that requeue should
100 	 * ignore the waiter.
101 	 */
102 	old = atomic_read_acquire(&q->requeue_state);
103 	do {
104 		if (old == Q_REQUEUE_PI_IGNORE)
105 			return false;
106 
107 		/*
108 		 * futex_proxy_trylock_atomic() might have set it to
109 		 * IN_PROGRESS and a interleaved early wake to WAIT.
110 		 *
111 		 * It was considered to have an extra state for that
112 		 * trylock, but that would just add more conditionals
113 		 * all over the place for a dubious value.
114 		 */
115 		if (old != Q_REQUEUE_PI_NONE)
116 			break;
117 
118 		new = Q_REQUEUE_PI_IN_PROGRESS;
119 	} while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
120 
121 	q->pi_state = pi_state;
122 	return true;
123 }
124 
125 static inline void futex_requeue_pi_complete(struct futex_q *q, int locked)
126 {
127 	int old, new;
128 
129 	old = atomic_read_acquire(&q->requeue_state);
130 	do {
131 		if (old == Q_REQUEUE_PI_IGNORE)
132 			return;
133 
134 		if (locked >= 0) {
135 			/* Requeue succeeded. Set DONE or LOCKED */
136 			WARN_ON_ONCE(old != Q_REQUEUE_PI_IN_PROGRESS &&
137 				     old != Q_REQUEUE_PI_WAIT);
138 			new = Q_REQUEUE_PI_DONE + locked;
139 		} else if (old == Q_REQUEUE_PI_IN_PROGRESS) {
140 			/* Deadlock, no early wakeup interleave */
141 			new = Q_REQUEUE_PI_NONE;
142 		} else {
143 			/* Deadlock, early wakeup interleave. */
144 			WARN_ON_ONCE(old != Q_REQUEUE_PI_WAIT);
145 			new = Q_REQUEUE_PI_IGNORE;
146 		}
147 	} while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
148 
149 #ifdef CONFIG_PREEMPT_RT
150 	/* If the waiter interleaved with the requeue let it know */
151 	if (unlikely(old == Q_REQUEUE_PI_WAIT))
152 		rcuwait_wake_up(&q->requeue_wait);
153 #endif
154 }
155 
156 static inline int futex_requeue_pi_wakeup_sync(struct futex_q *q)
157 {
158 	int old, new;
159 
160 	old = atomic_read_acquire(&q->requeue_state);
161 	do {
162 		/* Is requeue done already? */
163 		if (old >= Q_REQUEUE_PI_DONE)
164 			return old;
165 
166 		/*
167 		 * If not done, then tell the requeue code to either ignore
168 		 * the waiter or to wake it up once the requeue is done.
169 		 */
170 		new = Q_REQUEUE_PI_WAIT;
171 		if (old == Q_REQUEUE_PI_NONE)
172 			new = Q_REQUEUE_PI_IGNORE;
173 	} while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
174 
175 	/* If the requeue was in progress, wait for it to complete */
176 	if (old == Q_REQUEUE_PI_IN_PROGRESS) {
177 #ifdef CONFIG_PREEMPT_RT
178 		rcuwait_wait_event(&q->requeue_wait,
179 				   atomic_read(&q->requeue_state) != Q_REQUEUE_PI_WAIT,
180 				   TASK_UNINTERRUPTIBLE);
181 #else
182 		(void)atomic_cond_read_relaxed(&q->requeue_state, VAL != Q_REQUEUE_PI_WAIT);
183 #endif
184 	}
185 
186 	/*
187 	 * Requeue is now either prohibited or complete. Reread state
188 	 * because during the wait above it might have changed. Nothing
189 	 * will modify q->requeue_state after this point.
190 	 */
191 	return atomic_read(&q->requeue_state);
192 }
193 
194 /**
195  * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
196  * @q:		the futex_q
197  * @key:	the key of the requeue target futex
198  * @hb:		the hash_bucket of the requeue target futex
199  *
200  * During futex_requeue, with requeue_pi=1, it is possible to acquire the
201  * target futex if it is uncontended or via a lock steal.
202  *
203  * 1) Set @q::key to the requeue target futex key so the waiter can detect
204  *    the wakeup on the right futex.
205  *
206  * 2) Dequeue @q from the hash bucket.
207  *
208  * 3) Set @q::rt_waiter to NULL so the woken up task can detect atomic lock
209  *    acquisition.
210  *
211  * 4) Set the q->lock_ptr to the requeue target hb->lock for the case that
212  *    the waiter has to fixup the pi state.
213  *
214  * 5) Complete the requeue state so the waiter can make progress. After
215  *    this point the waiter task can return from the syscall immediately in
216  *    case that the pi state does not have to be fixed up.
217  *
218  * 6) Wake the waiter task.
219  *
220  * Must be called with both q->lock_ptr and hb->lock held.
221  */
222 static inline
223 void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
224 			   struct futex_hash_bucket *hb)
225 {
226 	q->key = *key;
227 
228 	__futex_unqueue(q);
229 
230 	WARN_ON(!q->rt_waiter);
231 	q->rt_waiter = NULL;
232 
233 	q->lock_ptr = &hb->lock;
234 
235 	/* Signal locked state to the waiter */
236 	futex_requeue_pi_complete(q, 1);
237 	wake_up_state(q->task, TASK_NORMAL);
238 }
239 
240 /**
241  * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
242  * @pifutex:		the user address of the to futex
243  * @hb1:		the from futex hash bucket, must be locked by the caller
244  * @hb2:		the to futex hash bucket, must be locked by the caller
245  * @key1:		the from futex key
246  * @key2:		the to futex key
247  * @ps:			address to store the pi_state pointer
248  * @exiting:		Pointer to store the task pointer of the owner task
249  *			which is in the middle of exiting
250  * @set_waiters:	force setting the FUTEX_WAITERS bit (1) or not (0)
251  *
252  * Try and get the lock on behalf of the top waiter if we can do it atomically.
253  * Wake the top waiter if we succeed.  If the caller specified set_waiters,
254  * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
255  * hb1 and hb2 must be held by the caller.
256  *
257  * @exiting is only set when the return value is -EBUSY. If so, this holds
258  * a refcount on the exiting task on return and the caller needs to drop it
259  * after waiting for the exit to complete.
260  *
261  * Return:
262  *  -  0 - failed to acquire the lock atomically;
263  *  - >0 - acquired the lock, return value is vpid of the top_waiter
264  *  - <0 - error
265  */
266 static int
267 futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1,
268 			   struct futex_hash_bucket *hb2, union futex_key *key1,
269 			   union futex_key *key2, struct futex_pi_state **ps,
270 			   struct task_struct **exiting, int set_waiters)
271 {
272 	struct futex_q *top_waiter;
273 	u32 curval;
274 	int ret;
275 
276 	if (futex_get_value_locked(&curval, pifutex))
277 		return -EFAULT;
278 
279 	if (unlikely(should_fail_futex(true)))
280 		return -EFAULT;
281 
282 	/*
283 	 * Find the top_waiter and determine if there are additional waiters.
284 	 * If the caller intends to requeue more than 1 waiter to pifutex,
285 	 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
286 	 * as we have means to handle the possible fault.  If not, don't set
287 	 * the bit unnecessarily as it will force the subsequent unlock to enter
288 	 * the kernel.
289 	 */
290 	top_waiter = futex_top_waiter(hb1, key1);
291 
292 	/* There are no waiters, nothing for us to do. */
293 	if (!top_waiter)
294 		return 0;
295 
296 	/*
297 	 * Ensure that this is a waiter sitting in futex_wait_requeue_pi()
298 	 * and waiting on the 'waitqueue' futex which is always !PI.
299 	 */
300 	if (!top_waiter->rt_waiter || top_waiter->pi_state)
301 		return -EINVAL;
302 
303 	/* Ensure we requeue to the expected futex. */
304 	if (!futex_match(top_waiter->requeue_pi_key, key2))
305 		return -EINVAL;
306 
307 	/* Ensure that this does not race against an early wakeup */
308 	if (!futex_requeue_pi_prepare(top_waiter, NULL))
309 		return -EAGAIN;
310 
311 	/*
312 	 * Try to take the lock for top_waiter and set the FUTEX_WAITERS bit
313 	 * in the contended case or if @set_waiters is true.
314 	 *
315 	 * In the contended case PI state is attached to the lock owner. If
316 	 * the user space lock can be acquired then PI state is attached to
317 	 * the new owner (@top_waiter->task) when @set_waiters is true.
318 	 */
319 	ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
320 				   exiting, set_waiters);
321 	if (ret == 1) {
322 		/*
323 		 * Lock was acquired in user space and PI state was
324 		 * attached to @top_waiter->task. That means state is fully
325 		 * consistent and the waiter can return to user space
326 		 * immediately after the wakeup.
327 		 */
328 		requeue_pi_wake_futex(top_waiter, key2, hb2);
329 	} else if (ret < 0) {
330 		/* Rewind top_waiter::requeue_state */
331 		futex_requeue_pi_complete(top_waiter, ret);
332 	} else {
333 		/*
334 		 * futex_lock_pi_atomic() did not acquire the user space
335 		 * futex, but managed to establish the proxy lock and pi
336 		 * state. top_waiter::requeue_state cannot be fixed up here
337 		 * because the waiter is not enqueued on the rtmutex
338 		 * yet. This is handled at the callsite depending on the
339 		 * result of rt_mutex_start_proxy_lock() which is
340 		 * guaranteed to be reached with this function returning 0.
341 		 */
342 	}
343 	return ret;
344 }
345 
346 /**
347  * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
348  * @uaddr1:	source futex user address
349  * @flags1:	futex flags (FLAGS_SHARED, etc.)
350  * @uaddr2:	target futex user address
351  * @flags2:	futex flags (FLAGS_SHARED, etc.)
352  * @nr_wake:	number of waiters to wake (must be 1 for requeue_pi)
353  * @nr_requeue:	number of waiters to requeue (0-INT_MAX)
354  * @cmpval:	@uaddr1 expected value (or %NULL)
355  * @requeue_pi:	if we are attempting to requeue from a non-pi futex to a
356  *		pi futex (pi to pi requeue is not supported)
357  *
358  * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
359  * uaddr2 atomically on behalf of the top waiter.
360  *
361  * Return:
362  *  - >=0 - on success, the number of tasks requeued or woken;
363  *  -  <0 - on error
364  */
365 int futex_requeue(u32 __user *uaddr1, unsigned int flags1,
366 		  u32 __user *uaddr2, unsigned int flags2,
367 		  int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi)
368 {
369 	union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
370 	int task_count = 0, ret;
371 	struct futex_pi_state *pi_state = NULL;
372 	struct futex_hash_bucket *hb1, *hb2;
373 	struct futex_q *this, *next;
374 	DEFINE_WAKE_Q(wake_q);
375 
376 	if (nr_wake < 0 || nr_requeue < 0)
377 		return -EINVAL;
378 
379 	/*
380 	 * When PI not supported: return -ENOSYS if requeue_pi is true,
381 	 * consequently the compiler knows requeue_pi is always false past
382 	 * this point which will optimize away all the conditional code
383 	 * further down.
384 	 */
385 	if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
386 		return -ENOSYS;
387 
388 	if (requeue_pi) {
389 		/*
390 		 * Requeue PI only works on two distinct uaddrs. This
391 		 * check is only valid for private futexes. See below.
392 		 */
393 		if (uaddr1 == uaddr2)
394 			return -EINVAL;
395 
396 		/*
397 		 * futex_requeue() allows the caller to define the number
398 		 * of waiters to wake up via the @nr_wake argument. With
399 		 * REQUEUE_PI, waking up more than one waiter is creating
400 		 * more problems than it solves. Waking up a waiter makes
401 		 * only sense if the PI futex @uaddr2 is uncontended as
402 		 * this allows the requeue code to acquire the futex
403 		 * @uaddr2 before waking the waiter. The waiter can then
404 		 * return to user space without further action. A secondary
405 		 * wakeup would just make the futex_wait_requeue_pi()
406 		 * handling more complex, because that code would have to
407 		 * look up pi_state and do more or less all the handling
408 		 * which the requeue code has to do for the to be requeued
409 		 * waiters. So restrict the number of waiters to wake to
410 		 * one, and only wake it up when the PI futex is
411 		 * uncontended. Otherwise requeue it and let the unlock of
412 		 * the PI futex handle the wakeup.
413 		 *
414 		 * All REQUEUE_PI users, e.g. pthread_cond_signal() and
415 		 * pthread_cond_broadcast() must use nr_wake=1.
416 		 */
417 		if (nr_wake != 1)
418 			return -EINVAL;
419 
420 		/*
421 		 * requeue_pi requires a pi_state, try to allocate it now
422 		 * without any locks in case it fails.
423 		 */
424 		if (refill_pi_state_cache())
425 			return -ENOMEM;
426 	}
427 
428 retry:
429 	ret = get_futex_key(uaddr1, flags1, &key1, FUTEX_READ);
430 	if (unlikely(ret != 0))
431 		return ret;
432 	ret = get_futex_key(uaddr2, flags2, &key2,
433 			    requeue_pi ? FUTEX_WRITE : FUTEX_READ);
434 	if (unlikely(ret != 0))
435 		return ret;
436 
437 	/*
438 	 * The check above which compares uaddrs is not sufficient for
439 	 * shared futexes. We need to compare the keys:
440 	 */
441 	if (requeue_pi && futex_match(&key1, &key2))
442 		return -EINVAL;
443 
444 	hb1 = futex_hash(&key1);
445 	hb2 = futex_hash(&key2);
446 
447 retry_private:
448 	futex_hb_waiters_inc(hb2);
449 	double_lock_hb(hb1, hb2);
450 
451 	if (likely(cmpval != NULL)) {
452 		u32 curval;
453 
454 		ret = futex_get_value_locked(&curval, uaddr1);
455 
456 		if (unlikely(ret)) {
457 			double_unlock_hb(hb1, hb2);
458 			futex_hb_waiters_dec(hb2);
459 
460 			ret = get_user(curval, uaddr1);
461 			if (ret)
462 				return ret;
463 
464 			if (!(flags1 & FLAGS_SHARED))
465 				goto retry_private;
466 
467 			goto retry;
468 		}
469 		if (curval != *cmpval) {
470 			ret = -EAGAIN;
471 			goto out_unlock;
472 		}
473 	}
474 
475 	if (requeue_pi) {
476 		struct task_struct *exiting = NULL;
477 
478 		/*
479 		 * Attempt to acquire uaddr2 and wake the top waiter. If we
480 		 * intend to requeue waiters, force setting the FUTEX_WAITERS
481 		 * bit.  We force this here where we are able to easily handle
482 		 * faults rather in the requeue loop below.
483 		 *
484 		 * Updates topwaiter::requeue_state if a top waiter exists.
485 		 */
486 		ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
487 						 &key2, &pi_state,
488 						 &exiting, nr_requeue);
489 
490 		/*
491 		 * At this point the top_waiter has either taken uaddr2 or
492 		 * is waiting on it. In both cases pi_state has been
493 		 * established and an initial refcount on it. In case of an
494 		 * error there's nothing.
495 		 *
496 		 * The top waiter's requeue_state is up to date:
497 		 *
498 		 *  - If the lock was acquired atomically (ret == 1), then
499 		 *    the state is Q_REQUEUE_PI_LOCKED.
500 		 *
501 		 *    The top waiter has been dequeued and woken up and can
502 		 *    return to user space immediately. The kernel/user
503 		 *    space state is consistent. In case that there must be
504 		 *    more waiters requeued the WAITERS bit in the user
505 		 *    space futex is set so the top waiter task has to go
506 		 *    into the syscall slowpath to unlock the futex. This
507 		 *    will block until this requeue operation has been
508 		 *    completed and the hash bucket locks have been
509 		 *    dropped.
510 		 *
511 		 *  - If the trylock failed with an error (ret < 0) then
512 		 *    the state is either Q_REQUEUE_PI_NONE, i.e. "nothing
513 		 *    happened", or Q_REQUEUE_PI_IGNORE when there was an
514 		 *    interleaved early wakeup.
515 		 *
516 		 *  - If the trylock did not succeed (ret == 0) then the
517 		 *    state is either Q_REQUEUE_PI_IN_PROGRESS or
518 		 *    Q_REQUEUE_PI_WAIT if an early wakeup interleaved.
519 		 *    This will be cleaned up in the loop below, which
520 		 *    cannot fail because futex_proxy_trylock_atomic() did
521 		 *    the same sanity checks for requeue_pi as the loop
522 		 *    below does.
523 		 */
524 		switch (ret) {
525 		case 0:
526 			/* We hold a reference on the pi state. */
527 			break;
528 
529 		case 1:
530 			/*
531 			 * futex_proxy_trylock_atomic() acquired the user space
532 			 * futex. Adjust task_count.
533 			 */
534 			task_count++;
535 			ret = 0;
536 			break;
537 
538 		/*
539 		 * If the above failed, then pi_state is NULL and
540 		 * waiter::requeue_state is correct.
541 		 */
542 		case -EFAULT:
543 			double_unlock_hb(hb1, hb2);
544 			futex_hb_waiters_dec(hb2);
545 			ret = fault_in_user_writeable(uaddr2);
546 			if (!ret)
547 				goto retry;
548 			return ret;
549 		case -EBUSY:
550 		case -EAGAIN:
551 			/*
552 			 * Two reasons for this:
553 			 * - EBUSY: Owner is exiting and we just wait for the
554 			 *   exit to complete.
555 			 * - EAGAIN: The user space value changed.
556 			 */
557 			double_unlock_hb(hb1, hb2);
558 			futex_hb_waiters_dec(hb2);
559 			/*
560 			 * Handle the case where the owner is in the middle of
561 			 * exiting. Wait for the exit to complete otherwise
562 			 * this task might loop forever, aka. live lock.
563 			 */
564 			wait_for_owner_exiting(ret, exiting);
565 			cond_resched();
566 			goto retry;
567 		default:
568 			goto out_unlock;
569 		}
570 	}
571 
572 	plist_for_each_entry_safe(this, next, &hb1->chain, list) {
573 		if (task_count - nr_wake >= nr_requeue)
574 			break;
575 
576 		if (!futex_match(&this->key, &key1))
577 			continue;
578 
579 		/*
580 		 * FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI should always
581 		 * be paired with each other and no other futex ops.
582 		 *
583 		 * We should never be requeueing a futex_q with a pi_state,
584 		 * which is awaiting a futex_unlock_pi().
585 		 */
586 		if ((requeue_pi && !this->rt_waiter) ||
587 		    (!requeue_pi && this->rt_waiter) ||
588 		    this->pi_state) {
589 			ret = -EINVAL;
590 			break;
591 		}
592 
593 		/* Plain futexes just wake or requeue and are done */
594 		if (!requeue_pi) {
595 			if (++task_count <= nr_wake)
596 				futex_wake_mark(&wake_q, this);
597 			else
598 				requeue_futex(this, hb1, hb2, &key2);
599 			continue;
600 		}
601 
602 		/* Ensure we requeue to the expected futex for requeue_pi. */
603 		if (!futex_match(this->requeue_pi_key, &key2)) {
604 			ret = -EINVAL;
605 			break;
606 		}
607 
608 		/*
609 		 * Requeue nr_requeue waiters and possibly one more in the case
610 		 * of requeue_pi if we couldn't acquire the lock atomically.
611 		 *
612 		 * Prepare the waiter to take the rt_mutex. Take a refcount
613 		 * on the pi_state and store the pointer in the futex_q
614 		 * object of the waiter.
615 		 */
616 		get_pi_state(pi_state);
617 
618 		/* Don't requeue when the waiter is already on the way out. */
619 		if (!futex_requeue_pi_prepare(this, pi_state)) {
620 			/*
621 			 * Early woken waiter signaled that it is on the
622 			 * way out. Drop the pi_state reference and try the
623 			 * next waiter. @this->pi_state is still NULL.
624 			 */
625 			put_pi_state(pi_state);
626 			continue;
627 		}
628 
629 		ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
630 						this->rt_waiter,
631 						this->task);
632 
633 		if (ret == 1) {
634 			/*
635 			 * We got the lock. We do neither drop the refcount
636 			 * on pi_state nor clear this->pi_state because the
637 			 * waiter needs the pi_state for cleaning up the
638 			 * user space value. It will drop the refcount
639 			 * after doing so. this::requeue_state is updated
640 			 * in the wakeup as well.
641 			 */
642 			requeue_pi_wake_futex(this, &key2, hb2);
643 			task_count++;
644 		} else if (!ret) {
645 			/* Waiter is queued, move it to hb2 */
646 			requeue_futex(this, hb1, hb2, &key2);
647 			futex_requeue_pi_complete(this, 0);
648 			task_count++;
649 		} else {
650 			/*
651 			 * rt_mutex_start_proxy_lock() detected a potential
652 			 * deadlock when we tried to queue that waiter.
653 			 * Drop the pi_state reference which we took above
654 			 * and remove the pointer to the state from the
655 			 * waiters futex_q object.
656 			 */
657 			this->pi_state = NULL;
658 			put_pi_state(pi_state);
659 			futex_requeue_pi_complete(this, ret);
660 			/*
661 			 * We stop queueing more waiters and let user space
662 			 * deal with the mess.
663 			 */
664 			break;
665 		}
666 	}
667 
668 	/*
669 	 * We took an extra initial reference to the pi_state in
670 	 * futex_proxy_trylock_atomic(). We need to drop it here again.
671 	 */
672 	put_pi_state(pi_state);
673 
674 out_unlock:
675 	double_unlock_hb(hb1, hb2);
676 	wake_up_q(&wake_q);
677 	futex_hb_waiters_dec(hb2);
678 	return ret ? ret : task_count;
679 }
680 
681 /**
682  * handle_early_requeue_pi_wakeup() - Handle early wakeup on the initial futex
683  * @hb:		the hash_bucket futex_q was original enqueued on
684  * @q:		the futex_q woken while waiting to be requeued
685  * @timeout:	the timeout associated with the wait (NULL if none)
686  *
687  * Determine the cause for the early wakeup.
688  *
689  * Return:
690  *  -EWOULDBLOCK or -ETIMEDOUT or -ERESTARTNOINTR
691  */
692 static inline
693 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
694 				   struct futex_q *q,
695 				   struct hrtimer_sleeper *timeout)
696 {
697 	int ret;
698 
699 	/*
700 	 * With the hb lock held, we avoid races while we process the wakeup.
701 	 * We only need to hold hb (and not hb2) to ensure atomicity as the
702 	 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
703 	 * It can't be requeued from uaddr2 to something else since we don't
704 	 * support a PI aware source futex for requeue.
705 	 */
706 	WARN_ON_ONCE(&hb->lock != q->lock_ptr);
707 
708 	/*
709 	 * We were woken prior to requeue by a timeout or a signal.
710 	 * Unqueue the futex_q and determine which it was.
711 	 */
712 	plist_del(&q->list, &hb->chain);
713 	futex_hb_waiters_dec(hb);
714 
715 	/* Handle spurious wakeups gracefully */
716 	ret = -EWOULDBLOCK;
717 	if (timeout && !timeout->task)
718 		ret = -ETIMEDOUT;
719 	else if (signal_pending(current))
720 		ret = -ERESTARTNOINTR;
721 	return ret;
722 }
723 
724 /**
725  * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
726  * @uaddr:	the futex we initially wait on (non-pi)
727  * @flags:	futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
728  *		the same type, no requeueing from private to shared, etc.
729  * @val:	the expected value of uaddr
730  * @abs_time:	absolute timeout
731  * @bitset:	32 bit wakeup bitset set by userspace, defaults to all
732  * @uaddr2:	the pi futex we will take prior to returning to user-space
733  *
734  * The caller will wait on uaddr and will be requeued by futex_requeue() to
735  * uaddr2 which must be PI aware and unique from uaddr.  Normal wakeup will wake
736  * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
737  * userspace.  This ensures the rt_mutex maintains an owner when it has waiters;
738  * without one, the pi logic would not know which task to boost/deboost, if
739  * there was a need to.
740  *
741  * We call schedule in futex_wait_queue() when we enqueue and return there
742  * via the following--
743  * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
744  * 2) wakeup on uaddr2 after a requeue
745  * 3) signal
746  * 4) timeout
747  *
748  * If 3, cleanup and return -ERESTARTNOINTR.
749  *
750  * If 2, we may then block on trying to take the rt_mutex and return via:
751  * 5) successful lock
752  * 6) signal
753  * 7) timeout
754  * 8) other lock acquisition failure
755  *
756  * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
757  *
758  * If 4 or 7, we cleanup and return with -ETIMEDOUT.
759  *
760  * Return:
761  *  -  0 - On success;
762  *  - <0 - On error
763  */
764 int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
765 			  u32 val, ktime_t *abs_time, u32 bitset,
766 			  u32 __user *uaddr2)
767 {
768 	struct hrtimer_sleeper timeout, *to;
769 	struct rt_mutex_waiter rt_waiter;
770 	struct futex_hash_bucket *hb;
771 	union futex_key key2 = FUTEX_KEY_INIT;
772 	struct futex_q q = futex_q_init;
773 	struct rt_mutex_base *pi_mutex;
774 	int res, ret;
775 
776 	if (!IS_ENABLED(CONFIG_FUTEX_PI))
777 		return -ENOSYS;
778 
779 	if (uaddr == uaddr2)
780 		return -EINVAL;
781 
782 	if (!bitset)
783 		return -EINVAL;
784 
785 	to = futex_setup_timer(abs_time, &timeout, flags,
786 			       current->timer_slack_ns);
787 
788 	/*
789 	 * The waiter is allocated on our stack, manipulated by the requeue
790 	 * code while we sleep on uaddr.
791 	 */
792 	rt_mutex_init_waiter(&rt_waiter);
793 
794 	ret = get_futex_key(uaddr2, flags, &key2, FUTEX_WRITE);
795 	if (unlikely(ret != 0))
796 		goto out;
797 
798 	q.bitset = bitset;
799 	q.rt_waiter = &rt_waiter;
800 	q.requeue_pi_key = &key2;
801 
802 	/*
803 	 * Prepare to wait on uaddr. On success, it holds hb->lock and q
804 	 * is initialized.
805 	 */
806 	ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
807 	if (ret)
808 		goto out;
809 
810 	/*
811 	 * The check above which compares uaddrs is not sufficient for
812 	 * shared futexes. We need to compare the keys:
813 	 */
814 	if (futex_match(&q.key, &key2)) {
815 		futex_q_unlock(hb);
816 		ret = -EINVAL;
817 		goto out;
818 	}
819 
820 	/* Queue the futex_q, drop the hb lock, wait for wakeup. */
821 	futex_wait_queue(hb, &q, to);
822 
823 	switch (futex_requeue_pi_wakeup_sync(&q)) {
824 	case Q_REQUEUE_PI_IGNORE:
825 		/* The waiter is still on uaddr1 */
826 		spin_lock(&hb->lock);
827 		ret = handle_early_requeue_pi_wakeup(hb, &q, to);
828 		spin_unlock(&hb->lock);
829 		break;
830 
831 	case Q_REQUEUE_PI_LOCKED:
832 		/* The requeue acquired the lock */
833 		if (q.pi_state && (q.pi_state->owner != current)) {
834 			spin_lock(q.lock_ptr);
835 			ret = fixup_pi_owner(uaddr2, &q, true);
836 			/*
837 			 * Drop the reference to the pi state which the
838 			 * requeue_pi() code acquired for us.
839 			 */
840 			put_pi_state(q.pi_state);
841 			spin_unlock(q.lock_ptr);
842 			/*
843 			 * Adjust the return value. It's either -EFAULT or
844 			 * success (1) but the caller expects 0 for success.
845 			 */
846 			ret = ret < 0 ? ret : 0;
847 		}
848 		break;
849 
850 	case Q_REQUEUE_PI_DONE:
851 		/* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
852 		pi_mutex = &q.pi_state->pi_mutex;
853 		ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
854 
855 		/*
856 		 * See futex_unlock_pi()'s cleanup: comment.
857 		 */
858 		if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
859 			ret = 0;
860 
861 		spin_lock(q.lock_ptr);
862 		debug_rt_mutex_free_waiter(&rt_waiter);
863 		/*
864 		 * Fixup the pi_state owner and possibly acquire the lock if we
865 		 * haven't already.
866 		 */
867 		res = fixup_pi_owner(uaddr2, &q, !ret);
868 		/*
869 		 * If fixup_pi_owner() returned an error, propagate that.  If it
870 		 * acquired the lock, clear -ETIMEDOUT or -EINTR.
871 		 */
872 		if (res)
873 			ret = (res < 0) ? res : 0;
874 
875 		futex_unqueue_pi(&q);
876 		spin_unlock(q.lock_ptr);
877 
878 		if (ret == -EINTR) {
879 			/*
880 			 * We've already been requeued, but cannot restart
881 			 * by calling futex_lock_pi() directly. We could
882 			 * restart this syscall, but it would detect that
883 			 * the user space "val" changed and return
884 			 * -EWOULDBLOCK.  Save the overhead of the restart
885 			 * and return -EWOULDBLOCK directly.
886 			 */
887 			ret = -EWOULDBLOCK;
888 		}
889 		break;
890 	default:
891 		BUG();
892 	}
893 
894 out:
895 	if (to) {
896 		hrtimer_cancel(&to->timer);
897 		destroy_hrtimer_on_stack(&to->timer);
898 	}
899 	return ret;
900 }
901 
902